hip_filename
stringlengths
5
84
hip_content
stringlengths
79
9.69M
cuda_filename
stringlengths
4
83
cuda_content
stringlengths
19
9.69M
d585895f69dbe2eb4c419e22908206a237ca5c93.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "caffe2/core/context_gpu.h" #include "caffe2/image/transform_gpu.h" #include "caffe2/utils/conversions.h" /** * * Copyright (c) 2016, NVIDIA CORPORATION, All rights reserved * Distributed under 2-clause BSD license; see accompanying LICENSE file * **/ namespace caffe2 { namespace { // input in (int8, NHWC), output in (fp32, NCHW) template <typename In, typename Out> __global__ void transform_kernel( const int C, const int H, const int W, const float* mean, const float* std, const In* in, Out* out) { const auto n = blockIdx.x; const auto nStride = C*H*W; // pointers to data for this image const In *const input_ptr = &in[n*nStride]; Out *const output_ptr = &out[n*nStride]; // either read or write uncoalesced - try reading for (int c=0; c < C; ++c) { for (int h=threadIdx.y; h < H; h += blockDim.y) { for (int w=threadIdx.x; w < W; w += blockDim.x) { const int in_idx = c + C*w + C*W*h; // HWC const int out_idx = c*H*W + h*W + w; // CHW output_ptr[out_idx] = convert::To<float,Out>( (convert::To<In,float>(input_ptr[in_idx])-mean[c]) * std[c]); } } } } } template <typename T_IN, typename T_OUT, class Context> bool TransformOnGPU( Tensor& X, Tensor* Y, Tensor& mean, Tensor& std, Context* context) { const int N = X.dim32(0), C = X.dim32(3), H = X.dim32(1), W = X.dim32(2); auto* input_data = X.template data<T_IN>(); auto* output_data = Y->template mutable_data<T_OUT>(); hipLaunchKernelGGL(( transform_kernel< T_IN, T_OUT>), dim3(N), dim3(dim3(16, 16)), 0, context->cuda_stream(), C, H, W, mean.template data<float>(), std.template data<float>(), input_data, output_data); C10_HIP_KERNEL_LAUNCH_CHECK(); return true; }; template bool TransformOnGPU<uint8_t, float, CUDAContext>( Tensor& X, Tensor* Y, Tensor& mean, Tensor& std, CUDAContext* context); template bool TransformOnGPU<uint8_t, at::Half, CUDAContext>( Tensor& X, Tensor* Y, Tensor& mean, Tensor& std, CUDAContext* context); } // namespace caffe2
d585895f69dbe2eb4c419e22908206a237ca5c93.cu
#include "caffe2/core/context_gpu.h" #include "caffe2/image/transform_gpu.h" #include "caffe2/utils/conversions.h" /** * * Copyright (c) 2016, NVIDIA CORPORATION, All rights reserved * Distributed under 2-clause BSD license; see accompanying LICENSE file * **/ namespace caffe2 { namespace { // input in (int8, NHWC), output in (fp32, NCHW) template <typename In, typename Out> __global__ void transform_kernel( const int C, const int H, const int W, const float* mean, const float* std, const In* in, Out* out) { const auto n = blockIdx.x; const auto nStride = C*H*W; // pointers to data for this image const In *const input_ptr = &in[n*nStride]; Out *const output_ptr = &out[n*nStride]; // either read or write uncoalesced - try reading for (int c=0; c < C; ++c) { for (int h=threadIdx.y; h < H; h += blockDim.y) { for (int w=threadIdx.x; w < W; w += blockDim.x) { const int in_idx = c + C*w + C*W*h; // HWC const int out_idx = c*H*W + h*W + w; // CHW output_ptr[out_idx] = convert::To<float,Out>( (convert::To<In,float>(input_ptr[in_idx])-mean[c]) * std[c]); } } } } } template <typename T_IN, typename T_OUT, class Context> bool TransformOnGPU( Tensor& X, Tensor* Y, Tensor& mean, Tensor& std, Context* context) { const int N = X.dim32(0), C = X.dim32(3), H = X.dim32(1), W = X.dim32(2); auto* input_data = X.template data<T_IN>(); auto* output_data = Y->template mutable_data<T_OUT>(); transform_kernel< T_IN, T_OUT><<<N, dim3(16, 16), 0, context->cuda_stream()>>>( C, H, W, mean.template data<float>(), std.template data<float>(), input_data, output_data); C10_CUDA_KERNEL_LAUNCH_CHECK(); return true; }; template bool TransformOnGPU<uint8_t, float, CUDAContext>( Tensor& X, Tensor* Y, Tensor& mean, Tensor& std, CUDAContext* context); template bool TransformOnGPU<uint8_t, at::Half, CUDAContext>( Tensor& X, Tensor* Y, Tensor& mean, Tensor& std, CUDAContext* context); } // namespace caffe2
f26bc9f6e4e6644b4f8cd43379a882bf80dc02e8.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "bootstrap.cuh" #include "random_gen.cuh" #include <catboost/cuda/cuda_lib/kernel/arch.cuh> namespace NKernel { __global__ void PoissonBootstrapImpl(const float lambda, ui64* seeds, ui32 seedSize, float* weights, ui32 size) { seeds += blockIdx.x * blockDim.x + threadIdx.x; ui32 i = blockIdx.x * blockDim.x + threadIdx.x; ui64 s = seeds[0]; while (i < size) { float w = weights[i]; weights[i] = w * NextPoisson(&s, lambda); i += gridDim.x * blockDim.x; } seeds[0] = s; } __global__ void GammaBootstrapImpl(const float scale, const float shape, ui64* seeds, ui32 seedSize, float* weights, ui32 size) { ui32 i = blockIdx.x * blockDim.x + threadIdx.x; seeds += i; ui64 s = seeds[0]; while (i < size) { float w = weights[i]; weights[i] = w * NextGamma(&s, scale, shape); i += gridDim.x * blockDim.x; } seeds[0] = s; } __global__ void BayesianBootstrapImpl(ui64* seeds, ui32 seedSize, float* weights, ui32 size, float temperature) { seeds += blockIdx.x * blockDim.x + threadIdx.x; ui32 i = blockIdx.x * blockDim.x + threadIdx.x; ui64 s = seeds[0]; while (i < size) { float w = weights[i]; const float tmp = (-log(NextUniform(&s) + 1e-20f)); weights[i] = w * (temperature != 1.0f ? powf(tmp, temperature) : tmp); i += gridDim.x * blockDim.x; } seeds[0] = s; } __global__ void UniformBootstrapImpl(const float sampleRate, ui64* seeds, ui32 seedSize, float* weights, ui32 size) { ui32 i = blockIdx.x * blockDim.x + threadIdx.x; seeds += i; ui64 s = seeds[0]; while (i < size) { const float w = weights[i]; const float flag = (NextUniform(&s) < sampleRate) ? 1.0f : 0.0f; weights[i] = w * flag; i += gridDim.x * blockDim.x; } seeds[0] = s; } void PoissonBootstrap(const float lambda, ui64* seeds, ui32 seedsSize, float* weights, ui32 weighsSize, TCudaStream stream) { const ui32 blockSize = 256; const ui32 numBlocks = min(CeilDivide(seedsSize, blockSize), CeilDivide(weighsSize, blockSize)); hipLaunchKernelGGL(( PoissonBootstrapImpl), dim3(numBlocks), dim3(blockSize), 0, stream, lambda, seeds, seedsSize, weights, weighsSize); } void UniformBootstrap(const float sampleRate, ui64* seeds, ui32 seedSize, float* weights, ui32 size, TCudaStream stream) { const ui32 blockSize = 256; const ui32 numBlocks = min(CeilDivide(seedSize, blockSize), CeilDivide(size, blockSize)); hipLaunchKernelGGL(( UniformBootstrapImpl), dim3(numBlocks), dim3(blockSize), 0 , stream, sampleRate, seeds, seedSize, weights, size); } void BayesianBootstrap(ui64* seeds, ui32 seedSize, float* weights, ui32 size, float temperature, TCudaStream stream) { const ui32 blockSize = 256; const ui32 numBlocks = min(CeilDivide(seedSize, blockSize), CeilDivide(size, blockSize)); // GammaBootstrapImpl<<<numBlocks, blockSize, 0 , stream>>>(1.0f, 1.0f, seeds, seedSize, weights, size); hipLaunchKernelGGL(( BayesianBootstrapImpl), dim3(numBlocks), dim3(blockSize), 0 , stream, seeds, seedSize, weights, size, temperature); } }
f26bc9f6e4e6644b4f8cd43379a882bf80dc02e8.cu
#include "bootstrap.cuh" #include "random_gen.cuh" #include <catboost/cuda/cuda_lib/kernel/arch.cuh> namespace NKernel { __global__ void PoissonBootstrapImpl(const float lambda, ui64* seeds, ui32 seedSize, float* weights, ui32 size) { seeds += blockIdx.x * blockDim.x + threadIdx.x; ui32 i = blockIdx.x * blockDim.x + threadIdx.x; ui64 s = seeds[0]; while (i < size) { float w = weights[i]; weights[i] = w * NextPoisson(&s, lambda); i += gridDim.x * blockDim.x; } seeds[0] = s; } __global__ void GammaBootstrapImpl(const float scale, const float shape, ui64* seeds, ui32 seedSize, float* weights, ui32 size) { ui32 i = blockIdx.x * blockDim.x + threadIdx.x; seeds += i; ui64 s = seeds[0]; while (i < size) { float w = weights[i]; weights[i] = w * NextGamma(&s, scale, shape); i += gridDim.x * blockDim.x; } seeds[0] = s; } __global__ void BayesianBootstrapImpl(ui64* seeds, ui32 seedSize, float* weights, ui32 size, float temperature) { seeds += blockIdx.x * blockDim.x + threadIdx.x; ui32 i = blockIdx.x * blockDim.x + threadIdx.x; ui64 s = seeds[0]; while (i < size) { float w = weights[i]; const float tmp = (-log(NextUniform(&s) + 1e-20f)); weights[i] = w * (temperature != 1.0f ? powf(tmp, temperature) : tmp); i += gridDim.x * blockDim.x; } seeds[0] = s; } __global__ void UniformBootstrapImpl(const float sampleRate, ui64* seeds, ui32 seedSize, float* weights, ui32 size) { ui32 i = blockIdx.x * blockDim.x + threadIdx.x; seeds += i; ui64 s = seeds[0]; while (i < size) { const float w = weights[i]; const float flag = (NextUniform(&s) < sampleRate) ? 1.0f : 0.0f; weights[i] = w * flag; i += gridDim.x * blockDim.x; } seeds[0] = s; } void PoissonBootstrap(const float lambda, ui64* seeds, ui32 seedsSize, float* weights, ui32 weighsSize, TCudaStream stream) { const ui32 blockSize = 256; const ui32 numBlocks = min(CeilDivide(seedsSize, blockSize), CeilDivide(weighsSize, blockSize)); PoissonBootstrapImpl<<<numBlocks, blockSize, 0, stream>>>(lambda, seeds, seedsSize, weights, weighsSize); } void UniformBootstrap(const float sampleRate, ui64* seeds, ui32 seedSize, float* weights, ui32 size, TCudaStream stream) { const ui32 blockSize = 256; const ui32 numBlocks = min(CeilDivide(seedSize, blockSize), CeilDivide(size, blockSize)); UniformBootstrapImpl<<<numBlocks, blockSize, 0 , stream>>>(sampleRate, seeds, seedSize, weights, size); } void BayesianBootstrap(ui64* seeds, ui32 seedSize, float* weights, ui32 size, float temperature, TCudaStream stream) { const ui32 blockSize = 256; const ui32 numBlocks = min(CeilDivide(seedSize, blockSize), CeilDivide(size, blockSize)); // GammaBootstrapImpl<<<numBlocks, blockSize, 0 , stream>>>(1.0f, 1.0f, seeds, seedSize, weights, size); BayesianBootstrapImpl<<<numBlocks, blockSize, 0 , stream>>>(seeds, seedSize, weights, size, temperature); } }
c0c7c10dd9426391358f7f239e453fcf0074db38.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* -- MAGMA (version 1.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2011 @precisions normal d */ /* blk_M=64 blk_N=64 blk_K=16 nthd_x=64 nthd_y=4 */ #include "common_magma.h" #include "commonblas_d.h" #define magmablas_dgemm_fermi magmablas_dgemm texture<int2,1> tex_x_double_A; texture<int2,1> tex_x_double_B; static __inline__ __device__ double fetch_x_A(const int& i) { register int2 v = tex1Dfetch(tex_x_double_A, i); return __hiloint2double(v.y, v.x); } static __inline__ __device__ double fetch_x_B(const int& i) { register int2 v = tex1Dfetch(tex_x_double_B, i); return __hiloint2double(v.y, v.x); } extern "C" __global__ void fermiDgemm_v2_kernel_NN(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2 = idt%16; const int ty2 = idt/16; __shared__ double Abs[64][17]; __shared__ double Bb[16][65]; int tll = ty2; double xxA[4]; double xxB[4]; int trackA = offsetA + ibx +__mul24( ty2, lda) + tx2 ; A += trackA; int trackB = offsetB + tx2+ __mul24(iby + ty2 * 4, ldb ); B += trackB; #pragma unroll for(int y=0; y<4; y++) Abs[tx2+ y*16][ty2] = /* (tll<k)* */ fetch_x_A(trackA + y*16) ; #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4+y] = fetch_x_B( trackB + y * ldb) ; __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll+=16; A += lda *16 ; B += 16; trackA += 16*lda ; trackB += 16; #pragma unroll for( int y=0; y<4; y++) xxA[y] = /* (tll<k)* */ fetch_x_A(trackA + y*16); #pragma unroll for( int y=0; y<4; y++) xxB[y] = fetch_x_B( trackB + y*ldb); #pragma unroll for( int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2+y*16][j1] ; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2+y*16]; #pragma unroll for( int x=0; x<4; x++) { #pragma unroll for( int y=0; y<4; y++) { Cb[x*4+y] += Axs[x]*Bxp[y]; } } } __syncthreads(); #pragma unroll for(int y=0; y<4; y++) Abs[tx2+y*16][ty2] = xxA[y]; #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4 + y] = xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24 (ty2 + iby ,ldc); #pragma unroll for(int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1] ; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int x=0; x<4; x++) { #pragma unroll for( int y=0;y<4; y++) { Cb[x*4 + y] += Axs[x]*Bxp[y]; } } } int gy = iby + ty2; #pragma unroll for( int y=0;y<4;y++, gy+=16) { int gx = ibx + tx2; #pragma unroll for(int x=0;x<4;x++, gx+=16) { if (gx < m && gy < n) C[x*16] = alpha*Cb[y+x*4] + beta * C[x*16]; } C += ldc*16; } } extern "C" __global__ void fermiDgemm_v2_kernel_TN(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2 = idt%16; const int ty2 = idt/16; __shared__ double Bb[16][65]; __shared__ double Abs[64][17]; double xxA[4]; double xxB[4]; int trackA = offsetA + tx2 + __mul24( ibx + ty2*4, lda ); int trackB = offsetB + tx2 + __mul24( iby + ty2*4, ldb ); A+= trackA; B+= trackB; int tll = tx2; #pragma unroll for(int y=0; y<4; y++) Abs[ty2*4+y][tx2] = (tll<k)* fetch_x_A(trackA + y*lda); #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4+y] = /* (tll<k)* */ fetch_x_B( trackB + y*ldb ); __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll +=16; B += 16; A += 16 ; trackA+=16 ; trackB+=16; #pragma unroll for(int y=0; y<4; y++) xxA[y] = (tll<k)* fetch_x_A(trackA + y*lda); #pragma unroll for(int y=0; y<4; y++) xxB[y] = /* (tll<k)* */ fetch_x_B(trackB + y*ldb); #pragma unroll for(int j1=0;j1<16;j1++) { #pragma unroll for(int y=0; y<4; y++) Axs[y] = Abs[tx2+y*16][j1]; #pragma unroll for(int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2+y*16]; #pragma unroll for(int x=0; x<4; x++) { #pragma unroll for(int y=0; y<4; y++) { Cb[x*4+y] += Axs[x]*Bxp[y]; } } } __syncthreads(); #pragma unroll for(int y=0; y<4; y++) Abs[ty2*4+y][tx2] = xxA[y]; #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4+y] =xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24 (ty2 + iby ,ldc); #pragma unroll for(int j1=0; j1<16; j1++) { #pragma unroll for(int y=0; y<4; y++) Axs[y] = Abs[tx2+y*16][j1]; #pragma unroll for(int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2+y*16]; #pragma unroll for(int x=0; x<4; x++) { #pragma unroll for(int y=0; y<4; y++) { Cb[x*4+y] += Axs[x]*Bxp[y]; } } } int gy = iby+ty2; #pragma unroll for(int y=0;y<4;y++, gy+=16) { int gx = ibx+tx2; #pragma unroll for(int x=0;x<4;x++, gx+=16) { if (gx < m && gy < n) C[x*16] =alpha*Cb[y+x*4] + beta * C[x*16]; } C+=ldc*16; } } extern "C" __global__ void fermiDgemm_v2_kernel_TT(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2 = idt%16; const int ty2 = idt/16; __shared__ double Bb[16][65]; __shared__ double Abs[64][17]; double xxA[4]; double xxB[4]; int trackA = offsetA + __mul24( ibx + ty2, lda) + tx2; int trackB = offsetB + iby+ tx2 + __mul24(ty2, ldb); A += trackA; B += trackB; int tll = tx2; #pragma unroll for(int y=0; y<4; y++) Abs[ty2+16*y][tx2] = /* (tll<k)* */ fetch_x_A(trackA + lda*16*y); #pragma unroll for(int y=0; y<4; y++) Bb[ty2][tx2+16*y] = fetch_x_B(trackB+16*y); __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll+=16; A += 16; B += 16*ldb; trackA+=16; trackB+=16*ldb; #pragma unroll for( int y=0; y<4; y++) xxA[y] = /* (tll<k)* */ fetch_x_A(trackA + lda*y*16); #pragma unroll for( int y=0; y<4; y++) xxB[y] = fetch_x_B(trackB + 16*y); #pragma unroll for( int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1]; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0;y<4;y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } __syncthreads(); #pragma unroll for( int y=0; y<4; y++) Abs[ty2 + 16*y][tx2] = xxA[y]; #pragma unroll for( int y=0; y<4; y++) Bb[ty2][tx2+y*16] = xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24 (ty2 + iby ,ldc); #pragma unroll for( int j1=0; j1<16; j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1]; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0; y<4; y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } int gy = iby + ty2; #pragma unroll for( int y=0; y<4; y++, gy+=16) { int gx = ibx + tx2; #pragma unroll for(int x=0; x<4; x++, gx+=16) { if (gx < m && gy < n) C[x*16] = alpha*Cb[y+x*4] + beta * C[x*16]; } C+=ldc*16; } } extern "C" __global__ void fermiDgemm_v2_kernel_NT(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2= idt%16; const int ty2= idt/16; __shared__ double Bb[16][65]; __shared__ double Abs[64][17]; double xxA[4]; double xxB[4]; int trackA = offsetA + ibx +__mul24(ty2, lda) + tx2 ; int trackB = offsetB + iby + tx2 + __mul24(ty2, ldb); A+= trackA; B += trackB; int tll = ty2; #pragma unroll for(int y=0; y<4; y++) Abs[tx2+ y*16][ty2] = /* (tll<k)* */ fetch_x_A(trackA + y*16); #pragma unroll for(int y=0; y<4; y++) Bb[ty2][tx2+16*y] = /* (tll<k)* */ fetch_x_B(trackB+16*y); __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll += 16; A += lda *16 ; B += 16*ldb; trackA+=16*lda ; trackB+=16*ldb; #pragma unroll for( int y=0; y<4; y++) xxA[y] = /* (tll<k)* */ fetch_x_A(trackA + y*16); #pragma unroll for( int y=0; y<4; y++) xxB[y] = /* (tll<k)* */ fetch_x_B( trackB + 16*y); #pragma unroll for( int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1] ; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0; y<4; y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } __syncthreads(); #pragma unroll for( int y=0; y<4; y++) Abs[tx2 + y*16][ty2] = xxA[y]; #pragma unroll for( int y=0; y<4; y++) Bb[ty2][tx2+y*16] = xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24(ty2 + iby ,ldc); #pragma unroll for(int j1=0; j1<16; j1++) { #pragma unroll for( int y=0; y<4; y++) Bxp[y] = Bb[j1][ty2 + y*16]; #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1] ; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0;y<4;y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } int gy = iby + ty2; #pragma unroll for( int y=0; y<4; y++, gy+=16) { int gx = ibx + tx2; #pragma unroll for(int x=0; x<4; x++, gx+=16) { if (gx < m && gy < n) C[x*16] = alpha*Cb[y + x*4] + beta * C[x*16]; } C+=ldc*16; } } extern "C" void magmablas_dgemm_fermi( char TRANSA, char TRANSB, magma_int_t m , magma_int_t n , magma_int_t k , double alpha, const double *A, magma_int_t lda, const double *B, magma_int_t ldb, double beta, double *C, magma_int_t ldc ) { /* -- MAGMA (version 1.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2011 Purpose ======= DGEMM performs one of the matrix-matrix operations C := alpha*op( A )*op( B ) + beta*C, where op( X ) is one of op( X ) = X or op( X ) = X', alpha and beta are scalars, and A, B and C are matrices, with op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. Parameters ========== TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n', op( A ) = A. TRANSA = 'T' or 't', op( A ) = A'. TRANSA = 'C' or 'c', op( A ) = A'. Unchanged on exit. TRANSB - CHARACTER*1. On entry, TRANSB specifies the form of op( B ) to be used in the matrix multiplication as follows: TRANSB = 'N' or 'n', op( B ) = B. TRANSB = 'T' or 't', op( B ) = B'. TRANSB = 'C' or 'c', op( B ) = B'. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix op( A ) and of the matrix C. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix op( B ) and the number of columns of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry, K specifies the number of columns of the matrix op( A ) and the number of rows of the matrix op( B ). K must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, ka ), where ka is k when TRANSA = 'N' or 'n', and is m otherwise. Before entry with TRANSA = 'N' or 'n', the leading m by k part of the array A must contain the matrix A, otherwise the leading k by m part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANSA = 'N' or 'n' then LDA must be at least max( 1, m ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - DOUBLE PRECISION array of DIMENSION ( LDB, kb ), where kb is n when TRANSB = 'N' or 'n', and is k otherwise. Before entry with TRANSB = 'N' or 'n', the leading k by n part of the array B must contain the matrix B, otherwise the leading n by k part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANSB = 'N' or 'n' then LDB must be at least max( 1, k ), otherwise LDB must be at least max( 1, n ). Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then C need not be set on input. Unchanged on exit. C - DOUBLE PRECISION array of DIMENSION ( LDC, n ). Before entry, the leading m by n part of the array C must contain the matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the array C is overwritten by the m by n matrix ( alpha*op( A )*op( B ) + beta*C ). LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, m ). Unchanged on exit. ===================================================================== */ if (m<=0 || n<=0 || k<=0) return; size_t offsetA = 0; size_t offsetB = 0; int TransA = 1, TransB = 1; if (TRANSA == 'N' || TRANSA == 'n') TransA = 0; if (TRANSB == 'N' || TRANSB == 'n') TransB = 0; size_t sizeA = (size_t) lda * (size_t) (!TransA ? k : m); size_t sizeB = (size_t) ldb * (size_t) (!TransB ? n : k); // size_t CUBLAS_MAX_1DBUF_SIZE = ((1 << 27) - 512) / 2; size_t CUBLAS_MAX_1DBUF_SIZE = ((1 << 27) - 512); if (sizeA>=CUBLAS_MAX_1DBUF_SIZE || sizeB>=CUBLAS_MAX_1DBUF_SIZE ) { // printf("Exceeding texuture limit (CUBLAS_MAX_1DBUF_SIZE=%ld), using hipblasSgemm\n", CUBLAS_MAX_1DBUF_SIZE); hipblasDgemm(TRANSA, TRANSB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); return; } hipError_t errt; errt = hipBindTexture(&offsetA, tex_x_double_A, (int2 *)A, sizeA * sizeof(A[0])); if( errt != hipSuccess) { printf("cannot bind to texture\n"); return; } errt = hipBindTexture(&offsetB, tex_x_double_B, (int2 *)B, sizeB * sizeof(B[0])); if( errt != hipSuccess) { printf("cannot bind to texture\n"); return; } dim3 threads( 64, 4 ); dim3 grid(m/(64)+(m%(64)!=0),n/(64)+(n%(64)!=0)); offsetA = offsetA/sizeof(A[0]); offsetB = offsetB/sizeof(B[0]); if ( TransB ) if ( !TransA ) hipLaunchKernelGGL(( fermiDgemm_v2_kernel_NT), dim3(grid), dim3(threads), 0, magma_stream , C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); else hipLaunchKernelGGL(( fermiDgemm_v2_kernel_TT), dim3(grid), dim3(threads), 0, magma_stream , C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); else if ( !TransA ) hipLaunchKernelGGL(( fermiDgemm_v2_kernel_NN), dim3(grid), dim3(threads), 0, magma_stream , C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); else hipLaunchKernelGGL(( fermiDgemm_v2_kernel_TN), dim3(grid), dim3(threads), 0, magma_stream , C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); hipUnbindTexture ( tex_x_double_A ) ; hipUnbindTexture ( tex_x_double_B ) ; }
c0c7c10dd9426391358f7f239e453fcf0074db38.cu
/* -- MAGMA (version 1.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2011 @precisions normal d */ /* blk_M=64 blk_N=64 blk_K=16 nthd_x=64 nthd_y=4 */ #include "common_magma.h" #include "commonblas_d.h" #define magmablas_dgemm_fermi magmablas_dgemm texture<int2,1> tex_x_double_A; texture<int2,1> tex_x_double_B; static __inline__ __device__ double fetch_x_A(const int& i) { register int2 v = tex1Dfetch(tex_x_double_A, i); return __hiloint2double(v.y, v.x); } static __inline__ __device__ double fetch_x_B(const int& i) { register int2 v = tex1Dfetch(tex_x_double_B, i); return __hiloint2double(v.y, v.x); } extern "C" __global__ void fermiDgemm_v2_kernel_NN(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2 = idt%16; const int ty2 = idt/16; __shared__ double Abs[64][17]; __shared__ double Bb[16][65]; int tll = ty2; double xxA[4]; double xxB[4]; int trackA = offsetA + ibx +__mul24( ty2, lda) + tx2 ; A += trackA; int trackB = offsetB + tx2+ __mul24(iby + ty2 * 4, ldb ); B += trackB; #pragma unroll for(int y=0; y<4; y++) Abs[tx2+ y*16][ty2] = /* (tll<k)* */ fetch_x_A(trackA + y*16) ; #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4+y] = fetch_x_B( trackB + y * ldb) ; __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll+=16; A += lda *16 ; B += 16; trackA += 16*lda ; trackB += 16; #pragma unroll for( int y=0; y<4; y++) xxA[y] = /* (tll<k)* */ fetch_x_A(trackA + y*16); #pragma unroll for( int y=0; y<4; y++) xxB[y] = fetch_x_B( trackB + y*ldb); #pragma unroll for( int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2+y*16][j1] ; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2+y*16]; #pragma unroll for( int x=0; x<4; x++) { #pragma unroll for( int y=0; y<4; y++) { Cb[x*4+y] += Axs[x]*Bxp[y]; } } } __syncthreads(); #pragma unroll for(int y=0; y<4; y++) Abs[tx2+y*16][ty2] = xxA[y]; #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4 + y] = xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24 (ty2 + iby ,ldc); #pragma unroll for(int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1] ; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int x=0; x<4; x++) { #pragma unroll for( int y=0;y<4; y++) { Cb[x*4 + y] += Axs[x]*Bxp[y]; } } } int gy = iby + ty2; #pragma unroll for( int y=0;y<4;y++, gy+=16) { int gx = ibx + tx2; #pragma unroll for(int x=0;x<4;x++, gx+=16) { if (gx < m && gy < n) C[x*16] = alpha*Cb[y+x*4] + beta * C[x*16]; } C += ldc*16; } } extern "C" __global__ void fermiDgemm_v2_kernel_TN(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2 = idt%16; const int ty2 = idt/16; __shared__ double Bb[16][65]; __shared__ double Abs[64][17]; double xxA[4]; double xxB[4]; int trackA = offsetA + tx2 + __mul24( ibx + ty2*4, lda ); int trackB = offsetB + tx2 + __mul24( iby + ty2*4, ldb ); A+= trackA; B+= trackB; int tll = tx2; #pragma unroll for(int y=0; y<4; y++) Abs[ty2*4+y][tx2] = (tll<k)* fetch_x_A(trackA + y*lda); #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4+y] = /* (tll<k)* */ fetch_x_B( trackB + y*ldb ); __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll +=16; B += 16; A += 16 ; trackA+=16 ; trackB+=16; #pragma unroll for(int y=0; y<4; y++) xxA[y] = (tll<k)* fetch_x_A(trackA + y*lda); #pragma unroll for(int y=0; y<4; y++) xxB[y] = /* (tll<k)* */ fetch_x_B(trackB + y*ldb); #pragma unroll for(int j1=0;j1<16;j1++) { #pragma unroll for(int y=0; y<4; y++) Axs[y] = Abs[tx2+y*16][j1]; #pragma unroll for(int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2+y*16]; #pragma unroll for(int x=0; x<4; x++) { #pragma unroll for(int y=0; y<4; y++) { Cb[x*4+y] += Axs[x]*Bxp[y]; } } } __syncthreads(); #pragma unroll for(int y=0; y<4; y++) Abs[ty2*4+y][tx2] = xxA[y]; #pragma unroll for(int y=0; y<4; y++) Bb[tx2][ty2*4+y] =xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24 (ty2 + iby ,ldc); #pragma unroll for(int j1=0; j1<16; j1++) { #pragma unroll for(int y=0; y<4; y++) Axs[y] = Abs[tx2+y*16][j1]; #pragma unroll for(int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2+y*16]; #pragma unroll for(int x=0; x<4; x++) { #pragma unroll for(int y=0; y<4; y++) { Cb[x*4+y] += Axs[x]*Bxp[y]; } } } int gy = iby+ty2; #pragma unroll for(int y=0;y<4;y++, gy+=16) { int gx = ibx+tx2; #pragma unroll for(int x=0;x<4;x++, gx+=16) { if (gx < m && gy < n) C[x*16] =alpha*Cb[y+x*4] + beta * C[x*16]; } C+=ldc*16; } } extern "C" __global__ void fermiDgemm_v2_kernel_TT(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2 = idt%16; const int ty2 = idt/16; __shared__ double Bb[16][65]; __shared__ double Abs[64][17]; double xxA[4]; double xxB[4]; int trackA = offsetA + __mul24( ibx + ty2, lda) + tx2; int trackB = offsetB + iby+ tx2 + __mul24(ty2, ldb); A += trackA; B += trackB; int tll = tx2; #pragma unroll for(int y=0; y<4; y++) Abs[ty2+16*y][tx2] = /* (tll<k)* */ fetch_x_A(trackA + lda*16*y); #pragma unroll for(int y=0; y<4; y++) Bb[ty2][tx2+16*y] = fetch_x_B(trackB+16*y); __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll+=16; A += 16; B += 16*ldb; trackA+=16; trackB+=16*ldb; #pragma unroll for( int y=0; y<4; y++) xxA[y] = /* (tll<k)* */ fetch_x_A(trackA + lda*y*16); #pragma unroll for( int y=0; y<4; y++) xxB[y] = fetch_x_B(trackB + 16*y); #pragma unroll for( int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1]; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0;y<4;y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } __syncthreads(); #pragma unroll for( int y=0; y<4; y++) Abs[ty2 + 16*y][tx2] = xxA[y]; #pragma unroll for( int y=0; y<4; y++) Bb[ty2][tx2+y*16] = xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24 (ty2 + iby ,ldc); #pragma unroll for( int j1=0; j1<16; j1++) { #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1]; #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0; y<4; y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } int gy = iby + ty2; #pragma unroll for( int y=0; y<4; y++, gy+=16) { int gx = ibx + tx2; #pragma unroll for(int x=0; x<4; x++, gx+=16) { if (gx < m && gy < n) C[x*16] = alpha*Cb[y+x*4] + beta * C[x*16]; } C+=ldc*16; } } extern "C" __global__ void fermiDgemm_v2_kernel_NT(double *C, const double *A, const double *B, int m, int n, int k, int lda, int ldb, int ldc, double alpha, double beta, int offsetA, int offsetB) { const int tx = threadIdx.x; const int ty = threadIdx.y; const int iby = blockIdx.y * 64; const int ibx = blockIdx.x * 64; const int idt = ty * 64 + tx; const int tx2= idt%16; const int ty2= idt/16; __shared__ double Bb[16][65]; __shared__ double Abs[64][17]; double xxA[4]; double xxB[4]; int trackA = offsetA + ibx +__mul24(ty2, lda) + tx2 ; int trackB = offsetB + iby + tx2 + __mul24(ty2, ldb); A+= trackA; B += trackB; int tll = ty2; #pragma unroll for(int y=0; y<4; y++) Abs[tx2+ y*16][ty2] = /* (tll<k)* */ fetch_x_A(trackA + y*16); #pragma unroll for(int y=0; y<4; y++) Bb[ty2][tx2+16*y] = /* (tll<k)* */ fetch_x_B(trackB+16*y); __syncthreads(); double Axs[4]; double Bxp[4]; double Cb[16] = {0,0,0,0, 0,0,0,0, 0,0,0,0, 0,0,0,0}; int k1; for(k1=0; k1<(k-16); k1+=16) { tll += 16; A += lda *16 ; B += 16*ldb; trackA+=16*lda ; trackB+=16*ldb; #pragma unroll for( int y=0; y<4; y++) xxA[y] = /* (tll<k)* */ fetch_x_A(trackA + y*16); #pragma unroll for( int y=0; y<4; y++) xxB[y] = /* (tll<k)* */ fetch_x_B( trackB + 16*y); #pragma unroll for( int j1=0;j1<16;j1++) { #pragma unroll for( int y=0; y<4; y++) Bxp[y]= Bb[j1][ty2 + y*16]; #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1] ; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0; y<4; y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } __syncthreads(); #pragma unroll for( int y=0; y<4; y++) Abs[tx2 + y*16][ty2] = xxA[y]; #pragma unroll for( int y=0; y<4; y++) Bb[ty2][tx2+y*16] = xxB[y]; __syncthreads(); } C += tx2 + ibx + __mul24(ty2 + iby ,ldc); #pragma unroll for(int j1=0; j1<16; j1++) { #pragma unroll for( int y=0; y<4; y++) Bxp[y] = Bb[j1][ty2 + y*16]; #pragma unroll for( int y=0; y<4; y++) Axs[y] = Abs[tx2 + y*16][j1] ; #pragma unroll for( int x=0; x<4; x++) #pragma unroll for( int y=0;y<4;y++) Cb[x*4+y] += Axs[x]*Bxp[y]; } int gy = iby + ty2; #pragma unroll for( int y=0; y<4; y++, gy+=16) { int gx = ibx + tx2; #pragma unroll for(int x=0; x<4; x++, gx+=16) { if (gx < m && gy < n) C[x*16] = alpha*Cb[y + x*4] + beta * C[x*16]; } C+=ldc*16; } } extern "C" void magmablas_dgemm_fermi( char TRANSA, char TRANSB, magma_int_t m , magma_int_t n , magma_int_t k , double alpha, const double *A, magma_int_t lda, const double *B, magma_int_t ldb, double beta, double *C, magma_int_t ldc ) { /* -- MAGMA (version 1.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver November 2011 Purpose ======= DGEMM performs one of the matrix-matrix operations C := alpha*op( A )*op( B ) + beta*C, where op( X ) is one of op( X ) = X or op( X ) = X', alpha and beta are scalars, and A, B and C are matrices, with op( A ) an m by k matrix, op( B ) a k by n matrix and C an m by n matrix. Parameters ========== TRANSA - CHARACTER*1. On entry, TRANSA specifies the form of op( A ) to be used in the matrix multiplication as follows: TRANSA = 'N' or 'n', op( A ) = A. TRANSA = 'T' or 't', op( A ) = A'. TRANSA = 'C' or 'c', op( A ) = A'. Unchanged on exit. TRANSB - CHARACTER*1. On entry, TRANSB specifies the form of op( B ) to be used in the matrix multiplication as follows: TRANSB = 'N' or 'n', op( B ) = B. TRANSB = 'T' or 't', op( B ) = B'. TRANSB = 'C' or 'c', op( B ) = B'. Unchanged on exit. M - INTEGER. On entry, M specifies the number of rows of the matrix op( A ) and of the matrix C. M must be at least zero. Unchanged on exit. N - INTEGER. On entry, N specifies the number of columns of the matrix op( B ) and the number of columns of the matrix C. N must be at least zero. Unchanged on exit. K - INTEGER. On entry, K specifies the number of columns of the matrix op( A ) and the number of rows of the matrix op( B ). K must be at least zero. Unchanged on exit. ALPHA - DOUBLE PRECISION. On entry, ALPHA specifies the scalar alpha. Unchanged on exit. A - DOUBLE PRECISION array of DIMENSION ( LDA, ka ), where ka is k when TRANSA = 'N' or 'n', and is m otherwise. Before entry with TRANSA = 'N' or 'n', the leading m by k part of the array A must contain the matrix A, otherwise the leading k by m part of the array A must contain the matrix A. Unchanged on exit. LDA - INTEGER. On entry, LDA specifies the first dimension of A as declared in the calling (sub) program. When TRANSA = 'N' or 'n' then LDA must be at least max( 1, m ), otherwise LDA must be at least max( 1, k ). Unchanged on exit. B - DOUBLE PRECISION array of DIMENSION ( LDB, kb ), where kb is n when TRANSB = 'N' or 'n', and is k otherwise. Before entry with TRANSB = 'N' or 'n', the leading k by n part of the array B must contain the matrix B, otherwise the leading n by k part of the array B must contain the matrix B. Unchanged on exit. LDB - INTEGER. On entry, LDB specifies the first dimension of B as declared in the calling (sub) program. When TRANSB = 'N' or 'n' then LDB must be at least max( 1, k ), otherwise LDB must be at least max( 1, n ). Unchanged on exit. BETA - DOUBLE PRECISION. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then C need not be set on input. Unchanged on exit. C - DOUBLE PRECISION array of DIMENSION ( LDC, n ). Before entry, the leading m by n part of the array C must contain the matrix C, except when beta is zero, in which case C need not be set on entry. On exit, the array C is overwritten by the m by n matrix ( alpha*op( A )*op( B ) + beta*C ). LDC - INTEGER. On entry, LDC specifies the first dimension of C as declared in the calling (sub) program. LDC must be at least max( 1, m ). Unchanged on exit. ===================================================================== */ if (m<=0 || n<=0 || k<=0) return; size_t offsetA = 0; size_t offsetB = 0; int TransA = 1, TransB = 1; if (TRANSA == 'N' || TRANSA == 'n') TransA = 0; if (TRANSB == 'N' || TRANSB == 'n') TransB = 0; size_t sizeA = (size_t) lda * (size_t) (!TransA ? k : m); size_t sizeB = (size_t) ldb * (size_t) (!TransB ? n : k); // size_t CUBLAS_MAX_1DBUF_SIZE = ((1 << 27) - 512) / 2; size_t CUBLAS_MAX_1DBUF_SIZE = ((1 << 27) - 512); if (sizeA>=CUBLAS_MAX_1DBUF_SIZE || sizeB>=CUBLAS_MAX_1DBUF_SIZE ) { // printf("Exceeding texuture limit (CUBLAS_MAX_1DBUF_SIZE=%ld), using cublasSgemm\n", CUBLAS_MAX_1DBUF_SIZE); cublasDgemm(TRANSA, TRANSB, m, n, k, alpha, A, lda, B, ldb, beta, C, ldc); return; } cudaError_t errt; errt = cudaBindTexture(&offsetA, tex_x_double_A, (int2 *)A, sizeA * sizeof(A[0])); if( errt != cudaSuccess) { printf("cannot bind to texture\n"); return; } errt = cudaBindTexture(&offsetB, tex_x_double_B, (int2 *)B, sizeB * sizeof(B[0])); if( errt != cudaSuccess) { printf("cannot bind to texture\n"); return; } dim3 threads( 64, 4 ); dim3 grid(m/(64)+(m%(64)!=0),n/(64)+(n%(64)!=0)); offsetA = offsetA/sizeof(A[0]); offsetB = offsetB/sizeof(B[0]); if ( TransB ) if ( !TransA ) fermiDgemm_v2_kernel_NT<<< grid, threads, 0, magma_stream >>>(C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); else fermiDgemm_v2_kernel_TT<<< grid, threads, 0, magma_stream >>>(C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); else if ( !TransA ) fermiDgemm_v2_kernel_NN<<< grid, threads, 0, magma_stream >>>(C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); else fermiDgemm_v2_kernel_TN<<< grid, threads, 0, magma_stream >>>(C, A, B, m, n, k, lda, ldb, ldc, alpha, beta, (int)offsetA, (int)offsetB); cudaUnbindTexture ( tex_x_double_A ) ; cudaUnbindTexture ( tex_x_double_B ) ; }
d62419522e6078e86ebe46e2acedc9e33c393ebf.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void reduction_unrolling_blocks4(int * input, int * temp, int size) { int tid = threadIdx.x; int BLOCK_OFFSET = blockIdx.x * blockDim.x * 4; int index = BLOCK_OFFSET + tid; int * i_data = input + BLOCK_OFFSET; if ((index + 3 * blockDim.x) < size) { int a1 = input[index]; int a2 = input[index + blockDim.x]; int a3 = input[index+ 2* blockDim.x]; int a4 = input[index+ 3 *blockDim.x]; input[index] = a1 + a2 + a3 + a4; } __syncthreads(); for (int offset = blockDim.x / 2; offset > 0; offset = offset / 2) { if (tid < offset) { i_data[tid] += i_data[tid + offset]; } __syncthreads(); } if (tid == 0) { temp[blockIdx.x] = i_data[0]; } }
d62419522e6078e86ebe46e2acedc9e33c393ebf.cu
#include "includes.h" __global__ void reduction_unrolling_blocks4(int * input, int * temp, int size) { int tid = threadIdx.x; int BLOCK_OFFSET = blockIdx.x * blockDim.x * 4; int index = BLOCK_OFFSET + tid; int * i_data = input + BLOCK_OFFSET; if ((index + 3 * blockDim.x) < size) { int a1 = input[index]; int a2 = input[index + blockDim.x]; int a3 = input[index+ 2* blockDim.x]; int a4 = input[index+ 3 *blockDim.x]; input[index] = a1 + a2 + a3 + a4; } __syncthreads(); for (int offset = blockDim.x / 2; offset > 0; offset = offset / 2) { if (tid < offset) { i_data[tid] += i_data[tid + offset]; } __syncthreads(); } if (tid == 0) { temp[blockIdx.x] = i_data[0]; } }
f29398f7195a77bbd8348500f251f5ebe13b358f.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <stdlib.h> #include <hip/hip_runtime.h> #include <cutil.h> #include <sys/time.h> #include "../lib/bed.h" #include "../lib/set_intersect.h" #include "radixsort.h" //#include "gpu.hpp" #include "random.hpp" #include "../lib/timer.h" #include "set_intersect_cuda.h" int main(int argc, char *argv[]) { //CUDA_SAFE_CALL( hipSetDevice( atoi(argv[7] ) ) ); CUDA_SAFE_CALL( hipFree(NULL) ); if (argc < 6) { fprintf(stderr, "usage: %s <u> <a> <b> <brute rounds N> <sum N>\n" "e.g., order U.bed A.bed B.bed 10000 1 1024 1\n", argv[0]); return 1; } int chrom_num = 24; /***********************REPLACE WITH INPUT FILE************************/ char *chrom_names[] = { "chr1", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX", "chrY" }; /**********************************************************************/ struct chr_list *U, *A, *B; char *U_file = argv[1], *A_file = argv[2], *B_file = argv[3]; int rounds = atoi(argv[4]); int sum_threads = atoi(argv[5]); if ( ( chr_list_from_bed_file(&U, chrom_names, chrom_num, U_file) == 1) || ( chr_list_from_bed_file(&A, chrom_names, chrom_num, A_file) == 1) || ( chr_list_from_bed_file(&B, chrom_names, chrom_num, B_file) == 1) ) { fprintf(stderr, "Error parsing bed files.\n"); return 1; } unsigned int max = add_offsets(U, chrom_num); trim(U, A, chrom_num); trim(U, B, chrom_num); int A_size, B_size, U_size; struct bed_line *U_array, *A_array, *B_array; U_size = chr_array_from_list(U, &U_array, chrom_num); A_size = chr_array_from_list(A, &A_array, chrom_num); B_size = chr_array_from_list(B, &B_array, chrom_num); unsigned int *A_key_h = (unsigned int *) malloc( (A_size) * sizeof(unsigned int)); unsigned int *A_val_h = (unsigned int *) malloc( (A_size) * sizeof(unsigned int)); unsigned int *B_key_h = (unsigned int *) malloc( (B_size) * sizeof(unsigned int)); unsigned int *B_val_h = (unsigned int *) malloc( (B_size) * sizeof(unsigned int)); /* * In CUDA we can sort key value pairs, * the key can be the offset, and the value can be the length */ set_start_len( U_array, U_size, A_array, A_key_h, A_val_h, A_size ); set_start_len( U_array, U_size, B_array, B_key_h, B_val_h, B_size ); // Move A and B to deviceB unsigned int *A_key_d, *A_val_d, *B_key_d, *B_val_d; hipMalloc((void **)&A_key_d, (A_size)*sizeof(unsigned int)); hipMalloc((void **)&A_val_d, (A_size)*sizeof(unsigned int)); hipMalloc((void **)&B_key_d, (B_size)*sizeof(unsigned int)); hipMalloc((void **)&B_val_d, (B_size)*sizeof(unsigned int)); start(); hipMemcpy(A_key_d, A_key_h, (A_size) * sizeof(unsigned int), hipMemcpyHostToDevice); hipMemcpy(A_val_d, A_val_h, (A_size) * sizeof(unsigned int), hipMemcpyHostToDevice); hipMemcpy(B_key_d, B_key_h, (B_size) * sizeof(unsigned int), hipMemcpyHostToDevice); hipMemcpy(B_val_d, B_val_h, (B_size) * sizeof(unsigned int), hipMemcpyHostToDevice); stop(); // R will hold the results of the intersection, for each interval A[i], // R[i] will be the number of intervals in B that A[i] intersects, unsigned int *R_d; hipMalloc((void **)&R_d, (A_size)*sizeof(unsigned int)); hipMemset(R_d, 0, (A_size)*sizeof(unsigned int)); unsigned long memup_time = report(); int block_size = 256; dim3 dimBlock(block_size); // *_key_d holds the start position, and *_val_d holds the length, // the end position is *_key_d + *_val_d // // Each thread will search |reps| items in A, we will keep the blocksize // fixed at 256, but we will need to adjust the grid size int grid_size = ( A_size + block_size - 1) / (block_size * 1); dim3 dimGridSearch( grid_size ); hipError_t err; // Sort A nvRadixSort::RadixSort radixsortA(A_size, false); radixsortA.sort((unsigned int*)A_key_d, (unsigned int*)A_val_d, A_size, 32); // Sort B nvRadixSort::RadixSort radixsortB(B_size, false); radixsortB.sort((unsigned int*)B_key_d, (unsigned int*)B_val_d, B_size, 32); hipDeviceSynchronize(); stop(); unsigned long sort_time = report(); unsigned int *R_h = (unsigned int *) malloc( A_size * sizeof(unsigned int)); err = hipGetLastError(); if(err != hipSuccess) fprintf(stderr, "Sort: %s.\n", hipGetErrorString( err) ); start(); int each_run = B_size / rounds, last_run = B_size / rounds + B_size % rounds; int i; for ( i = 0; i < (rounds - 1); i++) { hipLaunchKernelGGL(( intersection_brute_force) , dim3(dimGridSearch), dim3(dimBlock) , 0, 0, A_key_d, A_val_d, A_size, B_key_d, B_val_d, each_run, R_d, i * each_run); hipDeviceSynchronize(); err = hipGetLastError(); if(err != hipSuccess) fprintf(stderr, "Intersect %d: %s.\n", i, hipGetErrorString( err) ); } hipLaunchKernelGGL(( intersection_brute_force) , dim3(dimGridSearch), dim3( dimBlock) , 0, 0, A_key_d, A_val_d, A_size, B_key_d, B_val_d, last_run, R_d, i * each_run); hipDeviceSynchronize(); stop(); err = hipGetLastError(); if(err != hipSuccess) fprintf(stderr, "Last intersect %d: %s.\n", i, hipGetErrorString( err) ); unsigned long search_time = report(); hipFree(A_key_d); hipFree(B_key_d); hipFree(A_val_d); hipFree(B_val_d); /* unsigned int *R_all = (unsigned int *) malloc( (A_size) * sizeof(unsigned int)); hipMemcpy(R_all, R_d, A_size * sizeof(unsigned int), hipMemcpyDeviceToHost); for(i = 0; i < A_size; i++) printf("%u\n", R_all[i]); */ start(); parallel_sum(R_d, block_size, A_size, sum_threads); stop(); unsigned long sum_time = report(); unsigned int O; start(); hipMemcpy(&O, R_d, 1 * sizeof(unsigned int), hipMemcpyDeviceToHost); stop(); unsigned long memdown_time = report(); unsigned long total = memup_time + sort_time + search_time + sum_time + memdown_time; fprintf(stderr,"O:%d\n", O); printf("%d,%d,%d\tT:%ld\t" "up:%ld,%G\t" "sort:%ld,%G\t" "search:%ld,%G\t" "sum:%ld,%G\t" "down:%ld,%G\n", A_size, B_size, A_size + B_size, total, memup_time, (double)memup_time / (double)total, sort_time, (double)sort_time / (double)total, search_time, (double)search_time / (double)total, sum_time, (double)sum_time / (double)total, memdown_time, (double)memdown_time / (double)total ); hipFree(R_d); return 0; }
f29398f7195a77bbd8348500f251f5ebe13b358f.cu
#include <stdio.h> #include <stdlib.h> #include <cuda.h> #include <cutil.h> #include <sys/time.h> #include "../lib/bed.h" #include "../lib/set_intersect.h" #include "radixsort.h" //#include "gpu.hpp" #include "random.hpp" #include "../lib/timer.h" #include "set_intersect_cuda.h" int main(int argc, char *argv[]) { //CUDA_SAFE_CALL( cudaSetDevice( atoi(argv[7] ) ) ); CUDA_SAFE_CALL( cudaFree(NULL) ); if (argc < 6) { fprintf(stderr, "usage: %s <u> <a> <b> <brute rounds N> <sum N>\n" "e.g., order U.bed A.bed B.bed 10000 1 1024 1\n", argv[0]); return 1; } int chrom_num = 24; /***********************REPLACE WITH INPUT FILE************************/ char *chrom_names[] = { "chr1", "chr2", "chr3", "chr4", "chr5", "chr6", "chr7", "chr8", "chr9", "chr10", "chr11", "chr12", "chr13", "chr14", "chr15", "chr16", "chr17", "chr18", "chr19", "chr20", "chr21", "chr22", "chrX", "chrY" }; /**********************************************************************/ struct chr_list *U, *A, *B; char *U_file = argv[1], *A_file = argv[2], *B_file = argv[3]; int rounds = atoi(argv[4]); int sum_threads = atoi(argv[5]); if ( ( chr_list_from_bed_file(&U, chrom_names, chrom_num, U_file) == 1) || ( chr_list_from_bed_file(&A, chrom_names, chrom_num, A_file) == 1) || ( chr_list_from_bed_file(&B, chrom_names, chrom_num, B_file) == 1) ) { fprintf(stderr, "Error parsing bed files.\n"); return 1; } unsigned int max = add_offsets(U, chrom_num); trim(U, A, chrom_num); trim(U, B, chrom_num); int A_size, B_size, U_size; struct bed_line *U_array, *A_array, *B_array; U_size = chr_array_from_list(U, &U_array, chrom_num); A_size = chr_array_from_list(A, &A_array, chrom_num); B_size = chr_array_from_list(B, &B_array, chrom_num); unsigned int *A_key_h = (unsigned int *) malloc( (A_size) * sizeof(unsigned int)); unsigned int *A_val_h = (unsigned int *) malloc( (A_size) * sizeof(unsigned int)); unsigned int *B_key_h = (unsigned int *) malloc( (B_size) * sizeof(unsigned int)); unsigned int *B_val_h = (unsigned int *) malloc( (B_size) * sizeof(unsigned int)); /* * In CUDA we can sort key value pairs, * the key can be the offset, and the value can be the length */ set_start_len( U_array, U_size, A_array, A_key_h, A_val_h, A_size ); set_start_len( U_array, U_size, B_array, B_key_h, B_val_h, B_size ); // Move A and B to deviceB unsigned int *A_key_d, *A_val_d, *B_key_d, *B_val_d; cudaMalloc((void **)&A_key_d, (A_size)*sizeof(unsigned int)); cudaMalloc((void **)&A_val_d, (A_size)*sizeof(unsigned int)); cudaMalloc((void **)&B_key_d, (B_size)*sizeof(unsigned int)); cudaMalloc((void **)&B_val_d, (B_size)*sizeof(unsigned int)); start(); cudaMemcpy(A_key_d, A_key_h, (A_size) * sizeof(unsigned int), cudaMemcpyHostToDevice); cudaMemcpy(A_val_d, A_val_h, (A_size) * sizeof(unsigned int), cudaMemcpyHostToDevice); cudaMemcpy(B_key_d, B_key_h, (B_size) * sizeof(unsigned int), cudaMemcpyHostToDevice); cudaMemcpy(B_val_d, B_val_h, (B_size) * sizeof(unsigned int), cudaMemcpyHostToDevice); stop(); // R will hold the results of the intersection, for each interval A[i], // R[i] will be the number of intervals in B that A[i] intersects, unsigned int *R_d; cudaMalloc((void **)&R_d, (A_size)*sizeof(unsigned int)); cudaMemset(R_d, 0, (A_size)*sizeof(unsigned int)); unsigned long memup_time = report(); int block_size = 256; dim3 dimBlock(block_size); // *_key_d holds the start position, and *_val_d holds the length, // the end position is *_key_d + *_val_d // // Each thread will search |reps| items in A, we will keep the blocksize // fixed at 256, but we will need to adjust the grid size int grid_size = ( A_size + block_size - 1) / (block_size * 1); dim3 dimGridSearch( grid_size ); cudaError_t err; // Sort A nvRadixSort::RadixSort radixsortA(A_size, false); radixsortA.sort((unsigned int*)A_key_d, (unsigned int*)A_val_d, A_size, 32); // Sort B nvRadixSort::RadixSort radixsortB(B_size, false); radixsortB.sort((unsigned int*)B_key_d, (unsigned int*)B_val_d, B_size, 32); cudaThreadSynchronize(); stop(); unsigned long sort_time = report(); unsigned int *R_h = (unsigned int *) malloc( A_size * sizeof(unsigned int)); err = cudaGetLastError(); if(err != cudaSuccess) fprintf(stderr, "Sort: %s.\n", cudaGetErrorString( err) ); start(); int each_run = B_size / rounds, last_run = B_size / rounds + B_size % rounds; int i; for ( i = 0; i < (rounds - 1); i++) { intersection_brute_force <<<dimGridSearch, dimBlock >>> ( A_key_d, A_val_d, A_size, B_key_d, B_val_d, each_run, R_d, i * each_run); cudaThreadSynchronize(); err = cudaGetLastError(); if(err != cudaSuccess) fprintf(stderr, "Intersect %d: %s.\n", i, cudaGetErrorString( err) ); } intersection_brute_force <<<dimGridSearch, dimBlock >>> ( A_key_d, A_val_d, A_size, B_key_d, B_val_d, last_run, R_d, i * each_run); cudaThreadSynchronize(); stop(); err = cudaGetLastError(); if(err != cudaSuccess) fprintf(stderr, "Last intersect %d: %s.\n", i, cudaGetErrorString( err) ); unsigned long search_time = report(); cudaFree(A_key_d); cudaFree(B_key_d); cudaFree(A_val_d); cudaFree(B_val_d); /* unsigned int *R_all = (unsigned int *) malloc( (A_size) * sizeof(unsigned int)); cudaMemcpy(R_all, R_d, A_size * sizeof(unsigned int), cudaMemcpyDeviceToHost); for(i = 0; i < A_size; i++) printf("%u\n", R_all[i]); */ start(); parallel_sum(R_d, block_size, A_size, sum_threads); stop(); unsigned long sum_time = report(); unsigned int O; start(); cudaMemcpy(&O, R_d, 1 * sizeof(unsigned int), cudaMemcpyDeviceToHost); stop(); unsigned long memdown_time = report(); unsigned long total = memup_time + sort_time + search_time + sum_time + memdown_time; fprintf(stderr,"O:%d\n", O); printf("%d,%d,%d\tT:%ld\t" "up:%ld,%G\t" "sort:%ld,%G\t" "search:%ld,%G\t" "sum:%ld,%G\t" "down:%ld,%G\n", A_size, B_size, A_size + B_size, total, memup_time, (double)memup_time / (double)total, sort_time, (double)sort_time / (double)total, search_time, (double)search_time / (double)total, sum_time, (double)sum_time / (double)total, memdown_time, (double)memdown_time / (double)total ); cudaFree(R_d); return 0; }
a29451ccb8a19460adc8c14b912737056c29b8e5.hip
// !!! This is a file automatically generated by hipify!!! /* * Copyright 1993-2020 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. * */ // CUDA sample demonstrating a __nv_bfloat16 (E8M7) GEMM computation using the Warp Matrix Multiply // and Accumulate API introduced in CUDA 11.0. // In this program, the compute_gemm kernel computes the result of a matrix multiplication // and addition: D = alpha * A * B + beta * C. The dimensions of both C and D matrices // are M_GLOBAL x N_GLOBAL. The A matrix is M_GLOBAL x K_GLOBAL (row-major), the B matrix // is K_GLOBAL x N_GLOBAL (column-major). // In that kernel, each CTA computes one 128 x 128 tile of the resulting matrix // per iteration. When the tile is computed, the CTA stores it to the global memory // and begins a new iteration, selecting a new 128 x 128 tile to compute. // Each CTA consists of eight warps. For the 128 x 128 tile, each warp computes eight // 16 x 16 subtiles, organized in a 2 x 4 two-dimensional array. // Warps compute the 16 x 16 subtiles using nvcuda::wmma::mma_sync operations by // moving through the K_GLOBAL dimension of the A and B matrices and accumulating // the intermediate result in the local thread state. // There are a number of simple optimizations used in the algorithm: // - The CTA copies the 128 x 128 tile of the C matrix from the global memory to // shared memory. After that is done, each warp loads the C matrix fragments from // shared memory, thus avoiding a random global memory access. // - On each internal iteration, the CTA copies a portion of the A and B matrices from // global memory to shared memory. After that, all warps in the CTA reuse the A and B // data from shared memory, thus reducing the number of data copies from global memory. // - The portions of the A and B matrices are stored in shared memory with an additional // padding (skew) to reduce the number of shared memory access bank conflicts. // (See a detailed explanation near the SKEW_BF16 macro definition.) // - When the CTA finishes computing the tiles of the resulting matrix, each warp stores // its subtiles to shared memory. The CTA then copies the shared memory contents to // global memory, again avoiding redundant random global memory accesses. // - Note that the CTA tile size is chosen to maximize the GPU register utilization, // but carefully enough to avoid local memory use. #include <assert.h> #include <stdio.h> #include <hip/hip_runtime.h> #include <cuda_bf16.h> #include <mma.h> #include <cuda_pipeline.h> // helper functions and utilities to work with CUDA #include <helper_functions.h> #include <helper_cuda.h> // Externally configurable parameters. // Switch for choosing cpp interface for cuda pipeline // vs primitives interface. #define USE_CPP_API 0 #ifndef CPU_DEBUG // Set this to 1 to verify the correctness of the GPU-computed matrix. #define CPU_DEBUG 0 #endif #ifndef SHARED_MEMORY_LIMIT_64K // Set this to 0 to use more than 64 Kb of shared memory to cache data, to // improve the performance of the computations on GPU. // Note that you need a GPU that can have more than 64 Kb of shared memory // per multiprocessor. #define SHARED_MEMORY_LIMIT_64K 0 #endif // GPU configuration. #define WARP_SIZE 32 // MMA matrix tile dimensions. #define M 16 #define N 16 #define K 16 // GEMM configuration. #define M_TILES 512 #define N_TILES 512 #define K_TILES 512 #define M_GLOBAL (M * M_TILES) #define N_GLOBAL (N * N_TILES) #define K_GLOBAL (K * K_TILES) #define C_LAYOUT wmma::mem_row_major // Implementation constants. #define WARPS_PER_BLOCK 8 #define THREADS_PER_BLOCK (WARP_SIZE * WARPS_PER_BLOCK) #if SHARED_MEMORY_LIMIT_64K // With only 64 Kb shared memory available, we can fit two 8-tile chunks of // the A and B matrix data, that is (M = 16) * (K = 16) * 8 * (CHUNK_K = 8) // * sizeof(__nv_bfloat16) = 32 Kb each. // (i.e. two 8x8 arrays of tiles of 16x16 __nv_bfloat16-typed elements per CTA). // But we cannot account the 8 Kb total skew overhead, without which the performance // would be severely impacted. So we choose to reduce the chunk size in half, // i.e. the amount of A and B matrix data we cache in shared memory. // Accordingly, this doubles the number of outer iterations across the global K // dimension, which only slightly impacts the performance. #define CHUNK_K 4 #else #define CHUNK_K 8 #endif #define CHUNK_LINE_BYTES (CHUNK_K * K * sizeof(__nv_bfloat16)) #define WARP_COPY_BYTES (WARP_SIZE * sizeof(int4)) #define CHUNK_COPY_LINES_PER_WARP (WARP_COPY_BYTES / CHUNK_LINE_BYTES) #define CHUNK_COPY_LINE_LANES (WARP_SIZE / CHUNK_COPY_LINES_PER_WARP) #define BLOCK_ROW_WARPS 2 #define BLOCK_COL_WARPS 4 #define WARP_ROW_TILES 4 #define WARP_COL_TILES 2 #define BLOCK_ROW_TILES (WARP_ROW_TILES * BLOCK_ROW_WARPS) #define BLOCK_COL_TILES (WARP_COL_TILES * BLOCK_COL_WARPS) #define GLOBAL_MEM_STRIDE N_GLOBAL #define SHMEM_STRIDE (N * BLOCK_ROW_TILES) #define SHMEM_OFFSET (N * WARP_ROW_TILES) // The macro below is used to shift rows of the A matrix and columns of the B matrix // in shared memory to minimize possible bank conflicts. // Before performing the nvcuda::wmma::mma_sync operation, the warp must load the matrix // data using the nvcuda::wmma::load_matrix_sync operation. Although the memory access pattern // is not specified for that function, each lane in the warp can read one or multiple matrix // elements from different matrix rows or columns. // For shared memory, such access can result in bank conflicts if different rows / columns // of the matrix map to the same bank. By shifting each row and column by a few bytes, we // make sure that they map to different banks, thus reducing the number of possible bank // conflicts. // The number of 16 two-byte "__nv_bfloat16" elements is chosen as the minimum possible shift because // we must keep each row and column 256-bit aligned, as required by nvcuda::wmma::load_matrix_sync. #define SKEW_BF16 16 #define checkKernelErrors(expr) do { \ expr; \ \ hipError_t __err = hipGetLastError(); \ if (__err != hipSuccess) { \ printf("Line %d: '%s' failed: %s\n", __LINE__, # expr, hipGetErrorString(__err)); \ abort(); \ } \ } while(0) enum kernels { bf16mma_shmem_gemm_async_copy = 0, // __nv_bfloat16 MMA shmem using kernel with async_copy bf16mma_shmem_gemm = 1, // __nv_bfloat16 MMA shmem using kernel normal copy (without async_copy). simple_bf16mma_gemm = 2 // __nv_bfloat16 MMA non-shmem using simple kernel. }; const char* kernelNames[] = {"compute_bf16gemm_async_copy", "compute_bf16gemm", "simple_wmma_bf16gemm"}; using namespace nvcuda; namespace nvcuda_namespace = nvcuda::experimental; __host__ void init_host_matrices(__nv_bfloat16 *a, __nv_bfloat16 *b, float *c) { for (int i = 0; i < M_GLOBAL; i++) { for (int j = 0; j < K_GLOBAL; j++) { a[i*K_GLOBAL+j] = (__nv_bfloat16)(rand() % 3); } } for (int i = 0; i < N_GLOBAL; i++) { for (int j = 0; j < K_GLOBAL; j++) { b[i*K_GLOBAL+j] = (__nv_bfloat16)(rand() % 3); } } for (int t = 0; t < M_GLOBAL * N_GLOBAL; t++) { c[t] = (float)(rand() % 3); } } __global__ void compute_bf16gemm(const __nv_bfloat16 *A, const __nv_bfloat16 *B, const float *C, float *D, float alpha, float beta) { #if __CUDA_ARCH__ >= 800 extern __shared__ __nv_bfloat16 shmem[][CHUNK_K * K + SKEW_BF16]; // Warp and lane identification. const unsigned int warpId = threadIdx.x / WARP_SIZE; const unsigned int laneId = threadIdx.x % WARP_SIZE; // Offset in shared memory from which the B matrix is stored. const size_t shmem_idx_b_off = BLOCK_COL_TILES * M; // This pointer is used to access the C and D matrix tiles this warp computes. float *shmem_warp_tile_ptr = (float*)&shmem[0][0] + (warpId / BLOCK_ROW_WARPS) * SHMEM_STRIDE * N * BLOCK_ROW_WARPS + (warpId % BLOCK_ROW_WARPS) * SHMEM_OFFSET; // This pointer is used to stream the C and D matrices block-wide tile to and from shared memory. float *shmem_warp_stream_ptr = (float*)&shmem[0][0] + warpId * SHMEM_STRIDE * N; // Adjust the beta scaler, as it'll be multiplied by alpha at the end of // each tile computation. Technically this is not generally correct (may result // in a loss of precision). Zero still needs to be specially handled though. beta /= alpha; // Each CTA slides along the 128 x 128 tiles from the top left corner of the matrix to the // right and down, and selects the next tile to compute. Once there's no such tile, // all warps in this CTA exit. for(unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) { const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES); const unsigned int block_tile_j = (block_pos * BLOCK_COL_TILES) % N_TILES; // Stop when there are no more D matrix tiles to compute in this CTA. if (block_tile_i >= M_TILES) { break; } // This warp's pointer to the C matrix data to copy memory from to shared memory. const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N; const float *src_gmem_warp_stream_ptr = &C[gmem_idx]; // Stream multiple C tiles to shared memory. #pragma unroll for (int i = 0; i < N; i++) { *((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId) = *((int4*)(src_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId); } __syncthreads(); // These fragments will accumulate the result of A and B matrix fragment multiplications // along the K_GLOBAL dimension. wmma::fragment<wmma::accumulator, M, N, K, float> c[WARP_COL_TILES][WARP_ROW_TILES]; // Load the C matrix tiles into fragments from shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { const float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * N + j * N; wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Scale the C matrix. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll for (int t = 0; t < c[i][j].num_elements; t++) { c[i][j].x[t] *= beta; } } } // Select what warp copies what matrix to shared memory. // Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix. const __nv_bfloat16 *warp_ptr = (warpId < (WARPS_PER_BLOCK/2)) ? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2); // Go through the global K dimension by a fixed step at a time. #pragma unroll for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) { // Copy slices of the A and B matrices to shared memory. // The first half of the warps in the CTA copy the A matrix, the rest copy the B matrix. size_t shmem_idx = warpId < (WARPS_PER_BLOCK/2) ? (M * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (N * (warpId % (WARPS_PER_BLOCK/2)) * 2 + shmem_idx_b_off); // First half of the warp copies the first row / column of the matrix, // the second half of the warp copies the next. const __nv_bfloat16 *lane_ptr = (warp_ptr + tile_k * K + (laneId / CHUNK_COPY_LINE_LANES) * K_GLOBAL); // Shift the second half of the warp to the next row / column in the shared memory. shmem_idx += laneId / CHUNK_COPY_LINE_LANES; #pragma unroll for(int i = 0; i < ((WARP_SIZE/2) / CHUNK_COPY_LINES_PER_WARP) * 2; i++) { // Copy 16 bytes at once in each lane. *((int4*)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES)) = *((int4*)lane_ptr + (laneId % CHUNK_COPY_LINE_LANES)); // Advance the global memory pointer and the shared memory index. lane_ptr = lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP; shmem_idx += CHUNK_COPY_LINES_PER_WARP; } __syncthreads(); // Compute a grid of C matrix tiles in each warp. #pragma unroll for (int k_step = 0; k_step < CHUNK_K; k_step++) { wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a[WARP_COL_TILES]; wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b[WARP_ROW_TILES]; #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { size_t shmem_idx_a = (warpId/BLOCK_ROW_WARPS) * M * BLOCK_ROW_WARPS + (i * M); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_a][k_step * K]; wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_BF16); #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { if (i == 0) { // Load the B matrix fragment once, because it is going to be reused // against the other A matrix fragments. size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId%2) + (j * N); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_b][k_step * K]; wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_BF16); } wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]); } } } __syncthreads(); } // Store the D fragments to shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll // Uniform, point-wise transformations of ALL fragment elements by ALL threads in the // warp are well-defined even though element indices within fragment storage are not defined. for (int t = 0; t < c[i][j].num_elements; t++) c[i][j].x[t] *= alpha; float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N; wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Now that shared memory contains all the D tiles, stream them to global memory. float *dst_gmem_warp_stream_ptr = &D[gmem_idx]; #pragma unroll for (int i = 0; i < N; i++) { *((int4*)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) = *((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId); } __syncthreads(); } #endif } __global__ void compute_bf16gemm_async_copy(const __nv_bfloat16 *A, const __nv_bfloat16 *B, const float *C, float *D, float alpha, float beta) { #if __CUDA_ARCH__ >= 800 extern __shared__ __nv_bfloat16 shmem[][CHUNK_K * K + SKEW_BF16]; // Warp and lane identification. const unsigned int warpId = threadIdx.x / WARP_SIZE; const unsigned int laneId = threadIdx.x % WARP_SIZE; // Offset in shared memory from which the B matrix is stored. const size_t shmem_idx_b_off = BLOCK_COL_TILES * M; // This pointer is used to access the C and D matrix tiles this warp computes. float *shmem_warp_tile_ptr = (float*)&shmem[0][0] + (warpId / BLOCK_ROW_WARPS) * SHMEM_STRIDE * N * BLOCK_ROW_WARPS + (warpId % BLOCK_ROW_WARPS) * SHMEM_OFFSET; // This pointer is used to stream the C and D matrices block-wide tile to and from shared memory. float *shmem_warp_stream_ptr = (float*)&shmem[0][0] + warpId * SHMEM_STRIDE * N; // Adjust the beta scaler, as it'll be multiplied by alpha at the end of // each tile computation. Technically this is not generally correct (may result // in a loss of precision). Zero still needs to be specially handled though. beta /= alpha; #if USE_CPP_API nvcuda_namespace::pipeline pipe; #endif // Each CTA slides along the 128 x 128 tiles from the top left corner of the matrix to the // right and down, and selects the next tile to compute. Once there's no such tile, // all warps in this CTA exit. for(unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) { const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES); const unsigned int block_tile_j = (block_pos * BLOCK_COL_TILES) % N_TILES; // Stop when there are no more D matrix tiles to compute in this CTA. if (block_tile_i >= M_TILES) { break; } // This warp's pointer to the C matrix data to copy memory from to shared memory. const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N; const float *src_gmem_warp_stream_ptr = &C[gmem_idx]; // Stream multiple C tiles to shared memory. #pragma unroll for (int i = 0; i < N; i++) { #if USE_CPP_API nvcuda_namespace::memcpy_async(*((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId), *((int4*)(src_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId), pipe); pipe.commit(); #else __pipeline_memcpy_async((reinterpret_cast<int4*>(&shmem_warp_stream_ptr[(SHMEM_STRIDE * i)])) + laneId, (reinterpret_cast<const int4*>(&src_gmem_warp_stream_ptr[(GLOBAL_MEM_STRIDE * i)])) + laneId, sizeof(int4)); __pipeline_commit(); #endif } #if USE_CPP_API pipe.wait_prior<0>(); #else __pipeline_wait_prior(0); #endif __syncthreads(); // These fragments will accumulate the result of A and B matrix fragment multiplications // along the K_GLOBAL dimension. wmma::fragment<wmma::accumulator, M, N, K, float> c[WARP_COL_TILES][WARP_ROW_TILES]; // Load the C matrix tiles into fragments from shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { const float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * N + j * N; wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Scale the C matrix. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll for (int t = 0; t < c[i][j].num_elements; t++) { c[i][j].x[t] *= beta; } } } // Select what warp copies what matrix to shared memory. // Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix. const __nv_bfloat16 *warp_ptr = (warpId < (WARPS_PER_BLOCK/2)) ? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2); // Go through the global K dimension by a fixed step at a time. #pragma unroll for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) { // Copy slices of the A and B matrices to shared memory. // The first half of the warps in the CTA copy the A matrix, the rest copy the B matrix. size_t shmem_idx = warpId < (WARPS_PER_BLOCK/2) ? (M * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (N * (warpId % (WARPS_PER_BLOCK/2)) * 2 + shmem_idx_b_off); // First half of the warp copies the first row / column of the matrix, // the second half of the warp copies the next. const __nv_bfloat16 *lane_ptr = (warp_ptr + tile_k * K + (laneId / CHUNK_COPY_LINE_LANES) * K_GLOBAL); // Shift the second half of the warp to the next row / column in the shared memory. shmem_idx += laneId / CHUNK_COPY_LINE_LANES; #pragma unroll for(int i = 0; i < ((WARP_SIZE/2) / CHUNK_COPY_LINES_PER_WARP) * 2; i++) { // Copy 16 bytes at once in each lane. #if USE_CPP_API nvcuda_namespace::memcpy_async(*((int4*)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES)), *((int4*)lane_ptr + (laneId % CHUNK_COPY_LINE_LANES)), pipe); pipe.commit(); #else __pipeline_memcpy_async((int4*)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES), (int4*)lane_ptr + (laneId % CHUNK_COPY_LINE_LANES), sizeof(int4)); __pipeline_commit(); #endif // Advance the global memory pointer and the shared memory index. lane_ptr = lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP; shmem_idx += CHUNK_COPY_LINES_PER_WARP; } #if USE_CPP_API pipe.wait_prior<0>(); #else __pipeline_wait_prior(0); #endif __syncthreads(); // Compute a grid of C matrix tiles in each warp. #pragma unroll for (int k_step = 0; k_step < CHUNK_K; k_step++) { wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a[WARP_COL_TILES]; wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b[WARP_ROW_TILES]; #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { size_t shmem_idx_a = (warpId / BLOCK_ROW_WARPS) * M * BLOCK_ROW_WARPS + (i * M); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_a][k_step * K]; wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_BF16); #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { if (i == 0) { // Load the B matrix fragment once, because it is going to be reused // against the other A matrix fragments. size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId%2) + (j * N); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_b][k_step * K]; wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_BF16); } wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]); } } } __syncthreads(); } // Store the D fragments to shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll // Uniform, point-wise transformations of ALL fragment elements by ALL threads in the // warp are well-defined even though element indices within fragment storage are not defined. for (int t = 0; t < c[i][j].num_elements; t++) c[i][j].x[t] *= alpha; float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N; wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Now that shared memory contains all the D tiles, stream them to global memory. float *dst_gmem_warp_stream_ptr = &D[gmem_idx]; #pragma unroll for (int i = 0; i < N; i++) { *((int4*)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) = *((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId); } __syncthreads(); } #endif } // Performs an MxNxK bf16 GEMM (C=alpha*A*B + beta*C) assuming: // 1) Matrices are packed in memory. // 2) M, N and K are multiples of 16, 16 and 16 respectively. // 3) A is row major, B is column major matrix. // Note: This is a less performant version of the compute_bf16gemm kernel. It is designed for // demonstration purposes only to show the CUDA WMMA API use without relying on // availability of the shared memory. __global__ void simple_wmma_bf16gemm(__nv_bfloat16 *a, __nv_bfloat16 *b, float *c, float *d, int m_ld, int n_ld, int k_ld, float alpha, float beta) { #if __CUDA_ARCH__ >= 800 // Leading dimensions. Packed with no transpositions. int lda = k_ld; int ldb = k_ld; int ldc = n_ld; // Tile using a 2D grid int warpM = (blockIdx.x * blockDim.x + threadIdx.x) / warpSize; int warpN = (blockIdx.y * blockDim.y + threadIdx.y); // Declare the fragments wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a_frag; wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b_frag; wmma::fragment<wmma::accumulator, M, N, K, float> acc_frag; wmma::fragment<wmma::accumulator, M, N, K, float> c_frag; wmma::fill_fragment(acc_frag, 0.0f); // Loop over k for (int i = 0; i < k_ld; i += K) { int aCol = i; int aRow = warpM * M; int bCol = i; int bRow = warpN * N; // Bounds checking if (aRow < m_ld && aCol < k_ld && bRow < k_ld && bCol < n_ld) { // Load the inputs wmma::load_matrix_sync(a_frag, a + aCol + aRow * lda, lda); wmma::load_matrix_sync(b_frag, b + bRow + bCol * ldb, ldb); // Perform the matrix multiplication wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag); } } // Load in the current value of c, scale it by beta, and add this our result scaled by alpha int cCol = warpN * N; int cRow = warpM * M; if (cRow < m_ld && cCol < n_ld) { wmma::load_matrix_sync(c_frag, c + cCol + cRow * ldc, ldc, wmma::mem_row_major); for(int i=0; i < c_frag.num_elements; i++) { c_frag.x[i] = alpha * acc_frag.x[i] + beta * c_frag.x[i]; } // Store the output wmma::store_matrix_sync(d + cCol + cRow * ldc, c_frag, ldc, wmma::mem_row_major); } #endif } __host__ void matMultiplyOnHost(__nv_bfloat16 *A, __nv_bfloat16 *B, float *C, float alpha, float beta, int numARows, int numAColumns, int numBRows, int numBColumns, int numCRows, int numCColumns) { for (int i = 0; i < numCRows; i++) { for (int j = 0; j < numCColumns; j++) { float temp = 0.0; for (int k = 0; k < numAColumns; k++) { temp += (float)A[i * numAColumns + k] * (float)B[j * numBRows + k]; } C[i*numCColumns + j] = temp * alpha + beta * C[i * numCColumns + j]; } } } int main(int argc, char **argv) { printf("Initializing...\n"); int dev = findCudaDevice(argc, (const char **)argv); hipDeviceProp_t deviceProp; checkCudaErrors(hipGetDeviceProperties(&deviceProp, dev)); // Tensor cores require a GPU of Volta (SM8X) architecture or higher. if (deviceProp.major < 8) { printf("bf16TensorCoreGemm requires requires SM 8.0 or higher to use Tensor Cores. Exiting...\n"); exit(EXIT_WAIVED); } printf("M: %d (%d x %d)\n", M_GLOBAL, M, M_TILES); printf("N: %d (%d x %d)\n", N_GLOBAL, N, N_TILES); printf("K: %d (%d x %d)\n", K_GLOBAL, K, K_TILES); __nv_bfloat16 *A_h = NULL; __nv_bfloat16 *B_h = NULL; float *C_h = NULL; #if CPU_DEBUG float *result_hD = NULL; float *result_host = NULL; #endif A_h = (__nv_bfloat16*) malloc(sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL); B_h = (__nv_bfloat16*) malloc(sizeof(__nv_bfloat16) * K_GLOBAL * N_GLOBAL); C_h = (float*) malloc(sizeof(float) * M_GLOBAL * N_GLOBAL); #if CPU_DEBUG result_hD = (float*) malloc(sizeof(float) * M_GLOBAL * N_GLOBAL); result_host = (float*) malloc(sizeof(float) * M_GLOBAL * N_GLOBAL); #endif __nv_bfloat16 *A = NULL; __nv_bfloat16 *B = NULL; float *C = NULL; float *D = NULL; checkCudaErrors(hipMalloc((void**)&A, sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL)); checkCudaErrors(hipMalloc((void**)&B, sizeof(__nv_bfloat16) * N_GLOBAL * K_GLOBAL)); checkCudaErrors(hipMalloc((void**)&C, sizeof(float) * M_GLOBAL * N_GLOBAL)); checkCudaErrors(hipMalloc((void**)&D, sizeof(float) * M_GLOBAL * N_GLOBAL)); assert(((unsigned long long)A) % 128 == 0); assert(((unsigned long long)B) % 128 == 0); assert(((unsigned long long)C) % 128 == 0); assert(((unsigned long long)D) % 128 == 0); init_host_matrices(A_h, B_h, C_h); printf("Preparing data for GPU...\n"); checkCudaErrors(hipMemcpy(A, A_h, sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL, hipMemcpyHostToDevice)); checkCudaErrors(hipMemcpy(B, B_h, sizeof(__nv_bfloat16) * N_GLOBAL * K_GLOBAL, hipMemcpyHostToDevice)); checkCudaErrors(hipMemcpy(C, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL, hipMemcpyHostToDevice)); checkCudaErrors(hipMemset(D, 0, sizeof(float) * M_GLOBAL * N_GLOBAL)); enum { // Compute the right amount of shared memory to request. // We need shared memory to hold per-CTA C and D matrix tiles, and to cache per-CTA chunks // of the A and B matrices. Therefore, the right amount to request is the maximum of those // two numbers. SHMEM_SZ = MAX(sizeof(__nv_bfloat16) * (BLOCK_COL_TILES * M) * (CHUNK_K * K + SKEW_BF16) * 2, M * (BLOCK_ROW_WARPS * WARP_ROW_TILES) * N * (BLOCK_COL_WARPS * WARP_COL_TILES) * sizeof(float)) }; printf("Required shared memory size: %lu Kb\n", SHMEM_SZ / 1024UL); const float alpha = 1.1f; const float beta = 1.2f; hipEvent_t start, stop; checkCudaErrors(hipEventCreate(&start)); checkCudaErrors(hipEventCreate(&stop)); checkCudaErrors(hipEventRecord(start)); // kernel to run - default (b16mma_shmem_gemm_async_copy == 0) kernels selected_kernel = bf16mma_shmem_gemm_async_copy; if (checkCmdLineFlag(argc, (const char **)argv, "kernel")) { int kernel_number = getCmdLineArgumentInt(argc, (const char **)argv, "kernel"); if (kernel_number < 3) { selected_kernel = (kernels)kernel_number; } else { printf("Error: kernel number should be between 0 to 2, you have entered %d\n", kernel_number); exit(EXIT_FAILURE); } } // If enough shared memory available on the GPU use high performant kernel if ((deviceProp.sharedMemPerMultiprocessor >= SHMEM_SZ) && (selected_kernel != simple_bf16mma_gemm)) { printf("Computing using high performance kernel = %d - %s\n", selected_kernel, kernelNames[selected_kernel]); switch (selected_kernel) { case bf16mma_shmem_gemm_async_copy : default: checkCudaErrors(hipFuncSetAttribute(compute_bf16gemm_async_copy, hipFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ)); hipLaunchKernelGGL(( checkKernelErrors((compute_bf16gemm_async_copy), dim3(deviceProp.multiProcessorCount*2), dim3(THREADS_PER_BLOCK), SHMEM_SZ, 0, A, B, C, D, alpha, beta))); break; case bf16mma_shmem_gemm : checkCudaErrors(hipFuncSetAttribute(compute_bf16gemm, hipFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ)); hipLaunchKernelGGL(( checkKernelErrors((compute_bf16gemm), dim3(deviceProp.multiProcessorCount*2), dim3(THREADS_PER_BLOCK), SHMEM_SZ, 0, A, B, C, D, alpha, beta))); break; } #if CPU_DEBUG checkCudaErrors(hipMemcpy(result_hD, D, sizeof(float)*M_GLOBAL*N_GLOBAL, hipMemcpyDeviceToHost)); #endif } else { dim3 gridDim; dim3 blockDim; // blockDim.x must be a multple of warpSize // 128x4 means we have 16 warps and a block computes a 64x64 output tile blockDim.x = 128; blockDim.y = 4; gridDim.x = (M_GLOBAL + (M * blockDim.x / 32 - 1)) / (M * blockDim.x / 32); gridDim.y = (N_GLOBAL + N * blockDim.y - 1) / (N * blockDim.y); printf("Computing... using simple_wmma_gemm kernel\n"); hipLaunchKernelGGL(( simple_wmma_bf16gemm), dim3(gridDim), dim3(blockDim), 0, 0, A, B, C, D, M_GLOBAL, N_GLOBAL, K_GLOBAL, alpha, beta); #if CPU_DEBUG checkCudaErrors(hipMemcpy(result_hD, D, sizeof(float) * M_GLOBAL * N_GLOBAL, hipMemcpyDeviceToHost)); #endif } checkCudaErrors(hipEventRecord(stop)); checkCudaErrors(hipEventSynchronize(stop)); #if CPU_DEBUG printf("Verifying correctness of the computations...\n"); memcpy(result_host, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL); matMultiplyOnHost(A_h, B_h, result_host, alpha, beta, M_GLOBAL, K_GLOBAL, K_GLOBAL, N_GLOBAL, M_GLOBAL, N_GLOBAL); for (int i = 0; i < N_GLOBAL * M_GLOBAL; i++) { if (fabs(result_hD[i] - result_host[i]) > 0.1f) { printf("mismatch i=%d result_hD=%f result_host=%f\n", i, result_hD[i], result_host[i]); } } free(result_hD); free(result_host); #endif float milliseconds = 0; checkCudaErrors(hipEventElapsedTime(&milliseconds, start, stop)); printf("Time: %f ms\n", milliseconds); printf("TFLOPS: %.2f\n", (((double)M_GLOBAL * N_GLOBAL * K_GLOBAL * 2)/(milliseconds/1000.)) / 1e12); free(A_h); free(B_h); free(C_h); checkCudaErrors(hipFree((void*)A)); checkCudaErrors(hipFree((void*)B)); checkCudaErrors(hipFree((void*)C)); checkCudaErrors(hipFree((void*)D)); return 0; }
a29451ccb8a19460adc8c14b912737056c29b8e5.cu
/* * Copyright 1993-2020 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. * */ // CUDA sample demonstrating a __nv_bfloat16 (E8M7) GEMM computation using the Warp Matrix Multiply // and Accumulate API introduced in CUDA 11.0. // In this program, the compute_gemm kernel computes the result of a matrix multiplication // and addition: D = alpha * A * B + beta * C. The dimensions of both C and D matrices // are M_GLOBAL x N_GLOBAL. The A matrix is M_GLOBAL x K_GLOBAL (row-major), the B matrix // is K_GLOBAL x N_GLOBAL (column-major). // In that kernel, each CTA computes one 128 x 128 tile of the resulting matrix // per iteration. When the tile is computed, the CTA stores it to the global memory // and begins a new iteration, selecting a new 128 x 128 tile to compute. // Each CTA consists of eight warps. For the 128 x 128 tile, each warp computes eight // 16 x 16 subtiles, organized in a 2 x 4 two-dimensional array. // Warps compute the 16 x 16 subtiles using nvcuda::wmma::mma_sync operations by // moving through the K_GLOBAL dimension of the A and B matrices and accumulating // the intermediate result in the local thread state. // There are a number of simple optimizations used in the algorithm: // - The CTA copies the 128 x 128 tile of the C matrix from the global memory to // shared memory. After that is done, each warp loads the C matrix fragments from // shared memory, thus avoiding a random global memory access. // - On each internal iteration, the CTA copies a portion of the A and B matrices from // global memory to shared memory. After that, all warps in the CTA reuse the A and B // data from shared memory, thus reducing the number of data copies from global memory. // - The portions of the A and B matrices are stored in shared memory with an additional // padding (skew) to reduce the number of shared memory access bank conflicts. // (See a detailed explanation near the SKEW_BF16 macro definition.) // - When the CTA finishes computing the tiles of the resulting matrix, each warp stores // its subtiles to shared memory. The CTA then copies the shared memory contents to // global memory, again avoiding redundant random global memory accesses. // - Note that the CTA tile size is chosen to maximize the GPU register utilization, // but carefully enough to avoid local memory use. #include <assert.h> #include <stdio.h> #include <cuda.h> #include <cuda_bf16.h> #include <mma.h> #include <cuda_pipeline.h> // helper functions and utilities to work with CUDA #include <helper_functions.h> #include <helper_cuda.h> // Externally configurable parameters. // Switch for choosing cpp interface for cuda pipeline // vs primitives interface. #define USE_CPP_API 0 #ifndef CPU_DEBUG // Set this to 1 to verify the correctness of the GPU-computed matrix. #define CPU_DEBUG 0 #endif #ifndef SHARED_MEMORY_LIMIT_64K // Set this to 0 to use more than 64 Kb of shared memory to cache data, to // improve the performance of the computations on GPU. // Note that you need a GPU that can have more than 64 Kb of shared memory // per multiprocessor. #define SHARED_MEMORY_LIMIT_64K 0 #endif // GPU configuration. #define WARP_SIZE 32 // MMA matrix tile dimensions. #define M 16 #define N 16 #define K 16 // GEMM configuration. #define M_TILES 512 #define N_TILES 512 #define K_TILES 512 #define M_GLOBAL (M * M_TILES) #define N_GLOBAL (N * N_TILES) #define K_GLOBAL (K * K_TILES) #define C_LAYOUT wmma::mem_row_major // Implementation constants. #define WARPS_PER_BLOCK 8 #define THREADS_PER_BLOCK (WARP_SIZE * WARPS_PER_BLOCK) #if SHARED_MEMORY_LIMIT_64K // With only 64 Kb shared memory available, we can fit two 8-tile chunks of // the A and B matrix data, that is (M = 16) * (K = 16) * 8 * (CHUNK_K = 8) // * sizeof(__nv_bfloat16) = 32 Kb each. // (i.e. two 8x8 arrays of tiles of 16x16 __nv_bfloat16-typed elements per CTA). // But we cannot account the 8 Kb total skew overhead, without which the performance // would be severely impacted. So we choose to reduce the chunk size in half, // i.e. the amount of A and B matrix data we cache in shared memory. // Accordingly, this doubles the number of outer iterations across the global K // dimension, which only slightly impacts the performance. #define CHUNK_K 4 #else #define CHUNK_K 8 #endif #define CHUNK_LINE_BYTES (CHUNK_K * K * sizeof(__nv_bfloat16)) #define WARP_COPY_BYTES (WARP_SIZE * sizeof(int4)) #define CHUNK_COPY_LINES_PER_WARP (WARP_COPY_BYTES / CHUNK_LINE_BYTES) #define CHUNK_COPY_LINE_LANES (WARP_SIZE / CHUNK_COPY_LINES_PER_WARP) #define BLOCK_ROW_WARPS 2 #define BLOCK_COL_WARPS 4 #define WARP_ROW_TILES 4 #define WARP_COL_TILES 2 #define BLOCK_ROW_TILES (WARP_ROW_TILES * BLOCK_ROW_WARPS) #define BLOCK_COL_TILES (WARP_COL_TILES * BLOCK_COL_WARPS) #define GLOBAL_MEM_STRIDE N_GLOBAL #define SHMEM_STRIDE (N * BLOCK_ROW_TILES) #define SHMEM_OFFSET (N * WARP_ROW_TILES) // The macro below is used to shift rows of the A matrix and columns of the B matrix // in shared memory to minimize possible bank conflicts. // Before performing the nvcuda::wmma::mma_sync operation, the warp must load the matrix // data using the nvcuda::wmma::load_matrix_sync operation. Although the memory access pattern // is not specified for that function, each lane in the warp can read one or multiple matrix // elements from different matrix rows or columns. // For shared memory, such access can result in bank conflicts if different rows / columns // of the matrix map to the same bank. By shifting each row and column by a few bytes, we // make sure that they map to different banks, thus reducing the number of possible bank // conflicts. // The number of 16 two-byte "__nv_bfloat16" elements is chosen as the minimum possible shift because // we must keep each row and column 256-bit aligned, as required by nvcuda::wmma::load_matrix_sync. #define SKEW_BF16 16 #define checkKernelErrors(expr) do { \ expr; \ \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ printf("Line %d: '%s' failed: %s\n", __LINE__, # expr, cudaGetErrorString(__err)); \ abort(); \ } \ } while(0) enum kernels { bf16mma_shmem_gemm_async_copy = 0, // __nv_bfloat16 MMA shmem using kernel with async_copy bf16mma_shmem_gemm = 1, // __nv_bfloat16 MMA shmem using kernel normal copy (without async_copy). simple_bf16mma_gemm = 2 // __nv_bfloat16 MMA non-shmem using simple kernel. }; const char* kernelNames[] = {"compute_bf16gemm_async_copy", "compute_bf16gemm", "simple_wmma_bf16gemm"}; using namespace nvcuda; namespace nvcuda_namespace = nvcuda::experimental; __host__ void init_host_matrices(__nv_bfloat16 *a, __nv_bfloat16 *b, float *c) { for (int i = 0; i < M_GLOBAL; i++) { for (int j = 0; j < K_GLOBAL; j++) { a[i*K_GLOBAL+j] = (__nv_bfloat16)(rand() % 3); } } for (int i = 0; i < N_GLOBAL; i++) { for (int j = 0; j < K_GLOBAL; j++) { b[i*K_GLOBAL+j] = (__nv_bfloat16)(rand() % 3); } } for (int t = 0; t < M_GLOBAL * N_GLOBAL; t++) { c[t] = (float)(rand() % 3); } } __global__ void compute_bf16gemm(const __nv_bfloat16 *A, const __nv_bfloat16 *B, const float *C, float *D, float alpha, float beta) { #if __CUDA_ARCH__ >= 800 extern __shared__ __nv_bfloat16 shmem[][CHUNK_K * K + SKEW_BF16]; // Warp and lane identification. const unsigned int warpId = threadIdx.x / WARP_SIZE; const unsigned int laneId = threadIdx.x % WARP_SIZE; // Offset in shared memory from which the B matrix is stored. const size_t shmem_idx_b_off = BLOCK_COL_TILES * M; // This pointer is used to access the C and D matrix tiles this warp computes. float *shmem_warp_tile_ptr = (float*)&shmem[0][0] + (warpId / BLOCK_ROW_WARPS) * SHMEM_STRIDE * N * BLOCK_ROW_WARPS + (warpId % BLOCK_ROW_WARPS) * SHMEM_OFFSET; // This pointer is used to stream the C and D matrices block-wide tile to and from shared memory. float *shmem_warp_stream_ptr = (float*)&shmem[0][0] + warpId * SHMEM_STRIDE * N; // Adjust the beta scaler, as it'll be multiplied by alpha at the end of // each tile computation. Technically this is not generally correct (may result // in a loss of precision). Zero still needs to be specially handled though. beta /= alpha; // Each CTA slides along the 128 x 128 tiles from the top left corner of the matrix to the // right and down, and selects the next tile to compute. Once there's no such tile, // all warps in this CTA exit. for(unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) { const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES); const unsigned int block_tile_j = (block_pos * BLOCK_COL_TILES) % N_TILES; // Stop when there are no more D matrix tiles to compute in this CTA. if (block_tile_i >= M_TILES) { break; } // This warp's pointer to the C matrix data to copy memory from to shared memory. const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N; const float *src_gmem_warp_stream_ptr = &C[gmem_idx]; // Stream multiple C tiles to shared memory. #pragma unroll for (int i = 0; i < N; i++) { *((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId) = *((int4*)(src_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId); } __syncthreads(); // These fragments will accumulate the result of A and B matrix fragment multiplications // along the K_GLOBAL dimension. wmma::fragment<wmma::accumulator, M, N, K, float> c[WARP_COL_TILES][WARP_ROW_TILES]; // Load the C matrix tiles into fragments from shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { const float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * N + j * N; wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Scale the C matrix. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll for (int t = 0; t < c[i][j].num_elements; t++) { c[i][j].x[t] *= beta; } } } // Select what warp copies what matrix to shared memory. // Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix. const __nv_bfloat16 *warp_ptr = (warpId < (WARPS_PER_BLOCK/2)) ? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2); // Go through the global K dimension by a fixed step at a time. #pragma unroll for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) { // Copy slices of the A and B matrices to shared memory. // The first half of the warps in the CTA copy the A matrix, the rest copy the B matrix. size_t shmem_idx = warpId < (WARPS_PER_BLOCK/2) ? (M * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (N * (warpId % (WARPS_PER_BLOCK/2)) * 2 + shmem_idx_b_off); // First half of the warp copies the first row / column of the matrix, // the second half of the warp copies the next. const __nv_bfloat16 *lane_ptr = (warp_ptr + tile_k * K + (laneId / CHUNK_COPY_LINE_LANES) * K_GLOBAL); // Shift the second half of the warp to the next row / column in the shared memory. shmem_idx += laneId / CHUNK_COPY_LINE_LANES; #pragma unroll for(int i = 0; i < ((WARP_SIZE/2) / CHUNK_COPY_LINES_PER_WARP) * 2; i++) { // Copy 16 bytes at once in each lane. *((int4*)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES)) = *((int4*)lane_ptr + (laneId % CHUNK_COPY_LINE_LANES)); // Advance the global memory pointer and the shared memory index. lane_ptr = lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP; shmem_idx += CHUNK_COPY_LINES_PER_WARP; } __syncthreads(); // Compute a grid of C matrix tiles in each warp. #pragma unroll for (int k_step = 0; k_step < CHUNK_K; k_step++) { wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a[WARP_COL_TILES]; wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b[WARP_ROW_TILES]; #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { size_t shmem_idx_a = (warpId/BLOCK_ROW_WARPS) * M * BLOCK_ROW_WARPS + (i * M); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_a][k_step * K]; wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_BF16); #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { if (i == 0) { // Load the B matrix fragment once, because it is going to be reused // against the other A matrix fragments. size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId%2) + (j * N); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_b][k_step * K]; wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_BF16); } wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]); } } } __syncthreads(); } // Store the D fragments to shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll // Uniform, point-wise transformations of ALL fragment elements by ALL threads in the // warp are well-defined even though element indices within fragment storage are not defined. for (int t = 0; t < c[i][j].num_elements; t++) c[i][j].x[t] *= alpha; float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N; wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Now that shared memory contains all the D tiles, stream them to global memory. float *dst_gmem_warp_stream_ptr = &D[gmem_idx]; #pragma unroll for (int i = 0; i < N; i++) { *((int4*)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) = *((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId); } __syncthreads(); } #endif } __global__ void compute_bf16gemm_async_copy(const __nv_bfloat16 *A, const __nv_bfloat16 *B, const float *C, float *D, float alpha, float beta) { #if __CUDA_ARCH__ >= 800 extern __shared__ __nv_bfloat16 shmem[][CHUNK_K * K + SKEW_BF16]; // Warp and lane identification. const unsigned int warpId = threadIdx.x / WARP_SIZE; const unsigned int laneId = threadIdx.x % WARP_SIZE; // Offset in shared memory from which the B matrix is stored. const size_t shmem_idx_b_off = BLOCK_COL_TILES * M; // This pointer is used to access the C and D matrix tiles this warp computes. float *shmem_warp_tile_ptr = (float*)&shmem[0][0] + (warpId / BLOCK_ROW_WARPS) * SHMEM_STRIDE * N * BLOCK_ROW_WARPS + (warpId % BLOCK_ROW_WARPS) * SHMEM_OFFSET; // This pointer is used to stream the C and D matrices block-wide tile to and from shared memory. float *shmem_warp_stream_ptr = (float*)&shmem[0][0] + warpId * SHMEM_STRIDE * N; // Adjust the beta scaler, as it'll be multiplied by alpha at the end of // each tile computation. Technically this is not generally correct (may result // in a loss of precision). Zero still needs to be specially handled though. beta /= alpha; #if USE_CPP_API nvcuda_namespace::pipeline pipe; #endif // Each CTA slides along the 128 x 128 tiles from the top left corner of the matrix to the // right and down, and selects the next tile to compute. Once there's no such tile, // all warps in this CTA exit. for(unsigned int block_pos = blockIdx.x;; block_pos += gridDim.x) { const unsigned int block_tile_i = ((block_pos * BLOCK_ROW_TILES) / N_TILES) * (BLOCK_COL_TILES); const unsigned int block_tile_j = (block_pos * BLOCK_COL_TILES) % N_TILES; // Stop when there are no more D matrix tiles to compute in this CTA. if (block_tile_i >= M_TILES) { break; } // This warp's pointer to the C matrix data to copy memory from to shared memory. const size_t gmem_idx = (block_tile_i + warpId) * M * GLOBAL_MEM_STRIDE + block_tile_j * N; const float *src_gmem_warp_stream_ptr = &C[gmem_idx]; // Stream multiple C tiles to shared memory. #pragma unroll for (int i = 0; i < N; i++) { #if USE_CPP_API nvcuda_namespace::memcpy_async(*((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId), *((int4*)(src_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId), pipe); pipe.commit(); #else __pipeline_memcpy_async((reinterpret_cast<int4*>(&shmem_warp_stream_ptr[(SHMEM_STRIDE * i)])) + laneId, (reinterpret_cast<const int4*>(&src_gmem_warp_stream_ptr[(GLOBAL_MEM_STRIDE * i)])) + laneId, sizeof(int4)); __pipeline_commit(); #endif } #if USE_CPP_API pipe.wait_prior<0>(); #else __pipeline_wait_prior(0); #endif __syncthreads(); // These fragments will accumulate the result of A and B matrix fragment multiplications // along the K_GLOBAL dimension. wmma::fragment<wmma::accumulator, M, N, K, float> c[WARP_COL_TILES][WARP_ROW_TILES]; // Load the C matrix tiles into fragments from shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { const float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * N + j * N; wmma::load_matrix_sync(c[i][j], tile_ptr, SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Scale the C matrix. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll for (int t = 0; t < c[i][j].num_elements; t++) { c[i][j].x[t] *= beta; } } } // Select what warp copies what matrix to shared memory. // Warps 0-3 copy the A matrix, warps 4-7 copy the B matrix. const __nv_bfloat16 *warp_ptr = (warpId < (WARPS_PER_BLOCK/2)) ? (&A[block_tile_i * M * K_GLOBAL] + M * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (&B[block_tile_j * N * K_GLOBAL] + N * K_GLOBAL * (warpId % (WARPS_PER_BLOCK/2)) * 2); // Go through the global K dimension by a fixed step at a time. #pragma unroll for (int tile_k = 0; tile_k < K_TILES; tile_k += CHUNK_K) { // Copy slices of the A and B matrices to shared memory. // The first half of the warps in the CTA copy the A matrix, the rest copy the B matrix. size_t shmem_idx = warpId < (WARPS_PER_BLOCK/2) ? (M * (warpId % (WARPS_PER_BLOCK/2)) * 2) : (N * (warpId % (WARPS_PER_BLOCK/2)) * 2 + shmem_idx_b_off); // First half of the warp copies the first row / column of the matrix, // the second half of the warp copies the next. const __nv_bfloat16 *lane_ptr = (warp_ptr + tile_k * K + (laneId / CHUNK_COPY_LINE_LANES) * K_GLOBAL); // Shift the second half of the warp to the next row / column in the shared memory. shmem_idx += laneId / CHUNK_COPY_LINE_LANES; #pragma unroll for(int i = 0; i < ((WARP_SIZE/2) / CHUNK_COPY_LINES_PER_WARP) * 2; i++) { // Copy 16 bytes at once in each lane. #if USE_CPP_API nvcuda_namespace::memcpy_async(*((int4*)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES)), *((int4*)lane_ptr + (laneId % CHUNK_COPY_LINE_LANES)), pipe); pipe.commit(); #else __pipeline_memcpy_async((int4*)&shmem[shmem_idx][0] + (laneId % CHUNK_COPY_LINE_LANES), (int4*)lane_ptr + (laneId % CHUNK_COPY_LINE_LANES), sizeof(int4)); __pipeline_commit(); #endif // Advance the global memory pointer and the shared memory index. lane_ptr = lane_ptr + K_GLOBAL * CHUNK_COPY_LINES_PER_WARP; shmem_idx += CHUNK_COPY_LINES_PER_WARP; } #if USE_CPP_API pipe.wait_prior<0>(); #else __pipeline_wait_prior(0); #endif __syncthreads(); // Compute a grid of C matrix tiles in each warp. #pragma unroll for (int k_step = 0; k_step < CHUNK_K; k_step++) { wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a[WARP_COL_TILES]; wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b[WARP_ROW_TILES]; #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { size_t shmem_idx_a = (warpId / BLOCK_ROW_WARPS) * M * BLOCK_ROW_WARPS + (i * M); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_a][k_step * K]; wmma::load_matrix_sync(a[i], tile_ptr, K * CHUNK_K + SKEW_BF16); #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { if (i == 0) { // Load the B matrix fragment once, because it is going to be reused // against the other A matrix fragments. size_t shmem_idx_b = shmem_idx_b_off + (WARP_ROW_TILES * N) * (warpId%2) + (j * N); const __nv_bfloat16 *tile_ptr = &shmem[shmem_idx_b][k_step * K]; wmma::load_matrix_sync(b[j], tile_ptr, K * CHUNK_K + SKEW_BF16); } wmma::mma_sync(c[i][j], a[i], b[j], c[i][j]); } } } __syncthreads(); } // Store the D fragments to shared memory. #pragma unroll for (int i = 0; i < WARP_COL_TILES; i++) { #pragma unroll for (int j = 0; j < WARP_ROW_TILES; j++) { #pragma unroll // Uniform, point-wise transformations of ALL fragment elements by ALL threads in the // warp are well-defined even though element indices within fragment storage are not defined. for (int t = 0; t < c[i][j].num_elements; t++) c[i][j].x[t] *= alpha; float *tile_ptr = shmem_warp_tile_ptr + i * SHMEM_STRIDE * K + j * N; wmma::store_matrix_sync(tile_ptr, c[i][j], SHMEM_STRIDE, C_LAYOUT); } } __syncthreads(); // Now that shared memory contains all the D tiles, stream them to global memory. float *dst_gmem_warp_stream_ptr = &D[gmem_idx]; #pragma unroll for (int i = 0; i < N; i++) { *((int4*)(dst_gmem_warp_stream_ptr + GLOBAL_MEM_STRIDE * i) + laneId) = *((int4*)(shmem_warp_stream_ptr + SHMEM_STRIDE * i) + laneId); } __syncthreads(); } #endif } // Performs an MxNxK bf16 GEMM (C=alpha*A*B + beta*C) assuming: // 1) Matrices are packed in memory. // 2) M, N and K are multiples of 16, 16 and 16 respectively. // 3) A is row major, B is column major matrix. // Note: This is a less performant version of the compute_bf16gemm kernel. It is designed for // demonstration purposes only to show the CUDA WMMA API use without relying on // availability of the shared memory. __global__ void simple_wmma_bf16gemm(__nv_bfloat16 *a, __nv_bfloat16 *b, float *c, float *d, int m_ld, int n_ld, int k_ld, float alpha, float beta) { #if __CUDA_ARCH__ >= 800 // Leading dimensions. Packed with no transpositions. int lda = k_ld; int ldb = k_ld; int ldc = n_ld; // Tile using a 2D grid int warpM = (blockIdx.x * blockDim.x + threadIdx.x) / warpSize; int warpN = (blockIdx.y * blockDim.y + threadIdx.y); // Declare the fragments wmma::fragment<wmma::matrix_a, M, N, K, __nv_bfloat16, wmma::row_major> a_frag; wmma::fragment<wmma::matrix_b, M, N, K, __nv_bfloat16, wmma::col_major> b_frag; wmma::fragment<wmma::accumulator, M, N, K, float> acc_frag; wmma::fragment<wmma::accumulator, M, N, K, float> c_frag; wmma::fill_fragment(acc_frag, 0.0f); // Loop over k for (int i = 0; i < k_ld; i += K) { int aCol = i; int aRow = warpM * M; int bCol = i; int bRow = warpN * N; // Bounds checking if (aRow < m_ld && aCol < k_ld && bRow < k_ld && bCol < n_ld) { // Load the inputs wmma::load_matrix_sync(a_frag, a + aCol + aRow * lda, lda); wmma::load_matrix_sync(b_frag, b + bRow + bCol * ldb, ldb); // Perform the matrix multiplication wmma::mma_sync(acc_frag, a_frag, b_frag, acc_frag); } } // Load in the current value of c, scale it by beta, and add this our result scaled by alpha int cCol = warpN * N; int cRow = warpM * M; if (cRow < m_ld && cCol < n_ld) { wmma::load_matrix_sync(c_frag, c + cCol + cRow * ldc, ldc, wmma::mem_row_major); for(int i=0; i < c_frag.num_elements; i++) { c_frag.x[i] = alpha * acc_frag.x[i] + beta * c_frag.x[i]; } // Store the output wmma::store_matrix_sync(d + cCol + cRow * ldc, c_frag, ldc, wmma::mem_row_major); } #endif } __host__ void matMultiplyOnHost(__nv_bfloat16 *A, __nv_bfloat16 *B, float *C, float alpha, float beta, int numARows, int numAColumns, int numBRows, int numBColumns, int numCRows, int numCColumns) { for (int i = 0; i < numCRows; i++) { for (int j = 0; j < numCColumns; j++) { float temp = 0.0; for (int k = 0; k < numAColumns; k++) { temp += (float)A[i * numAColumns + k] * (float)B[j * numBRows + k]; } C[i*numCColumns + j] = temp * alpha + beta * C[i * numCColumns + j]; } } } int main(int argc, char **argv) { printf("Initializing...\n"); int dev = findCudaDevice(argc, (const char **)argv); cudaDeviceProp deviceProp; checkCudaErrors(cudaGetDeviceProperties(&deviceProp, dev)); // Tensor cores require a GPU of Volta (SM8X) architecture or higher. if (deviceProp.major < 8) { printf("bf16TensorCoreGemm requires requires SM 8.0 or higher to use Tensor Cores. Exiting...\n"); exit(EXIT_WAIVED); } printf("M: %d (%d x %d)\n", M_GLOBAL, M, M_TILES); printf("N: %d (%d x %d)\n", N_GLOBAL, N, N_TILES); printf("K: %d (%d x %d)\n", K_GLOBAL, K, K_TILES); __nv_bfloat16 *A_h = NULL; __nv_bfloat16 *B_h = NULL; float *C_h = NULL; #if CPU_DEBUG float *result_hD = NULL; float *result_host = NULL; #endif A_h = (__nv_bfloat16*) malloc(sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL); B_h = (__nv_bfloat16*) malloc(sizeof(__nv_bfloat16) * K_GLOBAL * N_GLOBAL); C_h = (float*) malloc(sizeof(float) * M_GLOBAL * N_GLOBAL); #if CPU_DEBUG result_hD = (float*) malloc(sizeof(float) * M_GLOBAL * N_GLOBAL); result_host = (float*) malloc(sizeof(float) * M_GLOBAL * N_GLOBAL); #endif __nv_bfloat16 *A = NULL; __nv_bfloat16 *B = NULL; float *C = NULL; float *D = NULL; checkCudaErrors(cudaMalloc((void**)&A, sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL)); checkCudaErrors(cudaMalloc((void**)&B, sizeof(__nv_bfloat16) * N_GLOBAL * K_GLOBAL)); checkCudaErrors(cudaMalloc((void**)&C, sizeof(float) * M_GLOBAL * N_GLOBAL)); checkCudaErrors(cudaMalloc((void**)&D, sizeof(float) * M_GLOBAL * N_GLOBAL)); assert(((unsigned long long)A) % 128 == 0); assert(((unsigned long long)B) % 128 == 0); assert(((unsigned long long)C) % 128 == 0); assert(((unsigned long long)D) % 128 == 0); init_host_matrices(A_h, B_h, C_h); printf("Preparing data for GPU...\n"); checkCudaErrors(cudaMemcpy(A, A_h, sizeof(__nv_bfloat16) * M_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice)); checkCudaErrors(cudaMemcpy(B, B_h, sizeof(__nv_bfloat16) * N_GLOBAL * K_GLOBAL, cudaMemcpyHostToDevice)); checkCudaErrors(cudaMemcpy(C, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyHostToDevice)); checkCudaErrors(cudaMemset(D, 0, sizeof(float) * M_GLOBAL * N_GLOBAL)); enum { // Compute the right amount of shared memory to request. // We need shared memory to hold per-CTA C and D matrix tiles, and to cache per-CTA chunks // of the A and B matrices. Therefore, the right amount to request is the maximum of those // two numbers. SHMEM_SZ = MAX(sizeof(__nv_bfloat16) * (BLOCK_COL_TILES * M) * (CHUNK_K * K + SKEW_BF16) * 2, M * (BLOCK_ROW_WARPS * WARP_ROW_TILES) * N * (BLOCK_COL_WARPS * WARP_COL_TILES) * sizeof(float)) }; printf("Required shared memory size: %lu Kb\n", SHMEM_SZ / 1024UL); const float alpha = 1.1f; const float beta = 1.2f; cudaEvent_t start, stop; checkCudaErrors(cudaEventCreate(&start)); checkCudaErrors(cudaEventCreate(&stop)); checkCudaErrors(cudaEventRecord(start)); // kernel to run - default (b16mma_shmem_gemm_async_copy == 0) kernels selected_kernel = bf16mma_shmem_gemm_async_copy; if (checkCmdLineFlag(argc, (const char **)argv, "kernel")) { int kernel_number = getCmdLineArgumentInt(argc, (const char **)argv, "kernel"); if (kernel_number < 3) { selected_kernel = (kernels)kernel_number; } else { printf("Error: kernel number should be between 0 to 2, you have entered %d\n", kernel_number); exit(EXIT_FAILURE); } } // If enough shared memory available on the GPU use high performant kernel if ((deviceProp.sharedMemPerMultiprocessor >= SHMEM_SZ) && (selected_kernel != simple_bf16mma_gemm)) { printf("Computing using high performance kernel = %d - %s\n", selected_kernel, kernelNames[selected_kernel]); switch (selected_kernel) { case bf16mma_shmem_gemm_async_copy : default: checkCudaErrors(cudaFuncSetAttribute(compute_bf16gemm_async_copy, cudaFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ)); checkKernelErrors((compute_bf16gemm_async_copy<<<deviceProp.multiProcessorCount*2, THREADS_PER_BLOCK, SHMEM_SZ>>>(A, B, C, D, alpha, beta))); break; case bf16mma_shmem_gemm : checkCudaErrors(cudaFuncSetAttribute(compute_bf16gemm, cudaFuncAttributeMaxDynamicSharedMemorySize, SHMEM_SZ)); checkKernelErrors((compute_bf16gemm<<<deviceProp.multiProcessorCount*2, THREADS_PER_BLOCK, SHMEM_SZ>>>(A, B, C, D, alpha, beta))); break; } #if CPU_DEBUG checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(float)*M_GLOBAL*N_GLOBAL, cudaMemcpyDeviceToHost)); #endif } else { dim3 gridDim; dim3 blockDim; // blockDim.x must be a multple of warpSize // 128x4 means we have 16 warps and a block computes a 64x64 output tile blockDim.x = 128; blockDim.y = 4; gridDim.x = (M_GLOBAL + (M * blockDim.x / 32 - 1)) / (M * blockDim.x / 32); gridDim.y = (N_GLOBAL + N * blockDim.y - 1) / (N * blockDim.y); printf("Computing... using simple_wmma_gemm kernel\n"); simple_wmma_bf16gemm<<<gridDim, blockDim>>>(A, B, C, D, M_GLOBAL, N_GLOBAL, K_GLOBAL, alpha, beta); #if CPU_DEBUG checkCudaErrors(cudaMemcpy(result_hD, D, sizeof(float) * M_GLOBAL * N_GLOBAL, cudaMemcpyDeviceToHost)); #endif } checkCudaErrors(cudaEventRecord(stop)); checkCudaErrors(cudaEventSynchronize(stop)); #if CPU_DEBUG printf("Verifying correctness of the computations...\n"); memcpy(result_host, C_h, sizeof(float) * M_GLOBAL * N_GLOBAL); matMultiplyOnHost(A_h, B_h, result_host, alpha, beta, M_GLOBAL, K_GLOBAL, K_GLOBAL, N_GLOBAL, M_GLOBAL, N_GLOBAL); for (int i = 0; i < N_GLOBAL * M_GLOBAL; i++) { if (fabs(result_hD[i] - result_host[i]) > 0.1f) { printf("mismatch i=%d result_hD=%f result_host=%f\n", i, result_hD[i], result_host[i]); } } free(result_hD); free(result_host); #endif float milliseconds = 0; checkCudaErrors(cudaEventElapsedTime(&milliseconds, start, stop)); printf("Time: %f ms\n", milliseconds); printf("TFLOPS: %.2f\n", (((double)M_GLOBAL * N_GLOBAL * K_GLOBAL * 2)/(milliseconds/1000.)) / 1e12); free(A_h); free(B_h); free(C_h); checkCudaErrors(cudaFree((void*)A)); checkCudaErrors(cudaFree((void*)B)); checkCudaErrors(cudaFree((void*)C)); checkCudaErrors(cudaFree((void*)D)); return 0; }
23646f59490083f2a7d9eb15911265b76df37787.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /** * APPROXIMATE PATTERN MATCHING * * INF560 */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/time.h> #define APM_DEBUG 0 char * read_input_file( char * filename, int * size ) { char * buf ; off_t fsize; int fd = 0 ; int n_bytes = 1 ; /* Open the text file */ fd = open( filename, O_RDONLY ) ; if ( fd == -1 ) { fprintf( stderr, "Unable to open the text file <%s>\n", filename ) ; return NULL ; } /* Get the number of characters in the textfile */ fsize = lseek(fd, 0, SEEK_END); if ( fsize == -1 ) { fprintf( stderr, "Unable to lseek to the end\n" ) ; return NULL ; } #if APM_DEBUG printf( "File length: %lld\n", fsize ) ; #endif /* Go back to the beginning of the input file */ if ( lseek(fd, 0, SEEK_SET) == -1 ) { fprintf( stderr, "Unable to lseek to start\n" ) ; return NULL ; } /* Allocate data to copy the target text */ buf = (char *)malloc( fsize * sizeof ( char ) ) ; if ( buf == NULL ) { fprintf( stderr, "Unable to allocate %lld byte(s) for main array\n", fsize ) ; return NULL ; } n_bytes = read( fd, buf, fsize ) ; if ( n_bytes != fsize ) { fprintf( stderr, "Unable to copy %lld byte(s) from text file (%d byte(s) copied)\n", fsize, n_bytes) ; return NULL ; } #if APM_DEBUG printf( "Number of read bytes: %d\n", n_bytes ) ; #endif *size = n_bytes ; close( fd ) ; return buf ; } #define MIN3(a, b, c) ((a) < (b) ? ((a) < (c) ? (a) : (c)) : ((b) < (c) ? (b) : (c))) __host__ __device__ int levenshtein(char *s1, char *s2, int len, int * column) { unsigned int x, y, lastdiag, olddiag; for (y = 1; y <= len; y++) { column[y] = y; } for (x = 1; x <= len; x++) { column[0] = x; lastdiag = x-1 ; for (y = 1; y <= len; y++) { olddiag = column[y]; column[y] = MIN3( column[y] + 1, column[y-1] + 1, lastdiag + (s1[y-1] == s2[x-1] ? 0 : 1) ); lastdiag = olddiag; } } return(column[len]); } __global__ void matchesKernel(int* d_n_matches, char * d_buf, char * d_pattern, int i, int size_pattern, int offset, int n_bytes, int approx_factor){ /* Traverse the input data up to the end of the file */ int j = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int distance = 0 ; int size ; size = size_pattern ; int* columns = (int *) malloc((size_pattern + 1) * sizeof(int)); while (j < n_bytes) { if (n_bytes - j < size_pattern ){ size = n_bytes - j ; } distance = levenshtein(d_pattern + offset, &d_buf[j], size, columns ) ; if ( distance <= approx_factor) { atomicAdd(&d_n_matches[i], 1); } j += stride; } free(columns); } int main( int argc, char ** argv ) { char ** pattern ; char * filename ; int approx_factor = 0 ; int nb_patterns = 0 ; int i; char * buf ; struct timeval t1, t2; double duration ; int n_bytes ; int * n_matches ; /* Check number of arguments */ if ( argc < 4 ) { printf( "Usage: %s approximation_factor " "dna_database pattern1 pattern2 ...\n", argv[0] ) ; return 1 ; } /* Get the distance factor */ approx_factor = atoi( argv[1] ) ; /* Grab the filename containing the target text */ filename = argv[2] ; /* Get the number of patterns that the user wants to search for */ nb_patterns = argc - 3 ; /* Fill the pattern array */ pattern = (char **)malloc( nb_patterns * sizeof( char * ) ) ; if ( pattern == NULL ) { fprintf( stderr, "Unable to allocate array of pattern of size %d\n", nb_patterns ) ; return 1 ; } /* Grab the patterns */ for ( i = 0 ; i < nb_patterns ; i++ ) { int l ; l = strlen(argv[i+3]) ; if ( l <= 0 ) { fprintf( stderr, "Error while parsing argument %d\n", i+3 ) ; return 1 ; } pattern[i] = (char *)malloc( (l+1) * sizeof( char ) ) ; if ( pattern[i] == NULL ) { fprintf( stderr, "Unable to allocate string of size %d\n", l ) ; return 1 ; } strncpy( pattern[i], argv[i+3], (l+1) ) ; } printf( "Approximate Pattern Mathing: " "looking for %d pattern(s) in file %s w/ distance of %d\n", nb_patterns, filename, approx_factor ) ; buf = read_input_file( filename, &n_bytes ) ; if ( buf == NULL ) { return 1 ; } /* Allocate the array of matches */ n_matches = (int *)malloc( nb_patterns * sizeof( int ) ) ; for (i = 0; i < nb_patterns; i++) { n_matches[i] = 0; } if ( n_matches == NULL ) { fprintf( stderr, "Error: unable to allocate memory for %ldB\n", nb_patterns * sizeof( int ) ) ; return 1 ; } /***** * BEGIN MAIN LOOP ******/ /* Timer start */ gettimeofday(&t1, NULL); /* Check each pattern one by one */ int* d_n_matches; char * d_pattern; char* d_buf; int* offset = (int *)malloc( nb_patterns * sizeof( int ) ) ; int* lens = (int *)malloc( nb_patterns * sizeof( int ) ) ; int sum_lens; lens[0] = strlen(pattern[0]); offset[0] = 0; sum_lens = lens[0]; for (i = 1; i < nb_patterns; i++) { offset[i] = offset[i-1] + lens[i-1]; lens[i] = strlen(pattern[i]); sum_lens += lens[i]; } char* concat_patterns = (char*) malloc( sum_lens * sizeof( char ) ) ; for (i = 0; i < nb_patterns; i++) { strcpy (concat_patterns + offset[i], pattern[i]); } hipError_t error; hipMalloc((void **)&d_n_matches, nb_patterns*sizeof(int)); hipMalloc((void **)&d_pattern, sum_lens*sizeof(char)); hipMalloc((void **)&d_buf, n_bytes); hipMemcpy(d_pattern, concat_patterns, sum_lens*sizeof(char), hipMemcpyHostToDevice); hipMemcpy(d_buf, buf, n_bytes, hipMemcpyHostToDevice); hipMemcpy(d_n_matches, n_matches, nb_patterns*sizeof(int), hipMemcpyHostToDevice); int Dg = 4; int Db = 256; for (i = 0; i < nb_patterns; i++) { hipLaunchKernelGGL(( matchesKernel), dim3(Dg),dim3(Db), 0, 0, d_n_matches, d_buf, d_pattern, i, lens[i], offset[i], n_bytes, approx_factor); hipGetLastError(); } hipMemcpy(n_matches, d_n_matches, nb_patterns*sizeof(int), hipMemcpyDeviceToHost); /* Timer stop */ gettimeofday(&t2, NULL); duration = (t2.tv_sec -t1.tv_sec)+((t2.tv_usec-t1.tv_usec)/1e6); printf( "APM done in %lf s\n", duration ) ; /***** * END MAIN LOOP ******/ for ( i = 0 ; i < nb_patterns ; i++ ) { printf( "Number of matches for pattern <%s>: %d\n", pattern[i], n_matches[i] ) ; } return 0 ; }
23646f59490083f2a7d9eb15911265b76df37787.cu
/** * APPROXIMATE PATTERN MATCHING * * INF560 */ #include <string.h> #include <stdio.h> #include <stdlib.h> #include <fcntl.h> #include <unistd.h> #include <sys/time.h> #define APM_DEBUG 0 char * read_input_file( char * filename, int * size ) { char * buf ; off_t fsize; int fd = 0 ; int n_bytes = 1 ; /* Open the text file */ fd = open( filename, O_RDONLY ) ; if ( fd == -1 ) { fprintf( stderr, "Unable to open the text file <%s>\n", filename ) ; return NULL ; } /* Get the number of characters in the textfile */ fsize = lseek(fd, 0, SEEK_END); if ( fsize == -1 ) { fprintf( stderr, "Unable to lseek to the end\n" ) ; return NULL ; } #if APM_DEBUG printf( "File length: %lld\n", fsize ) ; #endif /* Go back to the beginning of the input file */ if ( lseek(fd, 0, SEEK_SET) == -1 ) { fprintf( stderr, "Unable to lseek to start\n" ) ; return NULL ; } /* Allocate data to copy the target text */ buf = (char *)malloc( fsize * sizeof ( char ) ) ; if ( buf == NULL ) { fprintf( stderr, "Unable to allocate %lld byte(s) for main array\n", fsize ) ; return NULL ; } n_bytes = read( fd, buf, fsize ) ; if ( n_bytes != fsize ) { fprintf( stderr, "Unable to copy %lld byte(s) from text file (%d byte(s) copied)\n", fsize, n_bytes) ; return NULL ; } #if APM_DEBUG printf( "Number of read bytes: %d\n", n_bytes ) ; #endif *size = n_bytes ; close( fd ) ; return buf ; } #define MIN3(a, b, c) ((a) < (b) ? ((a) < (c) ? (a) : (c)) : ((b) < (c) ? (b) : (c))) __host__ __device__ int levenshtein(char *s1, char *s2, int len, int * column) { unsigned int x, y, lastdiag, olddiag; for (y = 1; y <= len; y++) { column[y] = y; } for (x = 1; x <= len; x++) { column[0] = x; lastdiag = x-1 ; for (y = 1; y <= len; y++) { olddiag = column[y]; column[y] = MIN3( column[y] + 1, column[y-1] + 1, lastdiag + (s1[y-1] == s2[x-1] ? 0 : 1) ); lastdiag = olddiag; } } return(column[len]); } __global__ void matchesKernel(int* d_n_matches, char * d_buf, char * d_pattern, int i, int size_pattern, int offset, int n_bytes, int approx_factor){ /* Traverse the input data up to the end of the file */ int j = blockIdx.x * blockDim.x + threadIdx.x; int stride = blockDim.x * gridDim.x; int distance = 0 ; int size ; size = size_pattern ; int* columns = (int *) malloc((size_pattern + 1) * sizeof(int)); while (j < n_bytes) { if (n_bytes - j < size_pattern ){ size = n_bytes - j ; } distance = levenshtein(d_pattern + offset, &d_buf[j], size, columns ) ; if ( distance <= approx_factor) { atomicAdd(&d_n_matches[i], 1); } j += stride; } free(columns); } int main( int argc, char ** argv ) { char ** pattern ; char * filename ; int approx_factor = 0 ; int nb_patterns = 0 ; int i; char * buf ; struct timeval t1, t2; double duration ; int n_bytes ; int * n_matches ; /* Check number of arguments */ if ( argc < 4 ) { printf( "Usage: %s approximation_factor " "dna_database pattern1 pattern2 ...\n", argv[0] ) ; return 1 ; } /* Get the distance factor */ approx_factor = atoi( argv[1] ) ; /* Grab the filename containing the target text */ filename = argv[2] ; /* Get the number of patterns that the user wants to search for */ nb_patterns = argc - 3 ; /* Fill the pattern array */ pattern = (char **)malloc( nb_patterns * sizeof( char * ) ) ; if ( pattern == NULL ) { fprintf( stderr, "Unable to allocate array of pattern of size %d\n", nb_patterns ) ; return 1 ; } /* Grab the patterns */ for ( i = 0 ; i < nb_patterns ; i++ ) { int l ; l = strlen(argv[i+3]) ; if ( l <= 0 ) { fprintf( stderr, "Error while parsing argument %d\n", i+3 ) ; return 1 ; } pattern[i] = (char *)malloc( (l+1) * sizeof( char ) ) ; if ( pattern[i] == NULL ) { fprintf( stderr, "Unable to allocate string of size %d\n", l ) ; return 1 ; } strncpy( pattern[i], argv[i+3], (l+1) ) ; } printf( "Approximate Pattern Mathing: " "looking for %d pattern(s) in file %s w/ distance of %d\n", nb_patterns, filename, approx_factor ) ; buf = read_input_file( filename, &n_bytes ) ; if ( buf == NULL ) { return 1 ; } /* Allocate the array of matches */ n_matches = (int *)malloc( nb_patterns * sizeof( int ) ) ; for (i = 0; i < nb_patterns; i++) { n_matches[i] = 0; } if ( n_matches == NULL ) { fprintf( stderr, "Error: unable to allocate memory for %ldB\n", nb_patterns * sizeof( int ) ) ; return 1 ; } /***** * BEGIN MAIN LOOP ******/ /* Timer start */ gettimeofday(&t1, NULL); /* Check each pattern one by one */ int* d_n_matches; char * d_pattern; char* d_buf; int* offset = (int *)malloc( nb_patterns * sizeof( int ) ) ; int* lens = (int *)malloc( nb_patterns * sizeof( int ) ) ; int sum_lens; lens[0] = strlen(pattern[0]); offset[0] = 0; sum_lens = lens[0]; for (i = 1; i < nb_patterns; i++) { offset[i] = offset[i-1] + lens[i-1]; lens[i] = strlen(pattern[i]); sum_lens += lens[i]; } char* concat_patterns = (char*) malloc( sum_lens * sizeof( char ) ) ; for (i = 0; i < nb_patterns; i++) { strcpy (concat_patterns + offset[i], pattern[i]); } cudaError_t error; cudaMalloc((void **)&d_n_matches, nb_patterns*sizeof(int)); cudaMalloc((void **)&d_pattern, sum_lens*sizeof(char)); cudaMalloc((void **)&d_buf, n_bytes); cudaMemcpy(d_pattern, concat_patterns, sum_lens*sizeof(char), cudaMemcpyHostToDevice); cudaMemcpy(d_buf, buf, n_bytes, cudaMemcpyHostToDevice); cudaMemcpy(d_n_matches, n_matches, nb_patterns*sizeof(int), cudaMemcpyHostToDevice); int Dg = 4; int Db = 256; for (i = 0; i < nb_patterns; i++) { matchesKernel<<<Dg,Db>>>(d_n_matches, d_buf, d_pattern, i, lens[i], offset[i], n_bytes, approx_factor); cudaGetLastError(); } cudaMemcpy(n_matches, d_n_matches, nb_patterns*sizeof(int), cudaMemcpyDeviceToHost); /* Timer stop */ gettimeofday(&t2, NULL); duration = (t2.tv_sec -t1.tv_sec)+((t2.tv_usec-t1.tv_usec)/1e6); printf( "APM done in %lf s\n", duration ) ; /***** * END MAIN LOOP ******/ for ( i = 0 ; i < nb_patterns ; i++ ) { printf( "Number of matches for pattern <%s>: %d\n", pattern[i], n_matches[i] ) ; } return 0 ; }
0022777b918ae2f644f0e56d2a6048c8af3c5ca7.hip
// !!! This is a file automatically generated by hipify!!! /* Copyright (c) 2019 PaddlePaddle Authors. 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. */ #pragma once #include <map> #include <vector> #include "lite/backends/cuda/math/elementwise.h" #include "lite/core/op_registry.h" #include "lite/kernels/cuda/elementwise_compute.h" namespace paddle { namespace lite { namespace kernels { namespace cuda { inline DDim trim_trailing_singular_dims(const DDim& dims) { // Remove trailing dimensions of size 1 for y auto actual_dims_size = dims.size(); for (; actual_dims_size != 0; --actual_dims_size) { if (dims[actual_dims_size - 1] != 1) break; } std::vector<int64_t> trim_dims; trim_dims.resize(actual_dims_size); for (int i = 0; i < actual_dims_size; ++i) { trim_dims[i] = dims[i]; } if (trim_dims.size() == 0) { return DDim(); } return DDim(trim_dims); } inline bool is_broadcast(const DDim& x_dims, const DDim& y_dims, int axis, int* pre, int* n, int* post) { if (axis < 0) { axis = x_dims.size() - y_dims.size(); } DDim y_dim_trim = trim_trailing_singular_dims(y_dims); axis = (y_dim_trim.size() == 0) ? x_dims.size() : axis; if (x_dims.size() == y_dim_trim.size()) { return false; } *pre = 1; *n = 1; *post = 1; for (int i = 0; i < axis; ++i) { (*pre) *= x_dims[i]; } for (int i = 0; i < y_dim_trim.size(); ++i) { CHECK_EQ(x_dims[i + axis], y_dim_trim[i]) << "Broadcast dimension mismatch."; (*n) *= y_dim_trim[i]; } for (int i = axis + y_dim_trim.size(); i < x_dims.size(); ++i) { (*post) *= x_dims[i]; } return true; } #define ELEMENTWISE_COMPUTE(OP) \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, pre, n, post, OP, stream); \ } else { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, 1, pixel_num, 1, OP, stream); \ } #define ELEMENTWISE_COMPUTE_ACT(OP) \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ auto act = param.act_type; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, pre, n, post, act, OP, stream); \ } else { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, 1, pixel_num, 1, act, OP, stream); \ } #define ELEMENTWISE_COMPUTE_NHWC(OP) \ std::map<int, int> pos_map = {{0, 0}, {1, 3}, {2, 1}, {3, 2}}; \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ if (axis < 0) axis = x->dims().size() - y->dims().size(); \ CHECK(axis >= 0) << "invalid axis of elementwise op"; \ axis = pos_map[axis]; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, pre, n, post, OP, stream); \ } else { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, 1, pixel_num, 1, OP, stream); \ } #define ELEMENTWISE_COMPUTE_ACT_NHWC(OP) \ std::map<int, int> pos_map = {{0, 0}, {1, 3}, {2, 1}, {3, 2}}; \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ if (axis < 0) axis = x->dims().size() - y->dims().size(); \ CHECK(axis >= 0) << "invalid axis of elementwise op"; \ axis = pos_map[axis]; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ auto act = param.act_type; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, pre, n, post, act, OP, stream); \ } else { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, 1, pixel_num, 1, act, OP, stream); \ } void ElementwiseAddCompute::Run() { ELEMENTWISE_COMPUTE(lite::cuda::math::BinaryOperation::kADD) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseAddComputeNHWC::Run() { ELEMENTWISE_COMPUTE_NHWC(lite::cuda::math::BinaryOperation::kADD) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseSubCompute::Run() { ELEMENTWISE_COMPUTE(lite::cuda::math::BinaryOperation::kSUB) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseSubComputeNHWC::Run() { ELEMENTWISE_COMPUTE_NHWC(lite::cuda::math::BinaryOperation::kSUB) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseMulCompute::Run() { ELEMENTWISE_COMPUTE(lite::cuda::math::BinaryOperation::kMUL) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseMulComputeNHWC::Run() { ELEMENTWISE_COMPUTE_NHWC(lite::cuda::math::BinaryOperation::kMUL) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseAddActivationCompute::Run() { ELEMENTWISE_COMPUTE_ACT(lite::cuda::math::BinaryOperation::kADD) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseAddActivationComputeNHWC::Run() { ELEMENTWISE_COMPUTE_ACT_NHWC(lite::cuda::math::BinaryOperation::kADD) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseSubActivationCompute::Run() { ELEMENTWISE_COMPUTE_ACT(lite::cuda::math::BinaryOperation::kSUB) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseSubActivationComputeNHWC::Run() { ELEMENTWISE_COMPUTE_ACT_NHWC(lite::cuda::math::BinaryOperation::kSUB) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseMulActivationCompute::Run() { ELEMENTWISE_COMPUTE_ACT(lite::cuda::math::BinaryOperation::kMUL) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } void ElementwiseMulActivationComputeNHWC::Run() { ELEMENTWISE_COMPUTE_ACT_NHWC(lite::cuda::math::BinaryOperation::kMUL) hipError_t error = hipGetLastError(); if (error != hipSuccess) LOG(INFO) << hipGetErrorString(error); } } // namespace cuda } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL(elementwise_add, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseAddCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_sub, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseSubCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_add, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseAddComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_sub, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseSubComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_mul, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseMulCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_mul, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseMulComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_add_activation, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseAddActivationCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_add_activation, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseAddActivationComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_sub_activation, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseSubActivationCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_sub_activation, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseSubActivationComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_mul_activation, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseMulActivationCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_mul_activation, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseMulActivationComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize();
0022777b918ae2f644f0e56d2a6048c8af3c5ca7.cu
/* Copyright (c) 2019 PaddlePaddle Authors. 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. */ #pragma once #include <map> #include <vector> #include "lite/backends/cuda/math/elementwise.h" #include "lite/core/op_registry.h" #include "lite/kernels/cuda/elementwise_compute.h" namespace paddle { namespace lite { namespace kernels { namespace cuda { inline DDim trim_trailing_singular_dims(const DDim& dims) { // Remove trailing dimensions of size 1 for y auto actual_dims_size = dims.size(); for (; actual_dims_size != 0; --actual_dims_size) { if (dims[actual_dims_size - 1] != 1) break; } std::vector<int64_t> trim_dims; trim_dims.resize(actual_dims_size); for (int i = 0; i < actual_dims_size; ++i) { trim_dims[i] = dims[i]; } if (trim_dims.size() == 0) { return DDim(); } return DDim(trim_dims); } inline bool is_broadcast(const DDim& x_dims, const DDim& y_dims, int axis, int* pre, int* n, int* post) { if (axis < 0) { axis = x_dims.size() - y_dims.size(); } DDim y_dim_trim = trim_trailing_singular_dims(y_dims); axis = (y_dim_trim.size() == 0) ? x_dims.size() : axis; if (x_dims.size() == y_dim_trim.size()) { return false; } *pre = 1; *n = 1; *post = 1; for (int i = 0; i < axis; ++i) { (*pre) *= x_dims[i]; } for (int i = 0; i < y_dim_trim.size(); ++i) { CHECK_EQ(x_dims[i + axis], y_dim_trim[i]) << "Broadcast dimension mismatch."; (*n) *= y_dim_trim[i]; } for (int i = axis + y_dim_trim.size(); i < x_dims.size(); ++i) { (*post) *= x_dims[i]; } return true; } #define ELEMENTWISE_COMPUTE(OP) \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, pre, n, post, OP, stream); \ } else { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, 1, pixel_num, 1, OP, stream); \ } #define ELEMENTWISE_COMPUTE_ACT(OP) \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ auto act = param.act_type; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, pre, n, post, act, OP, stream); \ } else { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, 1, pixel_num, 1, act, OP, stream); \ } #define ELEMENTWISE_COMPUTE_NHWC(OP) \ std::map<int, int> pos_map = {{0, 0}, {1, 3}, {2, 1}, {3, 2}}; \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ if (axis < 0) axis = x->dims().size() - y->dims().size(); \ CHECK(axis >= 0) << "invalid axis of elementwise op"; \ axis = pos_map[axis]; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, pre, n, post, OP, stream); \ } else { \ lite::cuda::math::elementwise( \ x_data, y_data, out_data, 1, pixel_num, 1, OP, stream); \ } #define ELEMENTWISE_COMPUTE_ACT_NHWC(OP) \ std::map<int, int> pos_map = {{0, 0}, {1, 3}, {2, 1}, {3, 2}}; \ auto& param = this->Param<param_t>(); \ auto& ctx = this->ctx_->template As<CUDAContext>(); \ auto stream = ctx.exec_stream(); \ const lite::Tensor* x = param.X; \ const lite::Tensor* y = param.Y; \ lite::Tensor* out = param.Out; \ int axis = param.axis; \ if (axis < 0) axis = x->dims().size() - y->dims().size(); \ CHECK(axis >= 0) << "invalid axis of elementwise op"; \ axis = pos_map[axis]; \ auto* x_data = x->data<float>(); \ auto* y_data = y->data<float>(); \ auto out_data = out->mutable_data<float>(TARGET(kCUDA)); \ int pixel_num = x->numel(); \ int pre = 1; \ int n = pixel_num; \ int post = 1; \ auto act = param.act_type; \ if (is_broadcast(x->dims(), y->dims(), axis, &pre, &n, &post)) { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, pre, n, post, act, OP, stream); \ } else { \ lite::cuda::math::elementwise_act( \ x_data, y_data, out_data, 1, pixel_num, 1, act, OP, stream); \ } void ElementwiseAddCompute::Run() { ELEMENTWISE_COMPUTE(lite::cuda::math::BinaryOperation::kADD) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseAddComputeNHWC::Run() { ELEMENTWISE_COMPUTE_NHWC(lite::cuda::math::BinaryOperation::kADD) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseSubCompute::Run() { ELEMENTWISE_COMPUTE(lite::cuda::math::BinaryOperation::kSUB) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseSubComputeNHWC::Run() { ELEMENTWISE_COMPUTE_NHWC(lite::cuda::math::BinaryOperation::kSUB) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseMulCompute::Run() { ELEMENTWISE_COMPUTE(lite::cuda::math::BinaryOperation::kMUL) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseMulComputeNHWC::Run() { ELEMENTWISE_COMPUTE_NHWC(lite::cuda::math::BinaryOperation::kMUL) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseAddActivationCompute::Run() { ELEMENTWISE_COMPUTE_ACT(lite::cuda::math::BinaryOperation::kADD) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseAddActivationComputeNHWC::Run() { ELEMENTWISE_COMPUTE_ACT_NHWC(lite::cuda::math::BinaryOperation::kADD) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseSubActivationCompute::Run() { ELEMENTWISE_COMPUTE_ACT(lite::cuda::math::BinaryOperation::kSUB) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseSubActivationComputeNHWC::Run() { ELEMENTWISE_COMPUTE_ACT_NHWC(lite::cuda::math::BinaryOperation::kSUB) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseMulActivationCompute::Run() { ELEMENTWISE_COMPUTE_ACT(lite::cuda::math::BinaryOperation::kMUL) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } void ElementwiseMulActivationComputeNHWC::Run() { ELEMENTWISE_COMPUTE_ACT_NHWC(lite::cuda::math::BinaryOperation::kMUL) cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) LOG(INFO) << cudaGetErrorString(error); } } // namespace cuda } // namespace kernels } // namespace lite } // namespace paddle REGISTER_LITE_KERNEL(elementwise_add, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseAddCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_sub, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseSubCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_add, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseAddComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_sub, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseSubComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_mul, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseMulCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL(elementwise_mul, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseMulComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_add_activation, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseAddActivationCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_add_activation, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseAddActivationComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_sub_activation, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseSubActivationCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_sub_activation, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseSubActivationComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_mul_activation, kCUDA, kFloat, kNCHW, paddle::lite::kernels::cuda::ElementwiseMulActivationCompute, def) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA))}) .Finalize(); REGISTER_LITE_KERNEL( fusion_elementwise_mul_activation, kCUDA, kFloat, kNHWC, paddle::lite::kernels::cuda::ElementwiseMulActivationComputeNHWC, nhwc_format) .BindInput("X", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindInput("Y", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .BindOutput("Out", {LiteType::GetTensorTy(TARGET(kCUDA), PRECISION(kFloat), DATALAYOUT(kNHWC))}) .Finalize();
13c025c20e98090e932aa0062b8f6bae575ff884.hip
// !!! This is a file automatically generated by hipify!!! // Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "cudakernel/memory/scatter_elements.h" #include "cudakernel/common/divmod_fast.h" #include "cudakernel/common/memory_utils.h" #include "ppl/nn/common/tensor_shape.h" #include "ppl/common/retcode.h" #include <hip/hip_runtime.h> #include <assert.h> __device__ __inline__ int get_indices_val( int indices_element_size, int offset, const void* indices) { int res = 0; switch (indices_element_size) { case sizeof(int32_t): res = static_cast<const int32_t *>(indices)[offset]; break; case sizeof(int64_t): res = static_cast<const int64_t *>(indices)[offset]; break; default: break; } return res; } template <typename T> __global__ void ppl_cukernel_scatter_elements( int64_t num_updates, int num_updates_dim, GArray<DivModFast> updates_strides_fast, int axis, int input_axis_width, GArray<int64_t> input_strides, const T* updates, const T* input, T* output, int indices_element_size, const void* indices) { int index = blockIdx.x * blockDim.x + threadIdx.x; if (index >= num_updates) return; T update_val = updates[index]; int indices_val = get_indices_val(indices_element_size, index, indices); if (indices_val < 0) indices_val += input_axis_width; assert(indices_val >= 0 && indices_val < input_axis_width); int64_t output_offset = 0; int idx, remain = index; for (int it = 0; it < num_updates_dim; ++it) { updates_strides_fast[it].divmod(remain, idx, remain); if (it == axis) { idx = indices_val; } output_offset += idx * input_strides[it]; } output[output_offset] = update_val; } ppl::common::RetCode PPLCUDAScatterElementsForwardImp( hipStream_t stream, const ppl::nn::TensorShape* input_shape, const void* input, const ppl::nn::TensorShape* indices_shape, const void* indices, const ppl::nn::TensorShape* updates_shape, const void* updates, const ppl::nn::TensorShape* output_shape, void* output, int axis) { int64_t num_elems = output_shape->GetElementsIncludingPadding(); hipMemcpyAsync(output, input, ppl::common::GetSizeOfDataType(input_shape->GetDataType()) * num_elems, hipMemcpyDeviceToDevice, stream); int64_t num_updates = updates_shape->GetElementsIncludingPadding(); int num_updates_dim = updates_shape->GetDimCount(); GArray<DivModFast> updates_strides_fast(num_updates_dim); GArray<int64_t> input_strides(num_updates_dim); int64_t acc_updates_stride = 1; int64_t acc_input_stride = 1; for (int it = num_updates_dim - 1; it >= 0; --it) { input_strides[it] = acc_input_stride; updates_strides_fast[it] = DivModFast(acc_updates_stride); acc_input_stride *= input_shape->GetDim(it); acc_updates_stride *= updates_shape->GetDim(it); } int block_size = 256; int grid_size = (num_updates + block_size - 1) / block_size; int indices_element_size = ppl::common::GetSizeOfDataType(indices_shape->GetDataType()); int input_axis_width = input_shape->GetDim(axis); #define SWITCH_CASE(TYPE) \ case sizeof(TYPE): { \ hipLaunchKernelGGL(( ppl_cukernel_scatter_elements), dim3(grid_size), dim3(block_size), 0, stream, num_updates, num_updates_dim, \ updates_strides_fast, axis, input_axis_width, input_strides, (const TYPE *)updates, \ (const TYPE *)input, (TYPE *)output, indices_element_size, (const void *)indices); \ return ppl::common::RC_SUCCESS; \ } switch (ppl::common::GetSizeOfDataType(input_shape->GetDataType())) { SWITCH_CASE(int8_t); SWITCH_CASE(int16_t); SWITCH_CASE(int32_t); SWITCH_CASE(int64_t); default: return ppl::common::RC_UNSUPPORTED; } #undef SWITCH_CASE }
13c025c20e98090e932aa0062b8f6bae575ff884.cu
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you under the Apache License, Version 2.0 (the // "License"); you may not use this file except in compliance // with the License. You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an // "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY // KIND, either express or implied. See the License for the // specific language governing permissions and limitations // under the License. #include "cudakernel/memory/scatter_elements.h" #include "cudakernel/common/divmod_fast.h" #include "cudakernel/common/memory_utils.h" #include "ppl/nn/common/tensor_shape.h" #include "ppl/common/retcode.h" #include <cuda_runtime.h> #include <assert.h> __device__ __inline__ int get_indices_val( int indices_element_size, int offset, const void* indices) { int res = 0; switch (indices_element_size) { case sizeof(int32_t): res = static_cast<const int32_t *>(indices)[offset]; break; case sizeof(int64_t): res = static_cast<const int64_t *>(indices)[offset]; break; default: break; } return res; } template <typename T> __global__ void ppl_cukernel_scatter_elements( int64_t num_updates, int num_updates_dim, GArray<DivModFast> updates_strides_fast, int axis, int input_axis_width, GArray<int64_t> input_strides, const T* updates, const T* input, T* output, int indices_element_size, const void* indices) { int index = blockIdx.x * blockDim.x + threadIdx.x; if (index >= num_updates) return; T update_val = updates[index]; int indices_val = get_indices_val(indices_element_size, index, indices); if (indices_val < 0) indices_val += input_axis_width; assert(indices_val >= 0 && indices_val < input_axis_width); int64_t output_offset = 0; int idx, remain = index; for (int it = 0; it < num_updates_dim; ++it) { updates_strides_fast[it].divmod(remain, idx, remain); if (it == axis) { idx = indices_val; } output_offset += idx * input_strides[it]; } output[output_offset] = update_val; } ppl::common::RetCode PPLCUDAScatterElementsForwardImp( cudaStream_t stream, const ppl::nn::TensorShape* input_shape, const void* input, const ppl::nn::TensorShape* indices_shape, const void* indices, const ppl::nn::TensorShape* updates_shape, const void* updates, const ppl::nn::TensorShape* output_shape, void* output, int axis) { int64_t num_elems = output_shape->GetElementsIncludingPadding(); cudaMemcpyAsync(output, input, ppl::common::GetSizeOfDataType(input_shape->GetDataType()) * num_elems, cudaMemcpyDeviceToDevice, stream); int64_t num_updates = updates_shape->GetElementsIncludingPadding(); int num_updates_dim = updates_shape->GetDimCount(); GArray<DivModFast> updates_strides_fast(num_updates_dim); GArray<int64_t> input_strides(num_updates_dim); int64_t acc_updates_stride = 1; int64_t acc_input_stride = 1; for (int it = num_updates_dim - 1; it >= 0; --it) { input_strides[it] = acc_input_stride; updates_strides_fast[it] = DivModFast(acc_updates_stride); acc_input_stride *= input_shape->GetDim(it); acc_updates_stride *= updates_shape->GetDim(it); } int block_size = 256; int grid_size = (num_updates + block_size - 1) / block_size; int indices_element_size = ppl::common::GetSizeOfDataType(indices_shape->GetDataType()); int input_axis_width = input_shape->GetDim(axis); #define SWITCH_CASE(TYPE) \ case sizeof(TYPE): { \ ppl_cukernel_scatter_elements<<<grid_size, block_size, 0, stream>>>(num_updates, num_updates_dim, \ updates_strides_fast, axis, input_axis_width, input_strides, (const TYPE *)updates, \ (const TYPE *)input, (TYPE *)output, indices_element_size, (const void *)indices); \ return ppl::common::RC_SUCCESS; \ } switch (ppl::common::GetSizeOfDataType(input_shape->GetDataType())) { SWITCH_CASE(int8_t); SWITCH_CASE(int16_t); SWITCH_CASE(int32_t); SWITCH_CASE(int64_t); default: return ppl::common::RC_UNSUPPORTED; } #undef SWITCH_CASE }
cf24c0f4e95c3a6d78a72904e346dfc9220cc040.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <iostream> #include <vector> #ifndef WIN64 #define EIGEN_DONT_ALIGN_STATICALLY #endif #include <Eigen/Dense> #include <Eigen/Cholesky> #include <sophus/se3.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "aux.h" #include "helper.hpp" #include "downsample.cuh" #include "gradient.cuh" #include "jacobian.cuh" #include "tum_benchmark.hpp" #include "save_ply.hpp" #include "viewer.hpp" #define STR1(x) #x #define STR(x) STR1(x) typedef Eigen::Matrix<float, 6, 6> Mat6f; typedef Eigen::Matrix<float, 6, 1> Vec6f; bool useGpu = false; int numIterations = 20; int numPyramidLevels = 5; int maxLevel = numPyramidLevels-1; int minLevel = 1; float errorImprovementStop = 0.995f; //0.99f Eigen::Matrix3f K; double runtimeAvg = 0.0; /*void align(const cv::Mat &depthRefIn, const cv::Mat &grayRefIn, const cv::Mat &depthCurIn, const cv::Mat &grayCurIn, Vec6f& xi) { //TODO //... }*/ int main(int argc, char *argv[]) { std::string dataFolder = std::string(STR(DVO_CUDA_SOURCE_DIR)) + "/data/"; // load file names std::string assocFile = dataFolder + "rgbd_assoc.txt"; std::vector<std::string> filesColor; std::vector<std::string> filesDepth; std::vector<double> timestampsDepth; std::vector<double> timestampsColor; if (!loadAssoc(assocFile, filesDepth, filesColor, timestampsDepth, timestampsColor)) { std::cout << "Assoc file could not be loaded!" << std::endl; return 1; } int numFrames = filesDepth.size(); // initialize cuda context hipDeviceSynchronize(); CUDA_CHECK; // initialize intrinsic matrix K << 517.3, 0.0, 318.6, 0.0, 516.5, 255.3, 0.0, 0.0, 1.0; //std::cout << "Camera matrix: " << K << std::endl; int maxFrames = -1; //maxFrames = 20; bool canceled = false; // process frames Eigen::Matrix4f absPose = Eigen::Matrix4f::Identity(); std::vector<Eigen::Matrix4f> poses; std::vector<double> timestamps; poses.push_back(absPose); timestamps.push_back(timestampsDepth[0]); int framesProcessed = 0; cv::Mat colorPrev = loadColor(dataFolder + filesColor[0]); cv::Mat grayPrev; cv::cvtColor(colorPrev, grayPrev, CV_BGR2GRAY); cv::Mat depthPrev = loadDepth(dataFolder + filesDepth[0]); #if 1 cv::Mat vertexMap0; depthToVertexMap(K.cast<double>(), depthPrev, vertexMap0); cv::Mat color0UC; colorPrev.convertTo(color0UC, CV_8UC3, 255.0f); canceled = !updateViewer(vertexMap0, color0UC, absPose); #endif for (size_t i = 1; i < numFrames && (maxFrames < 0 || i < maxFrames) && !canceled; ++i) { // load input frame std::string fileColor1 = filesColor[i]; std::string fileDepth1 = filesDepth[i]; double timeDepth1 = timestampsDepth[i]; //std::cout << "File " << i << ": " << fileColor1 << ", " << fileDepth1 << std::endl; cv::Mat color0 = colorPrev; cv::Mat depth0 = depthPrev; cv::Mat gray0 = grayPrev; cv::Mat color1 = loadColor(dataFolder + fileColor1); cv::Mat depth1 = loadDepth(dataFolder + fileDepth1); cv::Mat gray1; cv::cvtColor(color1, gray1, CV_BGR2GRAY); cv::Mat grayRef = gray0; cv::Mat depthRef = depth0; cv::Mat grayCur = gray1; cv::Mat depthCur = depth1; // frame alignment Vec6f xi = Vec6f::Zero(); { // get image dimensions int w = grayRef.cols; // width int h = grayRef.rows; // height double tmr = 0; // initialize intrinsic matrix Eigen::Matrix3f K; K << 517.3, 0.0, 318.6, 0.0, 516.5, 255.3, 0.0, 0.0, 1.0; // initial pose Eigen::Matrix3f rot; Eigen::Vector3f t; // Vec6f xi = Vec6f::Zero(); convertSE3ToTf(xi, rot, t); //Saving the finest level of images std::vector<Eigen::Matrix3f> kPyramid; kPyramid.push_back(K); //Downsampling K for (int i = LVL-1; i > 0; i--) { K = scaleIntrinsic(K); kPyramid.push_back(K); } int nbytes = w*h*sizeof(float); float *d_curImg0, *d_curImg1, *d_curImg2, *d_curImg3; float *d_refImg0, *d_refImg1, *d_refImg2, *d_refImg3; float *d_depthcur0, *d_depthcur1, *d_depthcur2, *d_depthcur3; float *d_depthref0, *d_depthref1, *d_depthref2, *d_depthref3; float *d_resImg0, *d_resImg1, *d_resImg2, *d_resImg3; float *d_jacobif0, *d_jacobif1, *d_jacobif2, *d_jacobif3; float *JtJ_final0, *JtJ_final1, *JtJ_final2, *JtJ_final3; float *Jtb_final0, *Jtb_final1, *Jtb_final2, *Jtb_final3; float *d_vx0, *d_vx1, *d_vx2, *d_vx3; float *d_vy0, *d_vy1, *d_vy2, *d_vy3; hipMalloc(&d_jacobif0, w*h*6*sizeof(float)); CUDA_CHECK; hipMalloc(&d_jacobif1, w/2*h/2*6*sizeof(float)); CUDA_CHECK; hipMalloc(&d_jacobif2, w/4*h/4*6*sizeof(float)); CUDA_CHECK; hipMalloc(&d_jacobif3, w/8*h/8*6*sizeof(float)); CUDA_CHECK; hipMalloc(&JtJ_final0, w*h*21*sizeof(float)); CUDA_CHECK; hipMalloc(&JtJ_final1, w/2*h/2*21*sizeof(float)); CUDA_CHECK; hipMalloc(&JtJ_final2, w/4*h/4*21*sizeof(float)); CUDA_CHECK; hipMalloc(&JtJ_final3, w/8*h/8*21*sizeof(float)); CUDA_CHECK; hipMalloc(&Jtb_final0, w*h*6*sizeof(float)); CUDA_CHECK; hipMalloc(&Jtb_final1, w/2*h/2*6*sizeof(float)); CUDA_CHECK; hipMalloc(&Jtb_final2, w/4*h/4*6*sizeof(float)); CUDA_CHECK; hipMalloc(&Jtb_final3, w/8*h/8*6*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vx0, w*h*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vx1, w/2*h/2*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vx2, w/4*h/4*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vx3, w/8*w/8*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vy0, w*h*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vy1, w/2*h/2*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vy2, w/4*h/4*sizeof(float)); CUDA_CHECK; hipMalloc(&d_vy3, w/8*h/8*sizeof(float)); CUDA_CHECK; hipMalloc(&d_resImg0,nbytes); CUDA_CHECK; hipMemset(d_resImg0, 0, nbytes); CUDA_CHECK; hipMalloc(&d_resImg1,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMemset(d_resImg1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMalloc(&d_resImg2,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMemset(d_resImg2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMalloc(&d_resImg3,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMemset(d_resImg3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMalloc(&d_curImg0,nbytes); CUDA_CHECK; hipMemcpy(d_curImg0, (void*)grayCur.data, nbytes, hipMemcpyHostToDevice); CUDA_CHECK; hipMalloc(&d_curImg1,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMemset(d_curImg1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMalloc(&d_curImg2,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMemset(d_curImg2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMalloc(&d_curImg3,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMemset(d_curImg3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMalloc(&d_refImg0,nbytes); CUDA_CHECK; hipMemcpy(d_refImg0, (void*)grayRef.data,nbytes, hipMemcpyHostToDevice); CUDA_CHECK; hipMalloc(&d_refImg1,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMemset(d_refImg1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMalloc(&d_refImg2,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMemset(d_refImg2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMalloc(&d_refImg3,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMemset(d_refImg3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMalloc(&d_depthcur0,nbytes); CUDA_CHECK; hipMemcpy(d_depthcur0, (void*)depthCur.data, nbytes, hipMemcpyHostToDevice); CUDA_CHECK; hipMalloc(&d_depthcur1,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMemset(d_depthcur1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMalloc(&d_depthcur2,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMemset(d_depthcur2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMalloc(&d_depthcur3,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMemset(d_depthcur3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMalloc(&d_depthref0,nbytes); CUDA_CHECK; hipMemcpy(d_depthref0, (void*)depthRef.data, nbytes, hipMemcpyHostToDevice); CUDA_CHECK; hipMalloc(&d_depthref1,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMemset(d_depthref1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; hipMalloc(&d_depthref2,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMemset(d_depthref2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; hipMalloc(&d_depthref3,w/8*h/8*sizeof(float)); CUDA_CHECK; hipMemset(d_depthref3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; std::vector<float *> JtJPyramid; JtJPyramid.push_back(JtJ_final0); JtJPyramid.push_back(JtJ_final1); JtJPyramid.push_back(JtJ_final2); JtJPyramid.push_back(JtJ_final3); std::vector<float *> jacobifPyramid; jacobifPyramid.push_back(d_jacobif0); jacobifPyramid.push_back(d_jacobif1); jacobifPyramid.push_back(d_jacobif2); jacobifPyramid.push_back(d_jacobif3); std::vector<float *> JtbPyramid; JtbPyramid.push_back(Jtb_final0); JtbPyramid.push_back(Jtb_final1); JtbPyramid.push_back(Jtb_final2); JtbPyramid.push_back(Jtb_final3); std::vector<float *> dvxPyramid; dvxPyramid.push_back(d_vx0); dvxPyramid.push_back(d_vx1); dvxPyramid.push_back(d_vx2); dvxPyramid.push_back(d_vx3); std::vector<float *> dvyPyramid; dvyPyramid.push_back(d_vy0); dvyPyramid.push_back(d_vy1); dvyPyramid.push_back(d_vy2); dvyPyramid.push_back(d_vy3); std::vector<float *> grayRefPyramid; grayRefPyramid.push_back(d_refImg0); grayRefPyramid.push_back(d_refImg1); grayRefPyramid.push_back(d_refImg2); grayRefPyramid.push_back(d_refImg3); std::vector<float *> depthRefPyramid; depthRefPyramid.push_back(d_depthref0); depthRefPyramid.push_back(d_depthref1); depthRefPyramid.push_back(d_depthref2); depthRefPyramid.push_back(d_depthref3); std::vector<float *> grayCurPyramid; grayCurPyramid.push_back(d_curImg0); grayCurPyramid.push_back(d_curImg1); grayCurPyramid.push_back(d_curImg2); grayCurPyramid.push_back(d_curImg3); std::vector<float *> depthCurPyramid; depthCurPyramid.push_back(d_depthcur0); depthCurPyramid.push_back(d_depthcur1); depthCurPyramid.push_back(d_depthcur2); depthCurPyramid.push_back(d_depthcur3); std::vector<float *> residualPyramid; residualPyramid.push_back(d_resImg0); residualPyramid.push_back(d_resImg1); residualPyramid.push_back(d_resImg2); residualPyramid.push_back(d_resImg3); // initialize cuda context hipDeviceSynchronize(); CUDA_CHECK; downSample(grayRefPyramid, depthRefPyramid, grayCurPyramid, depthCurPyramid, w, h); float *result = new float[(size_t)1]; float *A_interim = new float[(size_t)21]; float *b_interim = new float[(size_t)6]; Mat6f A = Mat6f::Zero(); Vec6f b = Vec6f::Zero(); for (int level = LVL; level>0 ; level--) { int width = w/pow(2,level-1); int height = h/pow(2,level-1); // initialize intrinsic matrix Eigen::Matrix3f kLevel = kPyramid[level-1]; // initialize cuda context hipDeviceSynchronize(); CUDA_CHECK; // copy data to device // Current grayscale image float *d_currImg = grayCurPyramid[level - 1] ; // Reference grayscale image float *d_refimgIn = grayRefPyramid[level -1]; //Current depth image float *d_depthImgIn = depthCurPyramid[level-1]; //Reference depth image float *d_refdepthImgIn = depthRefPyramid[level-1]; //Residual Image float *d_resImg = residualPyramid[level-1]; float *d_rot, *d_t; float fx = kLevel(0,0); float fy = kLevel(1,1); float cx = kLevel(0,2); float cy = kLevel(1,2); size_t n_d_vx = (size_t)width*height; size_t n_d_vy = (size_t)width*height; int N = width*height; float *d_jacobif = jacobifPyramid[level-1]; float *d_vx = dvxPyramid[level-1]; float *d_vy = dvyPyramid[level-1]; float *JtJ_final = JtJPyramid[level-1]; float *Jtb_final = JtbPyramid[level-1]; hipMalloc(&d_rot, 9*sizeof(float)); CUDA_CHECK; hipMalloc(&d_t, 3*sizeof(float)); CUDA_CHECK; float errLast = std::numeric_limits<float>::max(); for(int i = 0; i < ITER ; i++) { float *rot_data = rot.data(); float *t_data = t.data(); hipMemset(d_vy, 0, n_d_vy*sizeof(float)); CUDA_CHECK; hipMemset(d_vx, 0, n_d_vx*sizeof(float)); CUDA_CHECK; hipMemset(Jtb_final, 0, N*6*sizeof(float)); CUDA_CHECK; hipMemset(JtJ_final, 0, N*21*sizeof(float)); CUDA_CHECK; hipMemset(d_jacobif, 0, N*6*sizeof(float)); CUDA_CHECK; hipMemcpy(d_rot,rot_data,9*sizeof(float),hipMemcpyHostToDevice); CUDA_CHECK; hipMemcpy(d_t,t_data,3*sizeof(float),hipMemcpyHostToDevice); CUDA_CHECK; dim3 block = dim3(32, 8, 1); dim3 grid = dim3((width+block.x-1)/block.x, (height+block.y-1)/block.y, 1); //Texture Memory texRef.addressMode[0] = hipAddressModeClamp; texRef.addressMode[1] = hipAddressModeClamp; texRef.filterMode = hipFilterModeLinear; texRef.normalized = false; hipChannelFormatDesc desc = hipCreateChannelDesc<float>(); hipBindTexture2D(NULL, &texRef, d_currImg, &desc, width, height, width*sizeof(d_currImg[0])); texGradX.addressMode[0] = hipAddressModeClamp; texGradX.addressMode[1] = hipAddressModeClamp; texGradX.filterMode = hipFilterModeLinear; texGradX.normalized = false; hipChannelFormatDesc descX = hipCreateChannelDesc<float>(); hipBindTexture2D(NULL, &texGradX, d_vx, &descX, width, height, width*sizeof(d_vx[0])); texGradY.addressMode[0] = hipAddressModeClamp; texGradY.addressMode[1] = hipAddressModeClamp; texGradY.filterMode = hipFilterModeLinear; texGradY.normalized = false; hipChannelFormatDesc descY = hipCreateChannelDesc<float>(); hipBindTexture2D(NULL, &texGradY, d_vy, &descY, width, height, width*sizeof(d_vy[0])); hipLaunchKernelGGL(( calcErr) , dim3(grid),dim3(block), 0, 0, d_refimgIn,d_currImg,d_refdepthImgIn,d_resImg,d_rot,d_t,fx,fy,cx,cy,width,height); CUDA_CHECK; hipLaunchKernelGGL(( gradCompute) , dim3(grid),dim3(block), 0, 0, d_currImg,d_vx,d_vy,width,height); CUDA_CHECK; hipLaunchKernelGGL(( deriveNumeric) , dim3(grid),dim3(block), 0, 0, d_vx,d_vy,d_refdepthImgIn,d_resImg,d_jacobif,width,height,fx,fy,cx,cy,d_rot,d_t,JtJ_final,Jtb_final); CUDA_CHECK; cv::Mat residualGPU(height,width,grayRef.type()); hipMemcpy((void *)residualGPU.data,d_resImg,N*sizeof(float),hipMemcpyDeviceToHost); CUDA_CHECK; Eigen::VectorXf residual(N); int idx = 0; for(int i =0 ;i<width;i++) { for(int j =0 ;j<height;j++) { residual[idx] = residualGPU.at<float>(i,j); idx++; } } dim3 block1 = dim3(128, 1, 1); dim3 grid1 = dim3((N + block1.x -1)/block1.x,1,1); size_t smBytes = block1.x * block1.y * block1.z * sizeof(float); //Reduction for JtJ float* ptrJtJ = JtJ_final; for(int j = 0; j<21; j++) { hipLaunchKernelGGL(( block_sum) , dim3(grid1),dim3(block1),smBytes, 0, ptrJtJ,ptrJtJ,N); for(int offset = block1.x / 2;offset > 0;offset >>= 1) hipLaunchKernelGGL(( block_sum) , dim3(grid1),dim3(block1),smBytes, 0, ptrJtJ,ptrJtJ,N); hipMemcpy(result,ptrJtJ,sizeof(float),hipMemcpyDeviceToHost); CUDA_CHECK; A_interim[j]= result[0]; ptrJtJ = ptrJtJ + N; } int k = 0; for(int i = 0; i<6; i++) { for(int j = i; j<6; j++) { A(i,j) = A(j,i) =A_interim[k]; k++; } } float *ptrJtb = Jtb_final; for(int j = 0; j<6; j++) { hipLaunchKernelGGL(( block_sum) , dim3(grid1),dim3(block1),smBytes, 0, ptrJtb,ptrJtb,N); for(int offset = block1.x / 2;offset > 0;offset >>= 1) hipLaunchKernelGGL(( block_sum) , dim3(grid1),dim3(block1),smBytes, 0, ptrJtb,ptrJtb,N); hipMemcpy(result,ptrJtb,sizeof(float),hipMemcpyDeviceToHost); CUDA_CHECK; b_interim[j]= result[0]; ptrJtb = ptrJtb + N; } for(int i = 0; i<6; i++) b(i) = b_interim[i]; // solve using Cholesky LDLT decomposition Vec6f delta = -(A.ldlt().solve(b)); // update xi xi = Sophus::SE3f::log(Sophus::SE3f::exp(delta)*Sophus::SE3f::exp(xi)); hipUnbindTexture(texRef); hipUnbindTexture(texGradX); hipUnbindTexture(texGradY); // print out final pose convertSE3ToTf(xi, rot, t); /*std::cout << "xi = " << xi.transpose() << std::endl; Eigen::VectorXd xiResult(6); xiResult << -0.0021f, 0.0057f, 0.0374f, -0.0292f, -0.0183f, -0.0009f; std::cout << "xi expected = " << xiResult.transpose() << std::endl;*/ float error = (residual.cwiseProduct(residual)).mean(); if((error/errLast) > 0.995f) break; errLast = error; } hipFree(d_rot); CUDA_CHECK; hipFree(d_t); CUDA_CHECK; width = width * 2; height = height * 2; tmr = ((double)cv::getTickCount() - tmr)/cv::getTickFrequency(); std::cout << "runtime: " << tmr * 1000.0 << " ms" << std::endl; runtimeAvg += tmr; } delete[] result; delete[] A_interim; delete[] b_interim; hipFree(d_curImg0); CUDA_CHECK; hipFree(d_curImg1); CUDA_CHECK; hipFree(d_curImg2); CUDA_CHECK; hipFree(d_curImg3); CUDA_CHECK; hipFree(d_depthref0); CUDA_CHECK; hipFree(d_depthref1); CUDA_CHECK; hipFree(d_depthref2); CUDA_CHECK; hipFree(d_depthref3); CUDA_CHECK; hipFree(d_refImg0); CUDA_CHECK; hipFree(d_refImg1); CUDA_CHECK; hipFree(d_refImg2); CUDA_CHECK; hipFree(d_refImg3); CUDA_CHECK; hipFree(d_depthcur0); CUDA_CHECK; hipFree(d_depthcur1); CUDA_CHECK; hipFree(d_depthcur2); CUDA_CHECK; hipFree(d_depthcur3); CUDA_CHECK; hipFree(d_resImg0); CUDA_CHECK; hipFree(d_resImg1); CUDA_CHECK; hipFree(d_resImg2); CUDA_CHECK; hipFree(d_resImg3); CUDA_CHECK; hipFree(d_vx0); CUDA_CHECK; hipFree(d_vx1); CUDA_CHECK; hipFree(d_vx2); CUDA_CHECK; hipFree(d_vx3); CUDA_CHECK; hipFree(d_vy0); CUDA_CHECK; hipFree(d_vy1); CUDA_CHECK; hipFree(d_vy2); CUDA_CHECK; hipFree(d_vy3); CUDA_CHECK; hipFree(d_jacobif0); CUDA_CHECK; hipFree(d_jacobif1); CUDA_CHECK; hipFree(d_jacobif2); CUDA_CHECK; hipFree(d_jacobif3); CUDA_CHECK; hipFree(JtJ_final0); CUDA_CHECK; hipFree(JtJ_final1); CUDA_CHECK; hipFree(JtJ_final2); CUDA_CHECK; hipFree(JtJ_final3); CUDA_CHECK; hipFree(Jtb_final0); CUDA_CHECK; hipFree(Jtb_final1); CUDA_CHECK; hipFree(Jtb_final2); CUDA_CHECK; hipFree(Jtb_final3); CUDA_CHECK; } Eigen::Matrix3f rot; Eigen::Vector3f t; convertSE3ToTf(xi, rot, t); std::cout << "pose (xi) between frames " << (i-1) << " and " << i << ": " << xi.transpose() << std::endl; // concatenate poses Eigen::Matrix4f relPose = Eigen::Matrix4f::Identity(); relPose.topLeftCorner(3,3) = rot; relPose.topRightCorner(3,1) = t; absPose = absPose * relPose.inverse(); poses.push_back(absPose); timestamps.push_back(timeDepth1); rot = absPose.topLeftCorner(3,3); t = absPose.topRightCorner(3,1); cv::Mat vertexMap1; depthToVertexMap(K.cast<double>(), depth1, vertexMap1); cv::Mat vertexMapTf1 = vertexMap1.clone(); transformVertexMap(rot.cast<double>(), t.cast<double>(), vertexMapTf1); cv::Mat color1UC; color1.convertTo(color1UC, CV_8UC3, 255.0f); #if 0 // save frames as point cloud std::stringstream ss; ss << dataFolder << "cloud_" << std::setw(4) << std::setfill('0') << i << ".ply"; savePlyFile(ss.str(), color1UC, vertexMapTf1); #endif #if 1 canceled = !updateViewer(vertexMap1, color1UC, absPose); #endif colorPrev = color1; depthPrev = depth1; grayPrev = gray1; ++framesProcessed; } stopViewer(); std::cout << "average runtime: " << (runtimeAvg / framesProcessed) * 1000.0 << " ms" << std::endl; // save poses savePoses(dataFolder + "traj.txt", poses, timestamps); #if 0 cv::waitKey(0); #endif // clean up cv::destroyAllWindows(); std::cout << "Direct Image Alignment finished." << std::endl; return 0; }
cf24c0f4e95c3a6d78a72904e346dfc9220cc040.cu
#include <iostream> #include <vector> #ifndef WIN64 #define EIGEN_DONT_ALIGN_STATICALLY #endif #include <Eigen/Dense> #include <Eigen/Cholesky> #include <sophus/se3.hpp> #include <opencv2/core/core.hpp> #include <opencv2/highgui/highgui.hpp> #include <opencv2/imgproc/imgproc.hpp> #include "aux.h" #include "helper.hpp" #include "downsample.cuh" #include "gradient.cuh" #include "jacobian.cuh" #include "tum_benchmark.hpp" #include "save_ply.hpp" #include "viewer.hpp" #define STR1(x) #x #define STR(x) STR1(x) typedef Eigen::Matrix<float, 6, 6> Mat6f; typedef Eigen::Matrix<float, 6, 1> Vec6f; bool useGpu = false; int numIterations = 20; int numPyramidLevels = 5; int maxLevel = numPyramidLevels-1; int minLevel = 1; float errorImprovementStop = 0.995f; //0.99f Eigen::Matrix3f K; double runtimeAvg = 0.0; /*void align(const cv::Mat &depthRefIn, const cv::Mat &grayRefIn, const cv::Mat &depthCurIn, const cv::Mat &grayCurIn, Vec6f& xi) { //TODO //... }*/ int main(int argc, char *argv[]) { std::string dataFolder = std::string(STR(DVO_CUDA_SOURCE_DIR)) + "/data/"; // load file names std::string assocFile = dataFolder + "rgbd_assoc.txt"; std::vector<std::string> filesColor; std::vector<std::string> filesDepth; std::vector<double> timestampsDepth; std::vector<double> timestampsColor; if (!loadAssoc(assocFile, filesDepth, filesColor, timestampsDepth, timestampsColor)) { std::cout << "Assoc file could not be loaded!" << std::endl; return 1; } int numFrames = filesDepth.size(); // initialize cuda context cudaDeviceSynchronize(); CUDA_CHECK; // initialize intrinsic matrix K << 517.3, 0.0, 318.6, 0.0, 516.5, 255.3, 0.0, 0.0, 1.0; //std::cout << "Camera matrix: " << K << std::endl; int maxFrames = -1; //maxFrames = 20; bool canceled = false; // process frames Eigen::Matrix4f absPose = Eigen::Matrix4f::Identity(); std::vector<Eigen::Matrix4f> poses; std::vector<double> timestamps; poses.push_back(absPose); timestamps.push_back(timestampsDepth[0]); int framesProcessed = 0; cv::Mat colorPrev = loadColor(dataFolder + filesColor[0]); cv::Mat grayPrev; cv::cvtColor(colorPrev, grayPrev, CV_BGR2GRAY); cv::Mat depthPrev = loadDepth(dataFolder + filesDepth[0]); #if 1 cv::Mat vertexMap0; depthToVertexMap(K.cast<double>(), depthPrev, vertexMap0); cv::Mat color0UC; colorPrev.convertTo(color0UC, CV_8UC3, 255.0f); canceled = !updateViewer(vertexMap0, color0UC, absPose); #endif for (size_t i = 1; i < numFrames && (maxFrames < 0 || i < maxFrames) && !canceled; ++i) { // load input frame std::string fileColor1 = filesColor[i]; std::string fileDepth1 = filesDepth[i]; double timeDepth1 = timestampsDepth[i]; //std::cout << "File " << i << ": " << fileColor1 << ", " << fileDepth1 << std::endl; cv::Mat color0 = colorPrev; cv::Mat depth0 = depthPrev; cv::Mat gray0 = grayPrev; cv::Mat color1 = loadColor(dataFolder + fileColor1); cv::Mat depth1 = loadDepth(dataFolder + fileDepth1); cv::Mat gray1; cv::cvtColor(color1, gray1, CV_BGR2GRAY); cv::Mat grayRef = gray0; cv::Mat depthRef = depth0; cv::Mat grayCur = gray1; cv::Mat depthCur = depth1; // frame alignment Vec6f xi = Vec6f::Zero(); { // get image dimensions int w = grayRef.cols; // width int h = grayRef.rows; // height double tmr = 0; // initialize intrinsic matrix Eigen::Matrix3f K; K << 517.3, 0.0, 318.6, 0.0, 516.5, 255.3, 0.0, 0.0, 1.0; // initial pose Eigen::Matrix3f rot; Eigen::Vector3f t; // Vec6f xi = Vec6f::Zero(); convertSE3ToTf(xi, rot, t); //Saving the finest level of images std::vector<Eigen::Matrix3f> kPyramid; kPyramid.push_back(K); //Downsampling K for (int i = LVL-1; i > 0; i--) { K = scaleIntrinsic(K); kPyramid.push_back(K); } int nbytes = w*h*sizeof(float); float *d_curImg0, *d_curImg1, *d_curImg2, *d_curImg3; float *d_refImg0, *d_refImg1, *d_refImg2, *d_refImg3; float *d_depthcur0, *d_depthcur1, *d_depthcur2, *d_depthcur3; float *d_depthref0, *d_depthref1, *d_depthref2, *d_depthref3; float *d_resImg0, *d_resImg1, *d_resImg2, *d_resImg3; float *d_jacobif0, *d_jacobif1, *d_jacobif2, *d_jacobif3; float *JtJ_final0, *JtJ_final1, *JtJ_final2, *JtJ_final3; float *Jtb_final0, *Jtb_final1, *Jtb_final2, *Jtb_final3; float *d_vx0, *d_vx1, *d_vx2, *d_vx3; float *d_vy0, *d_vy1, *d_vy2, *d_vy3; cudaMalloc(&d_jacobif0, w*h*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_jacobif1, w/2*h/2*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_jacobif2, w/4*h/4*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_jacobif3, w/8*h/8*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&JtJ_final0, w*h*21*sizeof(float)); CUDA_CHECK; cudaMalloc(&JtJ_final1, w/2*h/2*21*sizeof(float)); CUDA_CHECK; cudaMalloc(&JtJ_final2, w/4*h/4*21*sizeof(float)); CUDA_CHECK; cudaMalloc(&JtJ_final3, w/8*h/8*21*sizeof(float)); CUDA_CHECK; cudaMalloc(&Jtb_final0, w*h*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&Jtb_final1, w/2*h/2*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&Jtb_final2, w/4*h/4*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&Jtb_final3, w/8*h/8*6*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vx0, w*h*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vx1, w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vx2, w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vx3, w/8*w/8*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vy0, w*h*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vy1, w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vy2, w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_vy3, w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_resImg0,nbytes); CUDA_CHECK; cudaMemset(d_resImg0, 0, nbytes); CUDA_CHECK; cudaMalloc(&d_resImg1,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMemset(d_resImg1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_resImg2,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMemset(d_resImg2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_resImg3,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMemset(d_resImg3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_curImg0,nbytes); CUDA_CHECK; cudaMemcpy(d_curImg0, (void*)grayCur.data, nbytes, cudaMemcpyHostToDevice); CUDA_CHECK; cudaMalloc(&d_curImg1,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMemset(d_curImg1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_curImg2,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMemset(d_curImg2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_curImg3,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMemset(d_curImg3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_refImg0,nbytes); CUDA_CHECK; cudaMemcpy(d_refImg0, (void*)grayRef.data,nbytes, cudaMemcpyHostToDevice); CUDA_CHECK; cudaMalloc(&d_refImg1,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMemset(d_refImg1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_refImg2,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMemset(d_refImg2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_refImg3,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMemset(d_refImg3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_depthcur0,nbytes); CUDA_CHECK; cudaMemcpy(d_depthcur0, (void*)depthCur.data, nbytes, cudaMemcpyHostToDevice); CUDA_CHECK; cudaMalloc(&d_depthcur1,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMemset(d_depthcur1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_depthcur2,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMemset(d_depthcur2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_depthcur3,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMemset(d_depthcur3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_depthref0,nbytes); CUDA_CHECK; cudaMemcpy(d_depthref0, (void*)depthRef.data, nbytes, cudaMemcpyHostToDevice); CUDA_CHECK; cudaMalloc(&d_depthref1,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMemset(d_depthref1,0,w/2*h/2*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_depthref2,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMemset(d_depthref2,0,w/4*h/4*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_depthref3,w/8*h/8*sizeof(float)); CUDA_CHECK; cudaMemset(d_depthref3,0,w/8*h/8*sizeof(float)); CUDA_CHECK; std::vector<float *> JtJPyramid; JtJPyramid.push_back(JtJ_final0); JtJPyramid.push_back(JtJ_final1); JtJPyramid.push_back(JtJ_final2); JtJPyramid.push_back(JtJ_final3); std::vector<float *> jacobifPyramid; jacobifPyramid.push_back(d_jacobif0); jacobifPyramid.push_back(d_jacobif1); jacobifPyramid.push_back(d_jacobif2); jacobifPyramid.push_back(d_jacobif3); std::vector<float *> JtbPyramid; JtbPyramid.push_back(Jtb_final0); JtbPyramid.push_back(Jtb_final1); JtbPyramid.push_back(Jtb_final2); JtbPyramid.push_back(Jtb_final3); std::vector<float *> dvxPyramid; dvxPyramid.push_back(d_vx0); dvxPyramid.push_back(d_vx1); dvxPyramid.push_back(d_vx2); dvxPyramid.push_back(d_vx3); std::vector<float *> dvyPyramid; dvyPyramid.push_back(d_vy0); dvyPyramid.push_back(d_vy1); dvyPyramid.push_back(d_vy2); dvyPyramid.push_back(d_vy3); std::vector<float *> grayRefPyramid; grayRefPyramid.push_back(d_refImg0); grayRefPyramid.push_back(d_refImg1); grayRefPyramid.push_back(d_refImg2); grayRefPyramid.push_back(d_refImg3); std::vector<float *> depthRefPyramid; depthRefPyramid.push_back(d_depthref0); depthRefPyramid.push_back(d_depthref1); depthRefPyramid.push_back(d_depthref2); depthRefPyramid.push_back(d_depthref3); std::vector<float *> grayCurPyramid; grayCurPyramid.push_back(d_curImg0); grayCurPyramid.push_back(d_curImg1); grayCurPyramid.push_back(d_curImg2); grayCurPyramid.push_back(d_curImg3); std::vector<float *> depthCurPyramid; depthCurPyramid.push_back(d_depthcur0); depthCurPyramid.push_back(d_depthcur1); depthCurPyramid.push_back(d_depthcur2); depthCurPyramid.push_back(d_depthcur3); std::vector<float *> residualPyramid; residualPyramid.push_back(d_resImg0); residualPyramid.push_back(d_resImg1); residualPyramid.push_back(d_resImg2); residualPyramid.push_back(d_resImg3); // initialize cuda context cudaDeviceSynchronize(); CUDA_CHECK; downSample(grayRefPyramid, depthRefPyramid, grayCurPyramid, depthCurPyramid, w, h); float *result = new float[(size_t)1]; float *A_interim = new float[(size_t)21]; float *b_interim = new float[(size_t)6]; Mat6f A = Mat6f::Zero(); Vec6f b = Vec6f::Zero(); for (int level = LVL; level>0 ; level--) { int width = w/pow(2,level-1); int height = h/pow(2,level-1); // initialize intrinsic matrix Eigen::Matrix3f kLevel = kPyramid[level-1]; // initialize cuda context cudaDeviceSynchronize(); CUDA_CHECK; // copy data to device // Current grayscale image float *d_currImg = grayCurPyramid[level - 1] ; // Reference grayscale image float *d_refimgIn = grayRefPyramid[level -1]; //Current depth image float *d_depthImgIn = depthCurPyramid[level-1]; //Reference depth image float *d_refdepthImgIn = depthRefPyramid[level-1]; //Residual Image float *d_resImg = residualPyramid[level-1]; float *d_rot, *d_t; float fx = kLevel(0,0); float fy = kLevel(1,1); float cx = kLevel(0,2); float cy = kLevel(1,2); size_t n_d_vx = (size_t)width*height; size_t n_d_vy = (size_t)width*height; int N = width*height; float *d_jacobif = jacobifPyramid[level-1]; float *d_vx = dvxPyramid[level-1]; float *d_vy = dvyPyramid[level-1]; float *JtJ_final = JtJPyramid[level-1]; float *Jtb_final = JtbPyramid[level-1]; cudaMalloc(&d_rot, 9*sizeof(float)); CUDA_CHECK; cudaMalloc(&d_t, 3*sizeof(float)); CUDA_CHECK; float errLast = std::numeric_limits<float>::max(); for(int i = 0; i < ITER ; i++) { float *rot_data = rot.data(); float *t_data = t.data(); cudaMemset(d_vy, 0, n_d_vy*sizeof(float)); CUDA_CHECK; cudaMemset(d_vx, 0, n_d_vx*sizeof(float)); CUDA_CHECK; cudaMemset(Jtb_final, 0, N*6*sizeof(float)); CUDA_CHECK; cudaMemset(JtJ_final, 0, N*21*sizeof(float)); CUDA_CHECK; cudaMemset(d_jacobif, 0, N*6*sizeof(float)); CUDA_CHECK; cudaMemcpy(d_rot,rot_data,9*sizeof(float),cudaMemcpyHostToDevice); CUDA_CHECK; cudaMemcpy(d_t,t_data,3*sizeof(float),cudaMemcpyHostToDevice); CUDA_CHECK; dim3 block = dim3(32, 8, 1); dim3 grid = dim3((width+block.x-1)/block.x, (height+block.y-1)/block.y, 1); //Texture Memory texRef.addressMode[0] = cudaAddressModeClamp; texRef.addressMode[1] = cudaAddressModeClamp; texRef.filterMode = cudaFilterModeLinear; texRef.normalized = false; cudaChannelFormatDesc desc = cudaCreateChannelDesc<float>(); cudaBindTexture2D(NULL, &texRef, d_currImg, &desc, width, height, width*sizeof(d_currImg[0])); texGradX.addressMode[0] = cudaAddressModeClamp; texGradX.addressMode[1] = cudaAddressModeClamp; texGradX.filterMode = cudaFilterModeLinear; texGradX.normalized = false; cudaChannelFormatDesc descX = cudaCreateChannelDesc<float>(); cudaBindTexture2D(NULL, &texGradX, d_vx, &descX, width, height, width*sizeof(d_vx[0])); texGradY.addressMode[0] = cudaAddressModeClamp; texGradY.addressMode[1] = cudaAddressModeClamp; texGradY.filterMode = cudaFilterModeLinear; texGradY.normalized = false; cudaChannelFormatDesc descY = cudaCreateChannelDesc<float>(); cudaBindTexture2D(NULL, &texGradY, d_vy, &descY, width, height, width*sizeof(d_vy[0])); calcErr <<<grid,block>>> (d_refimgIn,d_currImg,d_refdepthImgIn,d_resImg,d_rot,d_t,fx,fy,cx,cy,width,height); CUDA_CHECK; gradCompute <<<grid,block>>> (d_currImg,d_vx,d_vy,width,height); CUDA_CHECK; deriveNumeric <<<grid,block>>>(d_vx,d_vy,d_refdepthImgIn,d_resImg,d_jacobif,width,height,fx,fy,cx,cy,d_rot,d_t,JtJ_final,Jtb_final); CUDA_CHECK; cv::Mat residualGPU(height,width,grayRef.type()); cudaMemcpy((void *)residualGPU.data,d_resImg,N*sizeof(float),cudaMemcpyDeviceToHost); CUDA_CHECK; Eigen::VectorXf residual(N); int idx = 0; for(int i =0 ;i<width;i++) { for(int j =0 ;j<height;j++) { residual[idx] = residualGPU.at<float>(i,j); idx++; } } dim3 block1 = dim3(128, 1, 1); dim3 grid1 = dim3((N + block1.x -1)/block1.x,1,1); size_t smBytes = block1.x * block1.y * block1.z * sizeof(float); //Reduction for JtJ float* ptrJtJ = JtJ_final; for(int j = 0; j<21; j++) { block_sum <<<grid1,block1,smBytes>>> (ptrJtJ,ptrJtJ,N); for(int offset = block1.x / 2;offset > 0;offset >>= 1) block_sum <<<grid1,block1,smBytes>>> (ptrJtJ,ptrJtJ,N); cudaMemcpy(result,ptrJtJ,sizeof(float),cudaMemcpyDeviceToHost); CUDA_CHECK; A_interim[j]= result[0]; ptrJtJ = ptrJtJ + N; } int k = 0; for(int i = 0; i<6; i++) { for(int j = i; j<6; j++) { A(i,j) = A(j,i) =A_interim[k]; k++; } } float *ptrJtb = Jtb_final; for(int j = 0; j<6; j++) { block_sum <<<grid1,block1,smBytes>>> (ptrJtb,ptrJtb,N); for(int offset = block1.x / 2;offset > 0;offset >>= 1) block_sum <<<grid1,block1,smBytes>>> (ptrJtb,ptrJtb,N); cudaMemcpy(result,ptrJtb,sizeof(float),cudaMemcpyDeviceToHost); CUDA_CHECK; b_interim[j]= result[0]; ptrJtb = ptrJtb + N; } for(int i = 0; i<6; i++) b(i) = b_interim[i]; // solve using Cholesky LDLT decomposition Vec6f delta = -(A.ldlt().solve(b)); // update xi xi = Sophus::SE3f::log(Sophus::SE3f::exp(delta)*Sophus::SE3f::exp(xi)); cudaUnbindTexture(texRef); cudaUnbindTexture(texGradX); cudaUnbindTexture(texGradY); // print out final pose convertSE3ToTf(xi, rot, t); /*std::cout << "xi = " << xi.transpose() << std::endl; Eigen::VectorXd xiResult(6); xiResult << -0.0021f, 0.0057f, 0.0374f, -0.0292f, -0.0183f, -0.0009f; std::cout << "xi expected = " << xiResult.transpose() << std::endl;*/ float error = (residual.cwiseProduct(residual)).mean(); if((error/errLast) > 0.995f) break; errLast = error; } cudaFree(d_rot); CUDA_CHECK; cudaFree(d_t); CUDA_CHECK; width = width * 2; height = height * 2; tmr = ((double)cv::getTickCount() - tmr)/cv::getTickFrequency(); std::cout << "runtime: " << tmr * 1000.0 << " ms" << std::endl; runtimeAvg += tmr; } delete[] result; delete[] A_interim; delete[] b_interim; cudaFree(d_curImg0); CUDA_CHECK; cudaFree(d_curImg1); CUDA_CHECK; cudaFree(d_curImg2); CUDA_CHECK; cudaFree(d_curImg3); CUDA_CHECK; cudaFree(d_depthref0); CUDA_CHECK; cudaFree(d_depthref1); CUDA_CHECK; cudaFree(d_depthref2); CUDA_CHECK; cudaFree(d_depthref3); CUDA_CHECK; cudaFree(d_refImg0); CUDA_CHECK; cudaFree(d_refImg1); CUDA_CHECK; cudaFree(d_refImg2); CUDA_CHECK; cudaFree(d_refImg3); CUDA_CHECK; cudaFree(d_depthcur0); CUDA_CHECK; cudaFree(d_depthcur1); CUDA_CHECK; cudaFree(d_depthcur2); CUDA_CHECK; cudaFree(d_depthcur3); CUDA_CHECK; cudaFree(d_resImg0); CUDA_CHECK; cudaFree(d_resImg1); CUDA_CHECK; cudaFree(d_resImg2); CUDA_CHECK; cudaFree(d_resImg3); CUDA_CHECK; cudaFree(d_vx0); CUDA_CHECK; cudaFree(d_vx1); CUDA_CHECK; cudaFree(d_vx2); CUDA_CHECK; cudaFree(d_vx3); CUDA_CHECK; cudaFree(d_vy0); CUDA_CHECK; cudaFree(d_vy1); CUDA_CHECK; cudaFree(d_vy2); CUDA_CHECK; cudaFree(d_vy3); CUDA_CHECK; cudaFree(d_jacobif0); CUDA_CHECK; cudaFree(d_jacobif1); CUDA_CHECK; cudaFree(d_jacobif2); CUDA_CHECK; cudaFree(d_jacobif3); CUDA_CHECK; cudaFree(JtJ_final0); CUDA_CHECK; cudaFree(JtJ_final1); CUDA_CHECK; cudaFree(JtJ_final2); CUDA_CHECK; cudaFree(JtJ_final3); CUDA_CHECK; cudaFree(Jtb_final0); CUDA_CHECK; cudaFree(Jtb_final1); CUDA_CHECK; cudaFree(Jtb_final2); CUDA_CHECK; cudaFree(Jtb_final3); CUDA_CHECK; } Eigen::Matrix3f rot; Eigen::Vector3f t; convertSE3ToTf(xi, rot, t); std::cout << "pose (xi) between frames " << (i-1) << " and " << i << ": " << xi.transpose() << std::endl; // concatenate poses Eigen::Matrix4f relPose = Eigen::Matrix4f::Identity(); relPose.topLeftCorner(3,3) = rot; relPose.topRightCorner(3,1) = t; absPose = absPose * relPose.inverse(); poses.push_back(absPose); timestamps.push_back(timeDepth1); rot = absPose.topLeftCorner(3,3); t = absPose.topRightCorner(3,1); cv::Mat vertexMap1; depthToVertexMap(K.cast<double>(), depth1, vertexMap1); cv::Mat vertexMapTf1 = vertexMap1.clone(); transformVertexMap(rot.cast<double>(), t.cast<double>(), vertexMapTf1); cv::Mat color1UC; color1.convertTo(color1UC, CV_8UC3, 255.0f); #if 0 // save frames as point cloud std::stringstream ss; ss << dataFolder << "cloud_" << std::setw(4) << std::setfill('0') << i << ".ply"; savePlyFile(ss.str(), color1UC, vertexMapTf1); #endif #if 1 canceled = !updateViewer(vertexMap1, color1UC, absPose); #endif colorPrev = color1; depthPrev = depth1; grayPrev = gray1; ++framesProcessed; } stopViewer(); std::cout << "average runtime: " << (runtimeAvg / framesProcessed) * 1000.0 << " ms" << std::endl; // save poses savePoses(dataFolder + "traj.txt", poses, timestamps); #if 0 cv::waitKey(0); #endif // clean up cv::destroyAllWindows(); std::cout << "Direct Image Alignment finished." << std::endl; return 0; }
be531f99b41971da61228194b393287c1ec41f98.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "stdio.h" #include "stdlib.h" #include <math.h> #include <time.h> #include <sys/time.h> #include <string.h> #include "ass2_lib.h" #include <omp.h> #include "helper_cuda.h" void printMat(double * A, int N){ int i,j; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ printf("%7.0f ",A[i*N + j]); } printf("\n"); } } double getMatSum(double * A, int N){ int i,j; double sum = 0.0; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ sum += A[i*N + j]; } } return sum; } double fnorm_squared(double * u, double * uo, int N){ int i,j; double sum = 0; for(i = 1; i <N-1; i++){ for(j = 1; j<N-1; j++){ sum += (u[i*N + j]-uo[i*N + j])*(u[i*N + j]-uo[i*N + j]); } } return sum / (N*N); } void update_uo(double * u, double * uo, int N){ int i,j; for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i*N + j] = u[i*N + j]; } } } void initialize_matrices(double * u, double * uo, double * f, int N, double Nt){ // init loop variables int i, j; // define uo as zeros\ uo[x][0] = 0 i.e. outer wall for(i = 1; i < N; i++){ for(j = 1; j < N-1; j++){ uo[i*N + j] = 0; } } // Defining the boundaries to 20 { for(j = 0; j < N; j++) uo[j] = 20; for(i = 0; i < N; i++) uo[i*N] = 20; for(i = 0; i < N; i++) uo[i*N + N-1] = 20; } //setting u = uo; for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ u[i*N + j] = uo[i*N + j]; } } //printMat(uo,N); // defining the f matrix for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ f[i*N + j] = 0; } } for(i = 4*Nt; i < 5*Nt; i++){ for(j = 3*Nt; j < 4*Nt; j++){ f[i*N + j] = 200; } } } __global__ void ChangePointers(double ** p1, double ** p2) { double * temp = *p1; *p1 = *p2; *p2 = temp; } __global__ void PrintPointers(double * d_u, double * d_uo){ printf("&D_U: %i\n", d_u); printf("&D_UO: %i\n", d_uo); } __host__ void doSeq(double * u, double * uo, double * f, int N, double d, int kmax, double delta2, double dd){ double start = omp_get_wtime(); double *d_u, *d_uo, *d_f; int memsize = N*N*sizeof(double); hipMalloc(&d_u, memsize); hipMalloc(&d_uo, memsize); hipMalloc(&d_f, memsize); hipMemcpy(d_u, u, memsize, hipMemcpyHostToDevice); hipMemcpy(d_uo, uo, memsize, hipMemcpyHostToDevice); hipMemcpy(d_f, f, memsize, hipMemcpyHostToDevice); int k = 0; double checksum = 1000.0; while(k < kmax){ hipLaunchKernelGGL(( jacobi_seq_kernel), dim3(1), dim3(1), 0, 0, d_u, d_uo, d_f, N, delta2); double * temp = d_uo; d_uo = d_u; d_u = temp; k++; } hipMemcpy(uo, d_uo, memsize, hipMemcpyDeviceToHost); printf("%s, ", "CU-SEQ"); printf("%f, ", omp_get_wtime()-start); printf("%i, %.20f, %.0f, %i\n", N, dd, getMatSum(uo, N), k); hipFree(d_u); hipFree(d_uo); hipFree(d_f); } __host__ void doSingle(double * u, double * uo, double * f, int N, double d, int kmax, double delta2, double dd){ double *d_u, *d_uo, *d_f; int memsize = N*N*sizeof(double); hipMalloc(&d_u, memsize); hipMalloc(&d_uo, memsize); hipMalloc(&d_f, memsize); hipMemcpy(d_u, u, memsize, hipMemcpyHostToDevice); hipMemcpy(d_uo, uo, memsize, hipMemcpyHostToDevice); hipMemcpy(d_f, f, memsize, hipMemcpyHostToDevice); int k = 0; double checksum = 1000.0; hipSetDevice(6); int K = 16; int gridx = ceil((N-2)*1.0/(K)); int gridy = ceil((N-2)*1.0/(K)); double start = omp_get_wtime(); while(k < kmax){ hipLaunchKernelGGL(( jacobi_single_kernel), dim3(dim3(gridx,gridy)),dim3(dim3(K,K)), 0, 0, d_u, d_uo, d_f, N, delta2); double * temp = d_uo; d_uo = d_u; d_u = temp; k++; } double end = omp_get_wtime(); hipMemcpy(uo, d_uo, memsize, hipMemcpyDeviceToHost); //printf("MATRIX UO:\n"); //printMat(uo,N); //printf("\n"); printf("%s, ", "CU-SIN"); printf("%f, ", end-start); printf("%i, %.20f, %i, %.0f\n", N, dd, k, getMatSum(uo, N)); hipFree(d_u); hipFree(d_uo); hipFree(d_f); } __host__ void doMulti(double * u, double * uo, double * f, int N, double d, int kmax, double delta2, double dd){ double *d0_u, *d0_uo, *d0_f, *d1_u, *d1_uo, *d1_f; int memsize = N*N*sizeof(double); int Nsize = N*sizeof(double); hipSetDevice(6); hipDeviceEnablePeerAccess(7,0); hipMalloc((void**)&d0_u, memsize/2 + Nsize); hipMalloc((void**)&d0_uo, memsize/2 + Nsize); hipMalloc((void**)&d0_f, memsize/2 + Nsize); hipMemcpy(d0_u, u, memsize/2 + Nsize, hipMemcpyHostToDevice); hipMemcpy(d0_uo, uo, memsize/2 + Nsize, hipMemcpyHostToDevice); hipMemcpy(d0_f, f, memsize/2 + Nsize, hipMemcpyHostToDevice); hipSetDevice(7); hipDeviceEnablePeerAccess(6,0); hipMalloc((void**)&d1_u, memsize/2 + Nsize); hipMalloc((void**)&d1_uo, memsize/2 + Nsize); hipMalloc((void**)&d1_f, memsize/2 + Nsize); hipMemcpy(d1_u, &u[memsize/2/sizeof(double) -N], memsize/2 + Nsize, hipMemcpyHostToDevice); hipMemcpy(d1_uo, &uo[memsize/2/sizeof(double) -N], memsize/2 + Nsize, hipMemcpyHostToDevice); hipMemcpy(d1_f, &f[memsize/2/sizeof(double) -N], memsize/2 + Nsize, hipMemcpyHostToDevice); int k = 0; double checksum = 1000.0; int K = 16; int gridx = ceil((N-2)*1.0/(K)); int gridy = ceil((N-2)*1.0/(K)); gridy = ceil(gridy*1.0 / 2); double start = omp_get_wtime(); while(k < kmax){ hipSetDevice(6); hipLaunchKernelGGL(( jacobi_multi_kernel), dim3(dim3(gridx,gridy)),dim3(dim3(K,K)), 0, 0, d0_u, d0_uo, d0_f, N, delta2); hipSetDevice(7); hipLaunchKernelGGL(( jacobi_multi_kernel), dim3(dim3(gridx,gridy)),dim3(dim3(K,K)), 0, 0, d1_u, d1_uo, d1_f, N, delta2); hipDeviceSynchronize(); double * temp = d0_uo; d0_uo = d0_u; d0_u = temp; double * temp2 = d1_uo; d1_uo = d1_u; d1_u = temp2; hipMemcpy(d1_uo, d0_uo+(N-2)/2*N, Nsize, hipMemcpyDeviceToDevice); hipMemcpy(d0_uo+(N-2)/2*N+N , d1_uo+N, Nsize, hipMemcpyDeviceToDevice); k++; } double end = omp_get_wtime(); hipSetDevice(6); hipMemcpy(uo, d0_uo, memsize/2, hipMemcpyDeviceToHost); hipSetDevice(7); hipMemcpy(&uo[memsize/2/sizeof(double)], &d1_uo[N], memsize/2, hipMemcpyDeviceToHost); hipDeviceSynchronize(); //printf("MATRIX UO:\n"); //printMat(uo,N); //printf("\n"); printf("%s, ", "CU-MUL"); printf("%f, ", end-start); printf("%i, %.20f, %i, %.0f\n", N, dd, k, getMatSum(uo, N)); hipFree(d1_u); hipFree(d1_uo); hipFree(d1_f); hipFree(d0_u); hipFree(d0_uo); hipFree(d0_f); } int main(int argc, char **argv){ // ./poisson <method type> <NN> <d> <kmax> int NN; double dd; int kmax; sscanf(argv[2] , "%d", &NN); sscanf(argv[3] , "%lf", &dd); sscanf(argv[4] , "%d", &kmax); double d = dd*dd; int N = NN + 2; double delta = 2.0/N; double delta2 = delta*delta; double Nt = N/6.0; double * u, * uo, * f; u = (double*)malloc(N*N*sizeof(double)); uo = (double*)malloc(N*N*sizeof(double)); f = (double*)malloc(N*N*sizeof(double)); initialize_matrices(u,uo,f, N,Nt); //printf("MATRIX U:\n"); //printMat(u,N); //printf("\n"); //printf("MATRIX UO:\n"); //printMat(uo,N); //printf("\n"); if(strcmp(argv[1], "seq") == 0){ doSeq(u, uo, f, N, d, kmax, delta2, dd); } // naive single GPU // NN must be multiple of K if(strcmp(argv[1], "sin") == 0){ doSingle(u, uo, f, N, d, kmax, delta2, dd); } // naive multi GPU // NN must be even multiple of K if(strcmp(argv[1], "mul") == 0){ doMulti(u, uo, f, N, d, kmax, delta2, dd); } } // WEEK2 OPENMP STUFF /* //initialize_matrices(u, uo, f, N, Nt); int i, j; struct timeval tv1, tv2; double runtime; int nruns; if(strcmp(argv[1], "jacobi") == 0){ runtime = 0.0; nruns = 0; while(runtime <= 3.0){ k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); gettimeofday(&tv1, NULL); while(checksum > d && k < kmax){ jacobi_seq(u,uo,f,N,delta2); checksum = fnorm_squared(u,uo,N); for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } k++; // printf("%f \n", checksum); } gettimeofday(&tv2, NULL); runtime += (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec); nruns++; } printf("%s, ", "JAC"); printf("%f, ", (double) runtime / nruns); printf("%i, %.20f, %i, %i\n", N, dd, k, k*nruns); } if(strcmp(argv[1], "gauss") == 0){ runtime = 0.0; nruns = 0; while(runtime <= 3.0){ k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); gettimeofday(&tv1, NULL); while(checksum > d && k < kmax){ gauss_seidel(u,f,N,delta2); checksum = fnorm_squared(u,uo,N); for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } k++; } gettimeofday(&tv2, NULL); runtime += (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec); nruns++; } printf("%s, ", "G-S"); printf("%f, ", runtime); printf("%i, %.20f, %i, %i\n", N, dd, k, k*nruns); } if(strcmp(argv[1], "omp") == 0){ runtime = 0.0; k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); double omp_s = omp_get_wtime(); while(checksum > d && k < kmax){ #pragma omp parallel default(none) shared(u,uo,f,N,delta2) private(i,j) { jacobi_seq(u,uo,f,N,delta2); } // end parallel checksum = fnorm_squared(u,uo,N); for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } k++; } double omp_time = omp_get_wtime() - omp_s; int thread = omp_get_max_threads(); printf("%s, ", "OMP"); printf("%f, ", omp_time); printf("%i, %.20f, %i, %i\n", N, dd, k, thread); } if(strcmp(argv[1], "omp2") == 0){ runtime = 0.0; k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); double omp_s = omp_get_wtime(); #pragma omp parallel default(none) shared (u,uo,f,N,delta2, checksum, k, d, kmax) private(i,j) { while(checksum > d && k < kmax){ jacobi_seq(u,uo,f,N,delta2); // checksum = fnorm_squared(u,uo,N); #pragma omp for private(i,j) reduction(+:checksum) for(i = 1; i <N-1; i++){ for(j = 1; j<N-1; j++){ checksum += (u[i][j]-uo[i][j])*(u[i][j]-uo[i][j]); } } #pragma omp for private(i,j) for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } #pragma omp master { k++; checksum=checksum/(N*N); } #pragma omp barrier } // end while } // end parallel double omp_time = omp_get_wtime() - omp_s; int thread = omp_get_max_threads(); printf("%s, ", "OMP2"); printf("%f, ", omp_time); printf("%i, %.20f, %i, %i\n", N, dd, k, thread); } if(strcmp(argv[1], "omp3") == 0){ runtime = 0.0; k = 0; checksum = 1000; #pragma omp parallel default(none) shared(u, uo, f, N, Nt) { initialize_matrices(u, uo, f, N, Nt); } double omp_s = omp_get_wtime(); #pragma omp parallel default(none) shared (u,uo,f,N,delta2, checksum, k, d, kmax) private(i,j) { while(checksum > d && k < kmax){ jacobi_seq(u,uo,f,N,delta2); // checksum = fnorm_squared(u,uo,N); #pragma omp for private(i,j) reduction(+:checksum) for(i = 1; i <N-1; i++){ for(j = 1; j<N-1; j++){ checksum += (u[i][j]-uo[i][j])*(u[i][j]-uo[i][j]); } } #pragma omp for private(i,j) for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } #pragma omp master { k++; checksum=checksum/(N*N); } #pragma omp barrier } // end while } // end parallel double omp_time = omp_get_wtime() - omp_s; int thread = omp_get_max_threads(); printf("%s, ", "OMP3"); printf("%f, ", omp_time); printf("%i, %.20f, %i, %i\n", N, dd, k, thread); } // printMat(u,N); // Save the data /* The real code should be here. While loop that checks if change from uo to u is small enough to be accepted (solution has converged). Jacobi should be implemented as a sub-routine in a separate function */ //printf("k is: %i \n",k); // dfree_2d(u); // dfree_2d(uo); // dfree_2d(f); //}
be531f99b41971da61228194b393287c1ec41f98.cu
#include "stdio.h" #include "stdlib.h" #include <math.h> #include <time.h> #include <sys/time.h> #include <string.h> #include "ass2_lib.h" #include <omp.h> #include "helper_cuda.h" void printMat(double * A, int N){ int i,j; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ printf("%7.0f ",A[i*N + j]); } printf("\n"); } } double getMatSum(double * A, int N){ int i,j; double sum = 0.0; for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ sum += A[i*N + j]; } } return sum; } double fnorm_squared(double * u, double * uo, int N){ int i,j; double sum = 0; for(i = 1; i <N-1; i++){ for(j = 1; j<N-1; j++){ sum += (u[i*N + j]-uo[i*N + j])*(u[i*N + j]-uo[i*N + j]); } } return sum / (N*N); } void update_uo(double * u, double * uo, int N){ int i,j; for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i*N + j] = u[i*N + j]; } } } void initialize_matrices(double * u, double * uo, double * f, int N, double Nt){ // init loop variables int i, j; // define uo as zeros\ uo[x][0] = 0 i.e. outer wall for(i = 1; i < N; i++){ for(j = 1; j < N-1; j++){ uo[i*N + j] = 0; } } // Defining the boundaries to 20 { for(j = 0; j < N; j++) uo[j] = 20; for(i = 0; i < N; i++) uo[i*N] = 20; for(i = 0; i < N; i++) uo[i*N + N-1] = 20; } //setting u = uo; for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ u[i*N + j] = uo[i*N + j]; } } //printMat(uo,N); // defining the f matrix for(i = 0; i < N; i++){ for(j = 0; j < N; j++){ f[i*N + j] = 0; } } for(i = 4*Nt; i < 5*Nt; i++){ for(j = 3*Nt; j < 4*Nt; j++){ f[i*N + j] = 200; } } } __global__ void ChangePointers(double ** p1, double ** p2) { double * temp = *p1; *p1 = *p2; *p2 = temp; } __global__ void PrintPointers(double * d_u, double * d_uo){ printf("&D_U: %i\n", d_u); printf("&D_UO: %i\n", d_uo); } __host__ void doSeq(double * u, double * uo, double * f, int N, double d, int kmax, double delta2, double dd){ double start = omp_get_wtime(); double *d_u, *d_uo, *d_f; int memsize = N*N*sizeof(double); cudaMalloc(&d_u, memsize); cudaMalloc(&d_uo, memsize); cudaMalloc(&d_f, memsize); cudaMemcpy(d_u, u, memsize, cudaMemcpyHostToDevice); cudaMemcpy(d_uo, uo, memsize, cudaMemcpyHostToDevice); cudaMemcpy(d_f, f, memsize, cudaMemcpyHostToDevice); int k = 0; double checksum = 1000.0; while(k < kmax){ jacobi_seq_kernel<<<1, 1>>>(d_u, d_uo, d_f, N, delta2); double * temp = d_uo; d_uo = d_u; d_u = temp; k++; } cudaMemcpy(uo, d_uo, memsize, cudaMemcpyDeviceToHost); printf("%s, ", "CU-SEQ"); printf("%f, ", omp_get_wtime()-start); printf("%i, %.20f, %.0f, %i\n", N, dd, getMatSum(uo, N), k); cudaFree(d_u); cudaFree(d_uo); cudaFree(d_f); } __host__ void doSingle(double * u, double * uo, double * f, int N, double d, int kmax, double delta2, double dd){ double *d_u, *d_uo, *d_f; int memsize = N*N*sizeof(double); cudaMalloc(&d_u, memsize); cudaMalloc(&d_uo, memsize); cudaMalloc(&d_f, memsize); cudaMemcpy(d_u, u, memsize, cudaMemcpyHostToDevice); cudaMemcpy(d_uo, uo, memsize, cudaMemcpyHostToDevice); cudaMemcpy(d_f, f, memsize, cudaMemcpyHostToDevice); int k = 0; double checksum = 1000.0; cudaSetDevice(6); int K = 16; int gridx = ceil((N-2)*1.0/(K)); int gridy = ceil((N-2)*1.0/(K)); double start = omp_get_wtime(); while(k < kmax){ jacobi_single_kernel<<<dim3(gridx,gridy),dim3(K,K)>>>(d_u, d_uo, d_f, N, delta2); double * temp = d_uo; d_uo = d_u; d_u = temp; k++; } double end = omp_get_wtime(); cudaMemcpy(uo, d_uo, memsize, cudaMemcpyDeviceToHost); //printf("MATRIX UO:\n"); //printMat(uo,N); //printf("\n"); printf("%s, ", "CU-SIN"); printf("%f, ", end-start); printf("%i, %.20f, %i, %.0f\n", N, dd, k, getMatSum(uo, N)); cudaFree(d_u); cudaFree(d_uo); cudaFree(d_f); } __host__ void doMulti(double * u, double * uo, double * f, int N, double d, int kmax, double delta2, double dd){ double *d0_u, *d0_uo, *d0_f, *d1_u, *d1_uo, *d1_f; int memsize = N*N*sizeof(double); int Nsize = N*sizeof(double); cudaSetDevice(6); cudaDeviceEnablePeerAccess(7,0); cudaMalloc((void**)&d0_u, memsize/2 + Nsize); cudaMalloc((void**)&d0_uo, memsize/2 + Nsize); cudaMalloc((void**)&d0_f, memsize/2 + Nsize); cudaMemcpy(d0_u, u, memsize/2 + Nsize, cudaMemcpyHostToDevice); cudaMemcpy(d0_uo, uo, memsize/2 + Nsize, cudaMemcpyHostToDevice); cudaMemcpy(d0_f, f, memsize/2 + Nsize, cudaMemcpyHostToDevice); cudaSetDevice(7); cudaDeviceEnablePeerAccess(6,0); cudaMalloc((void**)&d1_u, memsize/2 + Nsize); cudaMalloc((void**)&d1_uo, memsize/2 + Nsize); cudaMalloc((void**)&d1_f, memsize/2 + Nsize); cudaMemcpy(d1_u, &u[memsize/2/sizeof(double) -N], memsize/2 + Nsize, cudaMemcpyHostToDevice); cudaMemcpy(d1_uo, &uo[memsize/2/sizeof(double) -N], memsize/2 + Nsize, cudaMemcpyHostToDevice); cudaMemcpy(d1_f, &f[memsize/2/sizeof(double) -N], memsize/2 + Nsize, cudaMemcpyHostToDevice); int k = 0; double checksum = 1000.0; int K = 16; int gridx = ceil((N-2)*1.0/(K)); int gridy = ceil((N-2)*1.0/(K)); gridy = ceil(gridy*1.0 / 2); double start = omp_get_wtime(); while(k < kmax){ cudaSetDevice(6); jacobi_multi_kernel<<<dim3(gridx,gridy),dim3(K,K)>>>(d0_u, d0_uo, d0_f, N, delta2); cudaSetDevice(7); jacobi_multi_kernel<<<dim3(gridx,gridy),dim3(K,K)>>>(d1_u, d1_uo, d1_f, N, delta2); cudaDeviceSynchronize(); double * temp = d0_uo; d0_uo = d0_u; d0_u = temp; double * temp2 = d1_uo; d1_uo = d1_u; d1_u = temp2; cudaMemcpy(d1_uo, d0_uo+(N-2)/2*N, Nsize, cudaMemcpyDeviceToDevice); cudaMemcpy(d0_uo+(N-2)/2*N+N , d1_uo+N, Nsize, cudaMemcpyDeviceToDevice); k++; } double end = omp_get_wtime(); cudaSetDevice(6); cudaMemcpy(uo, d0_uo, memsize/2, cudaMemcpyDeviceToHost); cudaSetDevice(7); cudaMemcpy(&uo[memsize/2/sizeof(double)], &d1_uo[N], memsize/2, cudaMemcpyDeviceToHost); cudaDeviceSynchronize(); //printf("MATRIX UO:\n"); //printMat(uo,N); //printf("\n"); printf("%s, ", "CU-MUL"); printf("%f, ", end-start); printf("%i, %.20f, %i, %.0f\n", N, dd, k, getMatSum(uo, N)); cudaFree(d1_u); cudaFree(d1_uo); cudaFree(d1_f); cudaFree(d0_u); cudaFree(d0_uo); cudaFree(d0_f); } int main(int argc, char **argv){ // ./poisson <method type> <NN> <d> <kmax> int NN; double dd; int kmax; sscanf(argv[2] , "%d", &NN); sscanf(argv[3] , "%lf", &dd); sscanf(argv[4] , "%d", &kmax); double d = dd*dd; int N = NN + 2; double delta = 2.0/N; double delta2 = delta*delta; double Nt = N/6.0; double * u, * uo, * f; u = (double*)malloc(N*N*sizeof(double)); uo = (double*)malloc(N*N*sizeof(double)); f = (double*)malloc(N*N*sizeof(double)); initialize_matrices(u,uo,f, N,Nt); //printf("MATRIX U:\n"); //printMat(u,N); //printf("\n"); //printf("MATRIX UO:\n"); //printMat(uo,N); //printf("\n"); if(strcmp(argv[1], "seq") == 0){ doSeq(u, uo, f, N, d, kmax, delta2, dd); } // naive single GPU // NN must be multiple of K if(strcmp(argv[1], "sin") == 0){ doSingle(u, uo, f, N, d, kmax, delta2, dd); } // naive multi GPU // NN must be even multiple of K if(strcmp(argv[1], "mul") == 0){ doMulti(u, uo, f, N, d, kmax, delta2, dd); } } // WEEK2 OPENMP STUFF /* //initialize_matrices(u, uo, f, N, Nt); int i, j; struct timeval tv1, tv2; double runtime; int nruns; if(strcmp(argv[1], "jacobi") == 0){ runtime = 0.0; nruns = 0; while(runtime <= 3.0){ k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); gettimeofday(&tv1, NULL); while(checksum > d && k < kmax){ jacobi_seq(u,uo,f,N,delta2); checksum = fnorm_squared(u,uo,N); for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } k++; // printf("%f \n", checksum); } gettimeofday(&tv2, NULL); runtime += (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec); nruns++; } printf("%s, ", "JAC"); printf("%f, ", (double) runtime / nruns); printf("%i, %.20f, %i, %i\n", N, dd, k, k*nruns); } if(strcmp(argv[1], "gauss") == 0){ runtime = 0.0; nruns = 0; while(runtime <= 3.0){ k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); gettimeofday(&tv1, NULL); while(checksum > d && k < kmax){ gauss_seidel(u,f,N,delta2); checksum = fnorm_squared(u,uo,N); for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } k++; } gettimeofday(&tv2, NULL); runtime += (double) (tv2.tv_usec - tv1.tv_usec) / 1000000 + (double) (tv2.tv_sec - tv1.tv_sec); nruns++; } printf("%s, ", "G-S"); printf("%f, ", runtime); printf("%i, %.20f, %i, %i\n", N, dd, k, k*nruns); } if(strcmp(argv[1], "omp") == 0){ runtime = 0.0; k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); double omp_s = omp_get_wtime(); while(checksum > d && k < kmax){ #pragma omp parallel default(none) shared(u,uo,f,N,delta2) private(i,j) { jacobi_seq(u,uo,f,N,delta2); } // end parallel checksum = fnorm_squared(u,uo,N); for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } k++; } double omp_time = omp_get_wtime() - omp_s; int thread = omp_get_max_threads(); printf("%s, ", "OMP"); printf("%f, ", omp_time); printf("%i, %.20f, %i, %i\n", N, dd, k, thread); } if(strcmp(argv[1], "omp2") == 0){ runtime = 0.0; k = 0; checksum = 1000; initialize_matrices(u, uo, f, N, Nt); double omp_s = omp_get_wtime(); #pragma omp parallel default(none) shared (u,uo,f,N,delta2, checksum, k, d, kmax) private(i,j) { while(checksum > d && k < kmax){ jacobi_seq(u,uo,f,N,delta2); // checksum = fnorm_squared(u,uo,N); #pragma omp for private(i,j) reduction(+:checksum) for(i = 1; i <N-1; i++){ for(j = 1; j<N-1; j++){ checksum += (u[i][j]-uo[i][j])*(u[i][j]-uo[i][j]); } } #pragma omp for private(i,j) for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } #pragma omp master { k++; checksum=checksum/(N*N); } #pragma omp barrier } // end while } // end parallel double omp_time = omp_get_wtime() - omp_s; int thread = omp_get_max_threads(); printf("%s, ", "OMP2"); printf("%f, ", omp_time); printf("%i, %.20f, %i, %i\n", N, dd, k, thread); } if(strcmp(argv[1], "omp3") == 0){ runtime = 0.0; k = 0; checksum = 1000; #pragma omp parallel default(none) shared(u, uo, f, N, Nt) { initialize_matrices(u, uo, f, N, Nt); } double omp_s = omp_get_wtime(); #pragma omp parallel default(none) shared (u,uo,f,N,delta2, checksum, k, d, kmax) private(i,j) { while(checksum > d && k < kmax){ jacobi_seq(u,uo,f,N,delta2); // checksum = fnorm_squared(u,uo,N); #pragma omp for private(i,j) reduction(+:checksum) for(i = 1; i <N-1; i++){ for(j = 1; j<N-1; j++){ checksum += (u[i][j]-uo[i][j])*(u[i][j]-uo[i][j]); } } #pragma omp for private(i,j) for(i = 0; i<N; i++){ for(j = 0; j<N; j++){ uo[i][j] = u[i][j]; } } #pragma omp master { k++; checksum=checksum/(N*N); } #pragma omp barrier } // end while } // end parallel double omp_time = omp_get_wtime() - omp_s; int thread = omp_get_max_threads(); printf("%s, ", "OMP3"); printf("%f, ", omp_time); printf("%i, %.20f, %i, %i\n", N, dd, k, thread); } // printMat(u,N); // Save the data /* The real code should be here. While loop that checks if change from uo to u is small enough to be accepted (solution has converged). Jacobi should be implemented as a sub-routine in a separate function */ //printf("k is: %i \n",k); // dfree_2d(u); // dfree_2d(uo); // dfree_2d(f); //}
7b7d6f64444d0f3a6ab987ba7291f66d166dcc19.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include<iostream> #include<fstream> #include<cmath> #include<string> #include<thrust/host_vector.h> #include<thrust/device_vector.h> #include<cuda_runtime.h> #include "../param.cpp" #include "../input.cpp" #include "vel_verlet.cpp" #include "../output.cpp" using namespace std; void cudasafe(int error, string message, string file, int line) { if (error != hipSuccess) { cout<<stderr<< " CUDA Error: "<<message<<" : "<<error<<". In "<<file<<" line "<<line<<endl; exit(-1); } } int main(){ //reading input parameters string paramFileName ="periodicity.par",input_path = "../Question/input/"; string part_input_file, part_out_name_base, vtk_out_name_base; double timeStep, timeEnd, epsilon, sigma; unsigned part_out_freq, vtk_out_freq, cl_wg_1dsize; unsigned x_n, y_n, z_n, cl_wg_3dsize_x, cl_wg_3dsize_y, cl_wg_3dsize_z; double x_min, x_max, y_min, y_max, z_min, z_max, r_cut, r_skin; // reading .par file { // in param.cpp file readParam( input_path + paramFileName, part_input_file, part_out_name_base, vtk_out_name_base, timeStep, timeEnd, epsilon, sigma, part_out_freq, vtk_out_freq, cl_wg_1dsize, cl_wg_3dsize_x, cl_wg_3dsize_y, cl_wg_3dsize_z, x_min, x_max, y_min, y_max, z_min, z_max, x_n, y_n, z_n, r_cut, r_skin ); // outParam( // part_input_file, part_out_name_base, // vtk_out_name_base, timeStep, timeEnd, epsilon, sigma, // part_out_freq, vtk_out_freq, cl_wg_1dsize, // cl_wg_3dsize_x, cl_wg_3dsize_y, cl_wg_3dsize_z, // x_min, x_max, y_min, y_max, z_min, z_max, // x_n, y_n, z_n, r_cut, r_skin // ); } double del_x=(x_max-x_min)/x_n, del_y=(y_max-y_min)/y_n, del_z=(z_max-z_min)/z_n; unsigned cell_n = x_n*y_n*z_n; // declearing host vector memory unsigned N, dim, frames = (timeEnd/timeStep); // frames -> # of timeframes // N -> # of particles // dim -> dimension of vector thrust::host_vector<double> sliced; readInput(input_path + part_input_file,sliced,N,dim); // in input.cpp host_vector<double> x(N*dim,0), v(N*dim,0), m(N,0),f(N*dim,0) ; // extracting m,x,v data from sliced { extract( raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), raw_pointer_cast(&m[0]), raw_pointer_cast(sliced.data()), N, dim ); // outInput( // raw_pointer_cast(x.data()), // raw_pointer_cast(v.data()), // raw_pointer_cast(m.data()), // N,dim // ); // in input.cpp } // CUDA Programming device_vector<double> d_x(x),d_v(v),d_f(N*dim,0),d_f_old(N*dim,0),zeros(N*dim,0),d_m(m); hipDeviceProp_t deviceProp; cudasafe( hipGetDeviceProperties(&deviceProp,0), "Get device Properties", __FILE__, __LINE__ ); // cout<<"Max threads per block: "<<deviceProp.maxThreadsPerBlock<<endl; int blockSize = deviceProp.maxThreadsPerBlock, gridSize = (N/deviceProp.maxThreadsPerBlock)+1; // cout<<"Block Size: "<<blockSize<<"\nGrid size: "<<gridSize<<endl // <<"Frames: "<<frames<<endl; // Initial force calculation hipLaunchKernelGGL(( calF), dim3(gridSize), dim3(blockSize), 0, 0, raw_pointer_cast(&d_x[0]), raw_pointer_cast(&d_f[0]), N, dim, epsilon, sigma, r_cut ); cudasafe( hipDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); writeOut( part_out_name_base, 0, raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp writeVTK( vtk_out_name_base, 0, raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp for(int i=1; i<=frames; i++){ hipLaunchKernelGGL(( calX), dim3(gridSize), dim3(blockSize), 0, 0, raw_pointer_cast(&d_x[0]), raw_pointer_cast(&d_v[0]), raw_pointer_cast(&d_f[0]), raw_pointer_cast(&d_m[0]), timeStep, N, dim, x_min, x_max, y_min, y_max, z_min, z_max ); cudasafe( hipDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); d_f_old = d_f; thrust::copy(zeros.begin(), zeros.end(), d_f.begin()); hipLaunchKernelGGL(( calF), dim3(gridSize), dim3(blockSize), 0, 0, raw_pointer_cast(&d_x[0]), raw_pointer_cast(&d_f[0]), N, dim, epsilon, sigma, r_cut ); cudasafe( hipDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); hipLaunchKernelGGL(( calV), dim3(gridSize),dim3(blockSize), 0, 0, raw_pointer_cast(&d_v[0]), raw_pointer_cast(&d_f[0]), raw_pointer_cast(&d_f_old[0]), raw_pointer_cast(&d_m[0]), timeStep, N, dim ); cudasafe( hipDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); if(i%part_out_freq == 0){ m = d_m; x = d_x; v = d_v; writeOut( part_out_name_base, (i/part_out_freq), raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp } if(i%vtk_out_freq == 0){ m = d_m; x = d_x; v = d_v; writeVTK( part_out_name_base, (i/vtk_out_freq), raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp } } cout<<"\n\nAll done!\n\n"; return 0; }
7b7d6f64444d0f3a6ab987ba7291f66d166dcc19.cu
#include<iostream> #include<fstream> #include<cmath> #include<string> #include<thrust/host_vector.h> #include<thrust/device_vector.h> #include<cuda_runtime.h> #include "../param.cpp" #include "../input.cpp" #include "vel_verlet.cpp" #include "../output.cpp" using namespace std; void cudasafe(int error, string message, string file, int line) { if (error != cudaSuccess) { cout<<stderr<< " CUDA Error: "<<message<<" : "<<error<<". In "<<file<<" line "<<line<<endl; exit(-1); } } int main(){ //reading input parameters string paramFileName ="periodicity.par",input_path = "../Question/input/"; string part_input_file, part_out_name_base, vtk_out_name_base; double timeStep, timeEnd, epsilon, sigma; unsigned part_out_freq, vtk_out_freq, cl_wg_1dsize; unsigned x_n, y_n, z_n, cl_wg_3dsize_x, cl_wg_3dsize_y, cl_wg_3dsize_z; double x_min, x_max, y_min, y_max, z_min, z_max, r_cut, r_skin; // reading .par file { // in param.cpp file readParam( input_path + paramFileName, part_input_file, part_out_name_base, vtk_out_name_base, timeStep, timeEnd, epsilon, sigma, part_out_freq, vtk_out_freq, cl_wg_1dsize, cl_wg_3dsize_x, cl_wg_3dsize_y, cl_wg_3dsize_z, x_min, x_max, y_min, y_max, z_min, z_max, x_n, y_n, z_n, r_cut, r_skin ); // outParam( // part_input_file, part_out_name_base, // vtk_out_name_base, timeStep, timeEnd, epsilon, sigma, // part_out_freq, vtk_out_freq, cl_wg_1dsize, // cl_wg_3dsize_x, cl_wg_3dsize_y, cl_wg_3dsize_z, // x_min, x_max, y_min, y_max, z_min, z_max, // x_n, y_n, z_n, r_cut, r_skin // ); } double del_x=(x_max-x_min)/x_n, del_y=(y_max-y_min)/y_n, del_z=(z_max-z_min)/z_n; unsigned cell_n = x_n*y_n*z_n; // declearing host vector memory unsigned N, dim, frames = (timeEnd/timeStep); // frames -> # of timeframes // N -> # of particles // dim -> dimension of vector thrust::host_vector<double> sliced; readInput(input_path + part_input_file,sliced,N,dim); // in input.cpp host_vector<double> x(N*dim,0), v(N*dim,0), m(N,0),f(N*dim,0) ; // extracting m,x,v data from sliced { extract( raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), raw_pointer_cast(&m[0]), raw_pointer_cast(sliced.data()), N, dim ); // outInput( // raw_pointer_cast(x.data()), // raw_pointer_cast(v.data()), // raw_pointer_cast(m.data()), // N,dim // ); // in input.cpp } // CUDA Programming device_vector<double> d_x(x),d_v(v),d_f(N*dim,0),d_f_old(N*dim,0),zeros(N*dim,0),d_m(m); cudaDeviceProp deviceProp; cudasafe( cudaGetDeviceProperties(&deviceProp,0), "Get device Properties", __FILE__, __LINE__ ); // cout<<"Max threads per block: "<<deviceProp.maxThreadsPerBlock<<endl; int blockSize = deviceProp.maxThreadsPerBlock, gridSize = (N/deviceProp.maxThreadsPerBlock)+1; // cout<<"Block Size: "<<blockSize<<"\nGrid size: "<<gridSize<<endl // <<"Frames: "<<frames<<endl; // Initial force calculation calF<<<gridSize, blockSize>>>( raw_pointer_cast(&d_x[0]), raw_pointer_cast(&d_f[0]), N, dim, epsilon, sigma, r_cut ); cudasafe( cudaDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); writeOut( part_out_name_base, 0, raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp writeVTK( vtk_out_name_base, 0, raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp for(int i=1; i<=frames; i++){ calX<<<gridSize, blockSize>>>( raw_pointer_cast(&d_x[0]), raw_pointer_cast(&d_v[0]), raw_pointer_cast(&d_f[0]), raw_pointer_cast(&d_m[0]), timeStep, N, dim, x_min, x_max, y_min, y_max, z_min, z_max ); cudasafe( cudaDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); d_f_old = d_f; thrust::copy(zeros.begin(), zeros.end(), d_f.begin()); calF<<<gridSize, blockSize>>>( raw_pointer_cast(&d_x[0]), raw_pointer_cast(&d_f[0]), N, dim, epsilon, sigma, r_cut ); cudasafe( cudaDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); calV<<<gridSize,blockSize>>>( raw_pointer_cast(&d_v[0]), raw_pointer_cast(&d_f[0]), raw_pointer_cast(&d_f_old[0]), raw_pointer_cast(&d_m[0]), timeStep, N, dim ); cudasafe( cudaDeviceSynchronize(), "sync threads", __FILE__, __LINE__ ); if(i%part_out_freq == 0){ m = d_m; x = d_x; v = d_v; writeOut( part_out_name_base, (i/part_out_freq), raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp } if(i%vtk_out_freq == 0){ m = d_m; x = d_x; v = d_v; writeVTK( part_out_name_base, (i/vtk_out_freq), raw_pointer_cast(&m[0]), raw_pointer_cast(&x[0]), raw_pointer_cast(&v[0]), N, dim ); // in output.cpp } } cout<<"\n\nAll done!\n\n"; return 0; }
f88c66511565dabbc2561c257f688a8f13810737.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void cudaSScaleAbs_kernel(unsigned int size, float* input, const float scale, const float beta, float* result) { const unsigned int index = blockIdx.x * blockDim.x + threadIdx.x; const unsigned int stride = blockDim.x * gridDim.x; if (beta != 0.0f) { for (unsigned int i = index; i < size; i += stride) result[i] = fabs(input[i]) * scale + beta * result[i]; } else { for (unsigned int i = index; i < size; i += stride) result[i] = fabs(input[i]) * scale; } }
f88c66511565dabbc2561c257f688a8f13810737.cu
#include "includes.h" __global__ void cudaSScaleAbs_kernel(unsigned int size, float* input, const float scale, const float beta, float* result) { const unsigned int index = blockIdx.x * blockDim.x + threadIdx.x; const unsigned int stride = blockDim.x * gridDim.x; if (beta != 0.0f) { for (unsigned int i = index; i < size; i += stride) result[i] = fabs(input[i]) * scale + beta * result[i]; } else { for (unsigned int i = index; i < size; i += stride) result[i] = fabs(input[i]) * scale; } }
eb034bcef4a3452501561c3b0ecc3b6142918e76.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <iostream> #include <math.h> // CUDA kernel to add 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; float *x, *y; // Allocate Unified Memory -- accessible from CPU or 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; } // Launch kernel on 1M elements on the GPU int blockSize = 256; int numBlocks = (N + blockSize - 1) / blockSize; hipLaunchKernelGGL(( add), dim3(numBlocks), dim3(blockSize), 0, 0, N, x, y); // Wait for GPU to finish before accessing on host 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); hipFree(y); return 0; }
eb034bcef4a3452501561c3b0ecc3b6142918e76.cu
#include <iostream> #include <math.h> // CUDA kernel to add 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; float *x, *y; // Allocate Unified Memory -- accessible from CPU or GPU cudaMallocManaged(&x, N*sizeof(float)); cudaMallocManaged(&y, N*sizeof(float)); // initialize x and y arrays on the host for (int i = 0; i < N; i++) { x[i] = 1.0f; y[i] = 2.0f; } // Launch kernel on 1M elements on the GPU int blockSize = 256; int numBlocks = (N + blockSize - 1) / blockSize; add<<<numBlocks, blockSize>>>(N, x, y); // Wait for GPU to finish before accessing on host 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); cudaFree(y); return 0; }
7c30b9af9f18036c9d1c654fadcbb92a553365a6.hip
// !!! This is a file automatically generated by hipify!!! // ==================================================================================================== // liba for cuda #include <hip/hip_runtime.h> #include <hip/device_functions.h> #include "hip/hip_runtime.h" #include "device_launch_parameters.h" #include <hipfft.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/transform.h> #include <thrust/functional.h> // libs common #include <iostream> #include <time.h> #include <stdio.h> #include <vector> #include <stdio.h> #include <stdarg.h> #include "fstream" #include "iostream" #include <complex> #include <cmath> #include <cstdlib> // libs for opencv #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/core/cuda.hpp" // namespace using namespace std; using namespace cv; // constants #define PI 3.14159265 #define SIZE 2 #define TILE_DIM 16 #define WIDTHPERBLOCK 32 #define BLOCK_ROWS 8 #define MATRIXWIDTH 128 #define MATRIXAREA MATRIXWIDTH*MATRIXWIDTH #define IMAGEWIDTH round(MATRIXWIDTH/sqrt(2)) // shred memory __shared__ float As[WIDTHPERBLOCK][WIDTHPERBLOCK]; __shared__ float Bs[WIDTHPERBLOCK][WIDTHPERBLOCK]; extern __shared__ float a[]; extern __shared__ float b[]; // ==================================================================================================== // Thrust vector<float> ConvertMat2Vector(Mat & im_in); vector<float> ConcatRow2Vector(Mat & im_in, int num_row); void MatAddThrust(std::vector<float> & v_out, std::vector<float> v_in1, std::vector<float> v_in2, unsigned int v_size); // DFT and Forward Radon Transform void ShiftDftToCenter(Mat & im_in); Mat CreateDisplaySpectrum(Mat & complexImg, bool rearrange); void CreateRampFilter(Mat & ramp_filter, double a); void CreateHannFilter(Mat & hann_filter, double a); void ApplyFilter(Mat & im_in, string filter_method, Mat & im_out); void ForwardRadonTransform(Mat & im_in, Mat & im_out); void PerformCuFFT(); // Add without shared memory __global__ void MatAddWithoutSharedMemory(float A[], float B[], float C[], int m, int n); // Add with shared memory __global__ void MatAddSharedMemory(float A[], float B[], float C[], int m, int n); // Methods void InverseRadonTransformOpenCV(Mat & im_in, Mat & im_out); void InverseRadonTransformArray(Mat & im_in, Mat & im_out); void InverseRadonTransformCuda(Mat & im_in, Mat & im_out); void InverseRadonTransformCudaSharedMemory(Mat & im_in, Mat & im_out); void InverseRadonTransformCudaThrust(Mat & im_in, Mat & im_out); void PerformRadonAndInverseRadon(string method); // Addition, Cuda while multiplying 2 complex matrices void ApplyFilterCuda(Mat & im_in, string filter_method, Mat & im_out); __global__ void MatMulPixelwiseWithoutSharedMemory(float A_r[], float A_c[], float B_r[], float B_c[], float C_r[], float C_c[], int m, int n); void MultiplySpectrums(Mat & planes_r, Mat & planes_c, Mat & planes_filter_r, Mat & planes_filter_c, Mat & img_complex); // ==================================================================================================== int main() { string method; method = "cudathrust"; PerformRadonAndInverseRadon(method); method = "cudanoshare"; PerformRadonAndInverseRadon(method); method = "cudashare"; PerformRadonAndInverseRadon(method); method = "array"; PerformRadonAndInverseRadon(method); method = "opencv"; PerformRadonAndInverseRadon(method); waitKey(0); return 0; } // ==================================================================================================== //----------------------------------------------------------------------------------------------------- /* Function: MatAddThrust Add 2 vectors using Thrust library Parameters: v_out - result vector v_in1 - vector 1 v_in2 - vector 2 v_size - vector size */ //----------------------------------------------------------------------------------------------------- void MatAddThrust(std::vector<float> & v_out, std::vector<float> v_in1, std::vector<float> v_in2, unsigned int v_size) { // Init vector in thrust thrust::device_vector<float> X(v_in1.begin(), v_in1.end()); thrust::device_vector<float> Y(v_in2.begin(), v_in2.end()); thrust::device_vector<float> Z(v_size); // Make adition thrust::transform(X.begin(), X.end(), Y.begin(), Z.begin(), thrust::plus<float>()); // Copy data back thrust::copy(Z.begin(), Z.end(), v_out.begin()); } //----------------------------------------------------------------------------------------------------- /* Function: MatAddWithoutSharedMemory Add 2 matrices without using shared memory Parameters: A - Matrix input 1 B - Matrix input 2 C - Matrix output m - Matrix row n - Matrix column */ //----------------------------------------------------------------------------------------------------- __global__ void MatAddWithoutSharedMemory(float A[], float B[], float C[], int m, int n) { /* blockDim.x = threads_per_block */ /* First block gets first threads_per_block components. */ /* Second block gets next threads_per_block components, etc. */ int idx = blockDim.x * blockIdx.x + threadIdx.x; /* The test shouldn't be necessary */ if (blockIdx.x < m && threadIdx.x < n) C[idx] = A[idx] + B[idx]; } //----------------------------------------------------------------------------------------------------- /* Function: MatAddSharedMemory Add 2 matrices using shared memory Parameters: A - Matrix input 1 B - Matrix input 2 C - Matrix output m - Matrix row n - Matrix column */ //----------------------------------------------------------------------------------------------------- __global__ void MatAddSharedMemory(float A[], float B[], float C[], int m, int n) { /* blockDim.x = threads_per_block */ /* First block gets first threads_per_block components. */ /* Second block gets next threads_per_block components, etc. */ int idx = blockDim.x * blockIdx.x + threadIdx.x; // Copy data to shared memory a[idx] = A[idx]; __syncthreads(); b[idx] = B[idx]; __syncthreads(); /* The test shouldn't be necessary */ if (blockIdx.x < m && threadIdx.x < n) { C[idx] = a[idx] + b[idx]; __syncthreads(); } } //----------------------------------------------------------------------------------------------------- /* Function: ShiftDftToCenter Shift DFT to the center Parameters: im_in - input image */ //----------------------------------------------------------------------------------------------------- void ShiftDftToCenter(Mat & im_in) { // init vars Mat tmp, q0, q1, q2, q3; // first crop the image, if it has an odd number of rows or columns im_in = im_in(Rect(0, 0, im_in.cols & -2, im_in.rows & -2)); // get size of image int cx = im_in.cols / 2; int cy = im_in.rows / 2; // rearrange the quadrants of Fourier image // so that the origin is at the image center q0 = im_in(Rect(0, 0, cx, cy)); q1 = im_in(Rect(cx, 0, cx, cy)); q2 = im_in(Rect(0, cy, cx, cy)); q3 = im_in(Rect(cx, cy, cx, cy)); // copy back q0.copyTo(tmp); q3.copyTo(q0); tmp.copyTo(q3); // shift q1.copyTo(tmp); q2.copyTo(q1); tmp.copyTo(q2); } //----------------------------------------------------------------------------------------------------- /* Function: CreateDisplaySpectrum Create image to display the spectrum Parameters: complexImg - input dft (2 channel floating point, Real + Imaginary fourier image) rearrange - perform rearrangement of DFT quadrants if true Returns: pointer to output spectrum magnitude image scaled for user viewing */ //----------------------------------------------------------------------------------------------------- Mat CreateDisplaySpectrum(Mat & complexImg, bool rearrange) { // init vars Mat planes[2]; // split plane split(complexImg, planes); magnitude(planes[0], planes[1], planes[0]); // for magnitude Mat mag = (planes[0]).clone(); mag += Scalar::all(1); log(mag, mag); // shift to center if (rearrange) { ShiftDftToCenter(mag); } // normalize image cv::normalize(mag, mag, 0, 1, CV_MINMAX); // get result return mag; } //----------------------------------------------------------------------------------------------------- /* Function: CreateRampFilter Create Ramp Filter Parameters: ramp_filter - ramp filter a - threshold */ //----------------------------------------------------------------------------------------------------- void CreateRampFilter(Mat & ramp_filter, double a) { // init image blocks Mat tmp = Mat(ramp_filter.rows, ramp_filter.cols, CV_32F); // get row and col of image int N = ramp_filter.cols; int M = ramp_filter.rows; // init vars double step; step = 2 * a / (N - 1); // make filter for (int i = 0; i < ramp_filter.rows; i++) { for (int j = 0; j < ramp_filter.cols; j++) { tmp.at<float>(i, j) = abs(-a + j*step); } } // patch real part with 0 Mat abc = Mat::zeros(tmp.size(), CV_32F); // merge real and complex parts Mat toMerge[] = { tmp, abc }; merge(toMerge, 2, ramp_filter); } //----------------------------------------------------------------------------------------------------- /* Function: CreateHannFilter Create Hann Filter Parameters: hann_filter - hann filter a - threshold */ //----------------------------------------------------------------------------------------------------- void CreateHannFilter(Mat & hann_filter, double a) { // init image blocks Mat tmp = Mat(hann_filter.rows, hann_filter.cols, CV_32F); // get row and col of image int N = hann_filter.cols; // length int M = hann_filter.rows; // 180% radon // init vars double step, ramp, hann; step = 2 * a / (N - 1); // make filter for (int i = 0; i < hann_filter.rows; i++) { for (int j = 0; j < hann_filter.cols; j++) { ramp = abs(-a + j*step); hann = sin(j*PI / (N - 1)); hann = pow(hann, 2.0); tmp.at<float>(i, j) = ramp*hann; } } // patch real part with 0 Mat abc = Mat::zeros(tmp.size(), CV_32F); // merge real and complex parts Mat toMerge[] = { tmp, abc }; merge(toMerge, 2, hann_filter); } //----------------------------------------------------------------------------------------------------- /* Function: ApplyFilter Apply filter to sinogram Parameters: im_in - input image filter_method - filter method im_out - output image */ //----------------------------------------------------------------------------------------------------- void ApplyFilter(Mat & im_in, string filter_method, Mat & im_out) { // Init images objects Mat img_gray, img_output, img_output_display; Mat img_padded; Mat img_complex, filter; Mat planes[2], img_magnitude; // Fourier image size int N, M; // String constant for image title const string originalName = "Input Image (grayscale)"; // window name const string spectrumMagName = "Magnitude Image (log transformed)"; // window name const string lowPassName = "Ramp Filtered (grayscale)"; // window name const string filterName = "Filter Image"; // window nam // setup the DFT image sizes M = getOptimalDFTSize(im_in.rows); N = getOptimalDFTSize(im_in.cols); // convert input to grayscale if RGB if (im_in.channels() == 3) cvtColor(im_in, img_gray, CV_BGR2GRAY); else img_gray = im_in.clone(); // setup the DFT images copyMakeBorder(img_gray, img_padded, 0, M - img_gray.rows, 0, N - img_gray.cols, BORDER_CONSTANT, Scalar::all(0)); planes[0] = Mat_<float>(img_padded); planes[1] = Mat::zeros(img_padded.size(), CV_32F); merge(planes, 2, img_complex); // do the DFT dft(img_complex, img_complex); // construct the filter (same size as complex image) Mat ramp_filter, hann_filter; filter = img_complex.clone(); ramp_filter = filter.clone(); hann_filter = filter.clone(); CreateRampFilter(ramp_filter, 1.0); CreateHannFilter(hann_filter, 1.0); // select filter to apply filter = ramp_filter.clone(); // apply filter ShiftDftToCenter(img_complex); // HERE! WE CAN PARALLELIZE THE MULTIPLICATION OF 2 COMPLEX MATRICES mulSpectrums(img_complex, filter, img_complex, 1); // shift dft to the center ShiftDftToCenter(img_complex); // create magnitude spectrum for display img_magnitude = CreateDisplaySpectrum(img_complex, true); // do inverse DFT on filtered image idft(img_complex, img_complex); // split into planes and extract plane 0 as output image split(img_complex, planes); cv::normalize(planes[0], img_output, 0, 1, CV_MINMAX); // do the same with the filter image split(filter, planes); cv::normalize(planes[0], img_output_display, 0, 1, CV_MINMAX); // save image output im_out = img_output.clone(); // show result Mat rgb = im_in.clone(); cv::normalize(rgb, rgb, 0, 1, cv::NORM_MINMAX); cv::imshow(spectrumMagName, img_magnitude); cv::imshow(lowPassName, img_output); cv::imshow(filterName, img_output_display); // Write result Mat img8bit; img_output_display.convertTo(img8bit, CV_8UC1, 255.0); imwrite( "filtered_sinogram.jpg", img8bit); } //----------------------------------------------------------------------------------------------------- /* Function: ForwardRadonTransform Forward Radon Transform Parameters: im_in - input image for forward projection im_out - sinogram */ //----------------------------------------------------------------------------------------------------- void ForwardRadonTransform(Mat & im_in, Mat & im_out) { // Init double w = im_in.cols; double h = im_in.rows; // calculate the diagonal double d = sqrt(w*w + h*h); // find out how much to enlarge the image so that the original version can rotate inside without loss double dw = (d - w) / 2; double dh = (d - h) / 2; // make image wider copyMakeBorder(im_in, im_in, dh, dh, dw, dw, cv::BORDER_CONSTANT, Scalar::all(0)); // the size of the enlarged (square) image w = im_in.cols; h = im_in.rows; // This will put the result im_out = Mat::zeros(h, w, CV_32FC1); // Center point of rotation Point center = Point(w / 2, h / 2); double angle = 0.0; double scale = 1.0; // Rotate the image double angleStep = 1; // Radon transformation (one line - one projection) Mat RadonImg(180.0 / angleStep, w, CV_32FC1); // Rotate the image, put the result in RadonImg for (int i = 0; i < RadonImg.rows; i++) { Mat rot_mat = getRotationMatrix2D(center, angle, scale); warpAffine(im_in, im_out, rot_mat, im_out.size()); reduce(im_out, RadonImg.row(i), 0, CV_REDUCE_SUM); angle += angleStep; } // Average radon im_out /= RadonImg.rows; im_out = RadonImg.clone(); } //----------------------------------------------------------------------------------------------------- /* Function: ConvertMat2Vector Convert Mat image to vector for Thrust Parameters: im_in - input image for forward projection Returns: vector stores data of image */ //----------------------------------------------------------------------------------------------------- vector<float> ConvertMat2Vector(Mat & im_in) { // Init vector std::vector<float> array; // Convert to vector if (im_in.isContinuous()) { array.assign((float*)im_in.datastart, (float*)im_in.dataend); } else { for (int i = 0; i < im_in.rows; ++i) { array.insert(array.end(), (float*)im_in.ptr<float>(i), (float*)im_in.ptr<float>(i) + im_in.cols); } } return array; } //----------------------------------------------------------------------------------------------------- /* Function: ConcatRow2Vector Concat Mat image using only 1 row to vector for Thrust Parameters: im_in - input image for forward projection num_row - row number to concat Returns: vector stores data of concat image */ //----------------------------------------------------------------------------------------------------- vector<float> ConcatRow2Vector(Mat & im_in, int num_row) { // Init vector std::vector<float> array; // Copy specific row and concat it into a predefine matrix for (int i = 0; i < im_in.cols; ++i) { array.insert(array.end(), (float*)im_in.ptr<float>(num_row), (float*)im_in.ptr<float>(num_row) + im_in.cols); } return array; } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformOpenCV Inverse radon transform using OpenCV Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformOpenCV(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Add matrices using OpenCV for (int j = 0; j < im_out.rows; j++) { im_out.row(j) += im_in.row((im_in.rows - 1) - i); } } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformArray Inverse radon transform using array addition Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformArray(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Get row and col of matrix size_t row = im_out.rows, col = im_out.rows; size_t size_matrix = row*col; // Init arrays float *a = new float[size_matrix]; float *b = new float[size_matrix]; float *c = new float[size_matrix]; // Copy data to array for (int j = 0; j < row; j++) for (int k = 0; k < col; k++) { a[j*col + k] = im_out.at<float>(j, k); b[j*col + k] = im_in.at<float>(im_in.rows - 1 - i, k); } // Add 2 arrays for (size_t j = 0; j < size_matrix; j++) c[j] = a[j] + b[j]; // Copy result to image for (int j = 0; j < row; j++) for (int k = 0; k < col; k++) { im_out.at<float>(j, k) = c[j*col + k]; } } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformCuda Inverse radon transform using Cuda without using shared memory Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformCuda(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection int start_s_cop = 0; for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Init int m, n; float *h_A, *h_B, *h_C; float *d_A, *d_B, *d_C; size_t size; // Size of image m = im_out.rows; n = im_out.cols; size = m*n * sizeof(float); // Allocate host memory h_A = (float*)malloc(size); h_B = (float*)malloc(size); h_C = (float*)malloc(size); // Start clocking for copying data int start_s = clock(); // Transfer data to host var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { h_A[j*n + k] = im_out.at<float>(j, k); h_B[j*n + k] = im_in.at<float>(im_in.rows - 1 - i, k); } // Stop cloking for copying data int stop_s = clock(); // Stack timing start_s_cop = start_s_cop + stop_s - start_s; // Allocate matrices in device memory hipMalloc(&d_A, size); hipMalloc(&d_B, size); hipMalloc(&d_C, size); // Copy matrices from host memory to device memory hipMemcpy(d_A, h_A, size, hipMemcpyHostToDevice); hipMemcpy(d_B, h_B, size, hipMemcpyHostToDevice); // Kernel matrix add MatAddWithoutSharedMemory << <MATRIXWIDTH, MATRIXWIDTH >> > (d_A, d_B, d_C, m, n); // Wait for the kernel to complete hipDeviceSynchronize(); // Copy result from device memory to host memory hipMemcpy(h_C, d_C, size, hipMemcpyDeviceToHost); // Copy result from host memory to local var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { im_out.at<float>(j, k) = h_C[j*n + k]; } // Free host memory free(h_A); free(h_B); free(h_C); // Free device memory hipFree(d_A); hipFree(d_B); hipFree(d_C); } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformCudaSharedMemory Inverse radon transform using Cuda with using shared memory Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformCudaSharedMemory(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection int start_s_cop = 0; for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Init int m, n; float *h_A, *h_B, *h_C; float *d_A, *d_B, *d_C; size_t size; // Size of image m = im_out.rows; n = im_out.cols; size = m*n * sizeof(float); // Allocate host memory h_A = (float*)malloc(size); h_B = (float*)malloc(size); h_C = (float*)malloc(size); // Start clocking for copying data int start_s = clock(); // Transfer data to host var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { h_A[j*n + k] = im_out.at<float>(j, k); h_B[j*n + k] = im_in.at<float>(im_in.rows - 1 - i, k); } // Stop cloking for copying data int stop_s = clock(); // Stack timing start_s_cop = start_s_cop + stop_s - start_s; // Allocate matrices in device memory hipMalloc(&d_A, size); hipMalloc(&d_B, size); hipMalloc(&d_C, size); // Copy matrices from host memory to device memory hipMemcpy(d_A, h_A, size, hipMemcpyHostToDevice); hipMemcpy(d_B, h_B, size, hipMemcpyHostToDevice); // Init dimgrid and dimblock dim3 dimGrid(MATRIXWIDTH / 32, MATRIXWIDTH / 32); dim3 dimBlock(32, 32); // Kernel matrix add MatAddSharedMemory << <dimGrid, dimBlock >> > (d_A, d_B, d_C, m, n); // Wait for the kernel to complete hipDeviceSynchronize(); // Copy result from device memory to host memory hipMemcpy(h_C, d_C, size, hipMemcpyDeviceToHost); // Copy result from host memory to local var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { im_out.at<float>(j, k) = h_C[j*n + k]; } // Free host memory free(h_A); free(h_B); free(h_C); // Free device memory hipFree(d_A); hipFree(d_B); hipFree(d_C); } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformCudaThrust Inverse radon transform using Thrust library Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformCudaThrust(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // thrust method vector<float> v_thrust_in1 = ConvertMat2Vector(im_out); vector<float> v_thrust_in2 = ConcatRow2Vector(im_in, im_in.rows - 1 - i); vector<float> v_thrust_out(im_out.rows*im_out.cols); MatAddThrust(v_thrust_out, v_thrust_in1, v_thrust_in2, im_out.rows*im_out.cols); } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: PerformRadonAndInverseRadon Perform Radon and Inverse Radon transform using filtered-back-projection to reconstruct image Parameters: method - method used */ //----------------------------------------------------------------------------------------------------- void PerformRadonAndInverseRadon(string method) { // Read and display image Mat sinogram; Mat img = imread("C:\\Users\\RD\\Google Drive\\Working\\VS2015\\OpenCVTest\\OpenCVTest\\media\\ct2.jpg", 0); // Resize image to defined image width resize(img, img, Size(IMAGEWIDTH, IMAGEWIDTH)); // Display input image namedWindow("SourceImg"); cv::imshow("SourceImg", img); imwrite( "original.jpg", img); // Init vars Mat sinogram_display, sinogram_filtered, img_reconstructed, img_imwrite; // Forward radon transform ForwardRadonTransform(img, sinogram); cv::normalize(sinogram, sinogram_display, 0, 1, cv::NORM_MINMAX); cv::imshow("RadonTransform", sinogram_display); // Save sinogram sinogram_display.convertTo(img_imwrite, CV_8UC1, 255.0); imwrite( "sinogram.jpg", img_imwrite); // Apply Filter string FilterMethod = "Ramp"; ApplyFilter(sinogram, FilterMethod, sinogram_filtered); // Start clocking int start_s = clock(); // Inverse radon transform with different method if (method.compare("opencv") == 0) // opencv InverseRadonTransformOpenCV(sinogram_filtered, img_reconstructed); else if (method.compare("array") == 0) // normal array InverseRadonTransformArray(sinogram_filtered, img_reconstructed); else if (method.compare("cudathrust") == 0) // thrust InverseRadonTransformCudaThrust(sinogram_filtered, img_reconstructed); else if (method.compare("cudanoshare") == 0) // cuda without shared memory InverseRadonTransformCuda(sinogram_filtered, img_reconstructed); else // cuda with shared memory InverseRadonTransformCudaSharedMemory(sinogram_filtered, img_reconstructed); // Stop clocking int stop_s = clock(); // Method timing if (method.compare("opencv") == 0) // opencv { std::cout << "===================================================================" << endl; std::cout << "Without CUDA using OpenCV" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else if (method.compare("array") == 0) // normal array { std::cout << "===================================================================" << endl; std::cout << "Without CUDA using array" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else if (method.compare("cudathrust") == 0) // thrust { std::cout << "===================================================================" << endl; std::cout << "With CUDA using Thrust" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else if (method.compare("cudanoshare") == 0) // cuda without shared memory { std::cout << "===================================================================" << endl; std::cout << "With CUDA without using shared memory" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else // cuda with shared memory { std::cout << "===================================================================" << endl; std::cout << "With CUDA using shared memory" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } // Display and write reconstructed image cv::normalize(img_reconstructed, img_reconstructed, 0, 1, cv::NORM_MINMAX); cv::imshow("ReconstructedImage", img_reconstructed); img_reconstructed.convertTo(img_imwrite, CV_8UC1, 255.0); imwrite( "final.jpg", img_imwrite); } void PerformCuFFT() { // Read image Mat des; Mat img = imread("C:\\Users\\RD\\Google Drive\\Working\\VS2015\\OpenCVTest\\OpenCVTest\\media\\ct.jpeg", 0); resize(img, img, Size(), 0.2, 0.2); namedWindow("SourceImg"); imshow("SourceImg", img); // Radon transform Mat des_print, filterOutput, inverse_img; ForwardRadonTransform(img, des); normalize(des, des_print, 0, 1, cv::NORM_MINMAX); imshow("RadonTransform", des_print); int NX = des.rows; int NY = des.cols; int NN = 1000; std::cout << "NX=" << NX << " ; NY=" << NY << " ; NN=" << NN << std::endl; hipfftHandle plan; hipfftComplex *dev_data, *res; hipMalloc((void**)&dev_data, sizeof(hipfftComplex)*NX*NY); hipMalloc((void**)&res, sizeof(hipfftComplex)*NX*NY); /* Try to do the same thing than cv::randu() */ hipfftComplex* host_data; host_data = (hipfftComplex *)malloc(sizeof(hipfftComplex)*NX*NY); srand(time(NULL)); float value; int idx; for (int i = 0; i < NX; i++) { for (int j = 0; j < NY; j++) { value = des.at<float>(i, j); idx = i*NX + j - 1; host_data[idx] = make_cuComplex(value, value); } } hipMemcpy(dev_data, host_data, sizeof(hipfftComplex)*NX*NY, hipMemcpyHostToDevice); /* Warm up ? */ double t = cv::getTickCount(); int start_s = clock(); /* Create a 2D FFT plan. */ hipfftPlan2d(&plan, NX, NY, HIPFFT_C2C); hipfftExecC2C(plan, dev_data, res, HIPFFT_FORWARD); int stop_s = clock(); cout << "===================================================================" << endl; cout << "With CUDA FFT" << endl; cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; std::cout << "Cuda time=" << t << " ms" << std::endl; int size_of_one_set = sizeof(hipfftComplex) * NX*NY; hipfftComplex* result; result = (hipfftComplex*)malloc(size_of_one_set); hipMemcpy(result, res, sizeof(hipfftComplex)*NX*NY, hipMemcpyDeviceToHost); /* Destroy the cuFFT plan. */ hipfftDestroy(plan); hipFree(dev_data); } //----------------------------------------------------------------------------------------------------- /* Function: MatMulPixelwiseWithoutSharedMemory Multiply 2 complex matrices without using shared memory Parameters: A_r - Matrix input 1 real part A_c - Matrix input 1 complex part B_r - Matrix input 2 real part B_c - Matrix input 2 complex part C_r - Matrix output real part C_c - Matrix output complex part m - Matrix row n - Matrix column */ //----------------------------------------------------------------------------------------------------- __global__ void MatMulPixelwiseWithoutSharedMemory(float A_r[], float A_c[], float B_r[], float B_c[], float C_r[], float C_c[], int m, int n) { /* blockDim.x = threads_per_block */ /* First block gets first threads_per_block components. */ /* Second block gets next threads_per_block components, etc. */ int idx = blockDim.x * blockIdx.x + threadIdx.x; /* The test shouldn't be necessary */ if (blockIdx.x < m && threadIdx.x < n) { C_r[idx] = A_r[idx] * B_r[idx] - A_c[idx] * B_c[idx]; C_c[idx] = A_r[idx] * B_c[idx] - A_c[idx] * B_r[idx]; } } //----------------------------------------------------------------------------------------------------- /* Function: MultiplySpectrums Multiply 2 complex matrices Parameters: planes - planes of complex image planes_filter - planes of filter image img_complex - output image */ //----------------------------------------------------------------------------------------------------- void MultiplySpectrums(Mat & planes_r, Mat & planes_c, Mat & planes_filter_r, Mat & planes_filter_c, Mat & img_complex) { vector<float> A_r = ConvertMat2Vector(planes_r); vector<float> A_c = ConvertMat2Vector(planes_c); vector<float> B_r = ConvertMat2Vector(planes_filter_r); vector<float> B_c = ConvertMat2Vector(planes_filter_c); // Init int m, n; float *h_A_r, *h_B_r, *h_C_r; float *h_A_c, *h_B_c, *h_C_c; float *d_A_r, *d_B_r, *d_C_r; float *d_A_c, *d_B_c, *d_C_c; size_t size; // Size of image m = planes_r.rows; n = planes_r.cols; size = m*n * sizeof(float); // Allocate host memory h_A_r = (float*)malloc(size); h_B_r = (float*)malloc(size); h_C_r = (float*)malloc(size); h_A_c = (float*)malloc(size); h_B_c = (float*)malloc(size); h_C_c = (float*)malloc(size); // Start clocking for copying data int start_s = clock(); // Transfer data to host var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { h_A_r[j*n + k] = planes_r.at<float>(j, k); h_B_r[j*n + k] = planes_filter_r.at<float>(j, k); h_A_c[j*n + k] = planes_c.at<float>(j, k); h_B_c[j*n + k] = planes_filter_c.at<float>(j, k); } // Stop cloking for copying data int stop_s = clock(); // Allocate matrices in device memory hipMalloc(&d_A_r, size); hipMalloc(&d_B_r, size); hipMalloc(&d_C_r, size); hipMalloc(&d_A_c, size); hipMalloc(&d_B_c, size); hipMalloc(&d_C_c, size); // Copy matrices from host memory to device memory hipMemcpy(d_A_r, h_A_r, size, hipMemcpyHostToDevice); hipMemcpy(d_B_r, h_B_r, size, hipMemcpyHostToDevice); hipMemcpy(d_A_c, h_A_c, size, hipMemcpyHostToDevice); hipMemcpy(d_B_c, h_B_c, size, hipMemcpyHostToDevice); // Kernel matrix add MatMulPixelwiseWithoutSharedMemory << <MATRIXWIDTH, MATRIXWIDTH >> > (d_A_r, d_A_c, d_B_r, d_B_c, d_C_r, d_C_c, m, n); // Wait for the kernel to complete hipDeviceSynchronize(); // Copy result from device memory to host memory hipMemcpy(h_C_r, d_C_r, size, hipMemcpyDeviceToHost); hipMemcpy(h_C_c, d_C_c, size, hipMemcpyDeviceToHost); // Declare block vars Mat plane_temp[2]; Mat m_A_r_temp = Mat::zeros(img_complex.size(), CV_32F); Mat m_A_c_temp = Mat::zeros(img_complex.size(), CV_32F); // Copy result from host memory to local var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { m_A_r_temp.at<float>(j, k) = h_C_r[j*n + k]; m_A_c_temp.at<float>(j, k) = h_C_c[j*n + k]; } plane_temp[0] = m_A_r_temp; plane_temp[1] = m_A_c_temp; merge(plane_temp, 2, img_complex); // Free host memory free(h_A_r); free(h_B_r); free(h_C_r); free(h_A_c); free(h_B_c); free(h_C_c); // Free device memory hipFree(d_A_r); hipFree(d_B_r); hipFree(d_C_r); hipFree(d_A_c); hipFree(d_B_c); hipFree(d_C_c); } //----------------------------------------------------------------------------------------------------- /* Function: ApplyFilterCuda Apply filter to sinogram using cuda when multiplying 2 complex matrices Parameters: im_in - input image filter_method - filter method im_out - output image */ //----------------------------------------------------------------------------------------------------- void ApplyFilterCuda(Mat & im_in, string filter_method, Mat & im_out) { // Init images objects Mat img_gray, img_output, img_output_display; Mat img_padded; Mat img_complex, filter; Mat planes[2], planes_filter[2], img_magnitude; // Fourier image size int N, M; // String constant for image title const string originalName = "Input Image (grayscale)"; // window name const string spectrumMagName = "Magnitude Image (log transformed)"; // window name const string lowPassName = "Ramp Filtered (grayscale)"; // window name const string filterName = "Filter Image"; // window nam // setup the DFT image sizes M = getOptimalDFTSize(im_in.rows); N = getOptimalDFTSize(im_in.cols); // convert input to grayscale if RGB if (im_in.channels() == 3) cvtColor(im_in, img_gray, CV_BGR2GRAY); else img_gray = im_in.clone(); // setup the DFT images copyMakeBorder(img_gray, img_padded, 0, M - img_gray.rows, 0, N - img_gray.cols, BORDER_CONSTANT, Scalar::all(0)); planes[0] = Mat_<float>(img_padded); planes[1] = Mat::zeros(img_padded.size(), CV_32F); merge(planes, 2, img_complex); // do the DFT dft(img_complex, img_complex); // construct the filter (same size as complex image) Mat ramp_filter, hann_filter; filter = img_complex.clone(); ramp_filter = filter.clone(); hann_filter = filter.clone(); CreateRampFilter(ramp_filter, 1.0); CreateHannFilter(hann_filter, 1.0); // select filter to apply filter = ramp_filter.clone(); // apply filter ShiftDftToCenter(img_complex); // HERE! WE CAN PARALLELIZE THE MULTIPLICATION OF 2 COMPLEX MATRICES split(img_complex, planes); split(filter, planes_filter); mulSpectrums(img_complex, filter, img_complex, 1); // shift dft to the center ShiftDftToCenter(img_complex); // create magnitude spectrum for display img_magnitude = CreateDisplaySpectrum(img_complex, true); // do inverse DFT on filtered image idft(img_complex, img_complex); // split into planes and extract plane 0 as output image split(img_complex, planes); cv::normalize(planes[0], img_output, 0, 1, CV_MINMAX); // do the same with the filter image split(filter, planes); cv::normalize(planes[0], img_output_display, 0, 1, CV_MINMAX); // save image output im_out = img_output.clone(); // show result Mat rgb = im_in.clone(); cv::normalize(rgb, rgb, 0, 1, cv::NORM_MINMAX); cv::imshow(spectrumMagName, img_magnitude); cv::imshow(lowPassName, img_output); cv::imshow(filterName, img_output_display); // Write result Mat img8bit; img_output_display.convertTo(img8bit, CV_8UC1, 255.0); imwrite( "filtered_sinogram.jpg", img8bit); }
7c30b9af9f18036c9d1c654fadcbb92a553365a6.cu
// ==================================================================================================== // liba for cuda #include <cuda.h> #include <device_functions.h> #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <cufft.h> #include <thrust/host_vector.h> #include <thrust/device_vector.h> #include <thrust/transform.h> #include <thrust/functional.h> // libs common #include <iostream> #include <time.h> #include <stdio.h> #include <vector> #include <stdio.h> #include <stdarg.h> #include "fstream" #include "iostream" #include <complex> #include <cmath> #include <cstdlib> // libs for opencv #include "opencv2/core/core.hpp" #include "opencv2/highgui/highgui.hpp" #include "opencv2/imgproc/imgproc.hpp" #include "opencv2/core/cuda.hpp" // namespace using namespace std; using namespace cv; // constants #define PI 3.14159265 #define SIZE 2 #define TILE_DIM 16 #define WIDTHPERBLOCK 32 #define BLOCK_ROWS 8 #define MATRIXWIDTH 128 #define MATRIXAREA MATRIXWIDTH*MATRIXWIDTH #define IMAGEWIDTH round(MATRIXWIDTH/sqrt(2)) // shred memory __shared__ float As[WIDTHPERBLOCK][WIDTHPERBLOCK]; __shared__ float Bs[WIDTHPERBLOCK][WIDTHPERBLOCK]; extern __shared__ float a[]; extern __shared__ float b[]; // ==================================================================================================== // Thrust vector<float> ConvertMat2Vector(Mat & im_in); vector<float> ConcatRow2Vector(Mat & im_in, int num_row); void MatAddThrust(std::vector<float> & v_out, std::vector<float> v_in1, std::vector<float> v_in2, unsigned int v_size); // DFT and Forward Radon Transform void ShiftDftToCenter(Mat & im_in); Mat CreateDisplaySpectrum(Mat & complexImg, bool rearrange); void CreateRampFilter(Mat & ramp_filter, double a); void CreateHannFilter(Mat & hann_filter, double a); void ApplyFilter(Mat & im_in, string filter_method, Mat & im_out); void ForwardRadonTransform(Mat & im_in, Mat & im_out); void PerformCuFFT(); // Add without shared memory __global__ void MatAddWithoutSharedMemory(float A[], float B[], float C[], int m, int n); // Add with shared memory __global__ void MatAddSharedMemory(float A[], float B[], float C[], int m, int n); // Methods void InverseRadonTransformOpenCV(Mat & im_in, Mat & im_out); void InverseRadonTransformArray(Mat & im_in, Mat & im_out); void InverseRadonTransformCuda(Mat & im_in, Mat & im_out); void InverseRadonTransformCudaSharedMemory(Mat & im_in, Mat & im_out); void InverseRadonTransformCudaThrust(Mat & im_in, Mat & im_out); void PerformRadonAndInverseRadon(string method); // Addition, Cuda while multiplying 2 complex matrices void ApplyFilterCuda(Mat & im_in, string filter_method, Mat & im_out); __global__ void MatMulPixelwiseWithoutSharedMemory(float A_r[], float A_c[], float B_r[], float B_c[], float C_r[], float C_c[], int m, int n); void MultiplySpectrums(Mat & planes_r, Mat & planes_c, Mat & planes_filter_r, Mat & planes_filter_c, Mat & img_complex); // ==================================================================================================== int main() { string method; method = "cudathrust"; PerformRadonAndInverseRadon(method); method = "cudanoshare"; PerformRadonAndInverseRadon(method); method = "cudashare"; PerformRadonAndInverseRadon(method); method = "array"; PerformRadonAndInverseRadon(method); method = "opencv"; PerformRadonAndInverseRadon(method); waitKey(0); return 0; } // ==================================================================================================== //----------------------------------------------------------------------------------------------------- /* Function: MatAddThrust Add 2 vectors using Thrust library Parameters: v_out - result vector v_in1 - vector 1 v_in2 - vector 2 v_size - vector size */ //----------------------------------------------------------------------------------------------------- void MatAddThrust(std::vector<float> & v_out, std::vector<float> v_in1, std::vector<float> v_in2, unsigned int v_size) { // Init vector in thrust thrust::device_vector<float> X(v_in1.begin(), v_in1.end()); thrust::device_vector<float> Y(v_in2.begin(), v_in2.end()); thrust::device_vector<float> Z(v_size); // Make adition thrust::transform(X.begin(), X.end(), Y.begin(), Z.begin(), thrust::plus<float>()); // Copy data back thrust::copy(Z.begin(), Z.end(), v_out.begin()); } //----------------------------------------------------------------------------------------------------- /* Function: MatAddWithoutSharedMemory Add 2 matrices without using shared memory Parameters: A - Matrix input 1 B - Matrix input 2 C - Matrix output m - Matrix row n - Matrix column */ //----------------------------------------------------------------------------------------------------- __global__ void MatAddWithoutSharedMemory(float A[], float B[], float C[], int m, int n) { /* blockDim.x = threads_per_block */ /* First block gets first threads_per_block components. */ /* Second block gets next threads_per_block components, etc. */ int idx = blockDim.x * blockIdx.x + threadIdx.x; /* The test shouldn't be necessary */ if (blockIdx.x < m && threadIdx.x < n) C[idx] = A[idx] + B[idx]; } //----------------------------------------------------------------------------------------------------- /* Function: MatAddSharedMemory Add 2 matrices using shared memory Parameters: A - Matrix input 1 B - Matrix input 2 C - Matrix output m - Matrix row n - Matrix column */ //----------------------------------------------------------------------------------------------------- __global__ void MatAddSharedMemory(float A[], float B[], float C[], int m, int n) { /* blockDim.x = threads_per_block */ /* First block gets first threads_per_block components. */ /* Second block gets next threads_per_block components, etc. */ int idx = blockDim.x * blockIdx.x + threadIdx.x; // Copy data to shared memory a[idx] = A[idx]; __syncthreads(); b[idx] = B[idx]; __syncthreads(); /* The test shouldn't be necessary */ if (blockIdx.x < m && threadIdx.x < n) { C[idx] = a[idx] + b[idx]; __syncthreads(); } } //----------------------------------------------------------------------------------------------------- /* Function: ShiftDftToCenter Shift DFT to the center Parameters: im_in - input image */ //----------------------------------------------------------------------------------------------------- void ShiftDftToCenter(Mat & im_in) { // init vars Mat tmp, q0, q1, q2, q3; // first crop the image, if it has an odd number of rows or columns im_in = im_in(Rect(0, 0, im_in.cols & -2, im_in.rows & -2)); // get size of image int cx = im_in.cols / 2; int cy = im_in.rows / 2; // rearrange the quadrants of Fourier image // so that the origin is at the image center q0 = im_in(Rect(0, 0, cx, cy)); q1 = im_in(Rect(cx, 0, cx, cy)); q2 = im_in(Rect(0, cy, cx, cy)); q3 = im_in(Rect(cx, cy, cx, cy)); // copy back q0.copyTo(tmp); q3.copyTo(q0); tmp.copyTo(q3); // shift q1.copyTo(tmp); q2.copyTo(q1); tmp.copyTo(q2); } //----------------------------------------------------------------------------------------------------- /* Function: CreateDisplaySpectrum Create image to display the spectrum Parameters: complexImg - input dft (2 channel floating point, Real + Imaginary fourier image) rearrange - perform rearrangement of DFT quadrants if true Returns: pointer to output spectrum magnitude image scaled for user viewing */ //----------------------------------------------------------------------------------------------------- Mat CreateDisplaySpectrum(Mat & complexImg, bool rearrange) { // init vars Mat planes[2]; // split plane split(complexImg, planes); magnitude(planes[0], planes[1], planes[0]); // for magnitude Mat mag = (planes[0]).clone(); mag += Scalar::all(1); log(mag, mag); // shift to center if (rearrange) { ShiftDftToCenter(mag); } // normalize image cv::normalize(mag, mag, 0, 1, CV_MINMAX); // get result return mag; } //----------------------------------------------------------------------------------------------------- /* Function: CreateRampFilter Create Ramp Filter Parameters: ramp_filter - ramp filter a - threshold */ //----------------------------------------------------------------------------------------------------- void CreateRampFilter(Mat & ramp_filter, double a) { // init image blocks Mat tmp = Mat(ramp_filter.rows, ramp_filter.cols, CV_32F); // get row and col of image int N = ramp_filter.cols; int M = ramp_filter.rows; // init vars double step; step = 2 * a / (N - 1); // make filter for (int i = 0; i < ramp_filter.rows; i++) { for (int j = 0; j < ramp_filter.cols; j++) { tmp.at<float>(i, j) = abs(-a + j*step); } } // patch real part with 0 Mat abc = Mat::zeros(tmp.size(), CV_32F); // merge real and complex parts Mat toMerge[] = { tmp, abc }; merge(toMerge, 2, ramp_filter); } //----------------------------------------------------------------------------------------------------- /* Function: CreateHannFilter Create Hann Filter Parameters: hann_filter - hann filter a - threshold */ //----------------------------------------------------------------------------------------------------- void CreateHannFilter(Mat & hann_filter, double a) { // init image blocks Mat tmp = Mat(hann_filter.rows, hann_filter.cols, CV_32F); // get row and col of image int N = hann_filter.cols; // length int M = hann_filter.rows; // 180% radon // init vars double step, ramp, hann; step = 2 * a / (N - 1); // make filter for (int i = 0; i < hann_filter.rows; i++) { for (int j = 0; j < hann_filter.cols; j++) { ramp = abs(-a + j*step); hann = sin(j*PI / (N - 1)); hann = pow(hann, 2.0); tmp.at<float>(i, j) = ramp*hann; } } // patch real part with 0 Mat abc = Mat::zeros(tmp.size(), CV_32F); // merge real and complex parts Mat toMerge[] = { tmp, abc }; merge(toMerge, 2, hann_filter); } //----------------------------------------------------------------------------------------------------- /* Function: ApplyFilter Apply filter to sinogram Parameters: im_in - input image filter_method - filter method im_out - output image */ //----------------------------------------------------------------------------------------------------- void ApplyFilter(Mat & im_in, string filter_method, Mat & im_out) { // Init images objects Mat img_gray, img_output, img_output_display; Mat img_padded; Mat img_complex, filter; Mat planes[2], img_magnitude; // Fourier image size int N, M; // String constant for image title const string originalName = "Input Image (grayscale)"; // window name const string spectrumMagName = "Magnitude Image (log transformed)"; // window name const string lowPassName = "Ramp Filtered (grayscale)"; // window name const string filterName = "Filter Image"; // window nam // setup the DFT image sizes M = getOptimalDFTSize(im_in.rows); N = getOptimalDFTSize(im_in.cols); // convert input to grayscale if RGB if (im_in.channels() == 3) cvtColor(im_in, img_gray, CV_BGR2GRAY); else img_gray = im_in.clone(); // setup the DFT images copyMakeBorder(img_gray, img_padded, 0, M - img_gray.rows, 0, N - img_gray.cols, BORDER_CONSTANT, Scalar::all(0)); planes[0] = Mat_<float>(img_padded); planes[1] = Mat::zeros(img_padded.size(), CV_32F); merge(planes, 2, img_complex); // do the DFT dft(img_complex, img_complex); // construct the filter (same size as complex image) Mat ramp_filter, hann_filter; filter = img_complex.clone(); ramp_filter = filter.clone(); hann_filter = filter.clone(); CreateRampFilter(ramp_filter, 1.0); CreateHannFilter(hann_filter, 1.0); // select filter to apply filter = ramp_filter.clone(); // apply filter ShiftDftToCenter(img_complex); // HERE! WE CAN PARALLELIZE THE MULTIPLICATION OF 2 COMPLEX MATRICES mulSpectrums(img_complex, filter, img_complex, 1); // shift dft to the center ShiftDftToCenter(img_complex); // create magnitude spectrum for display img_magnitude = CreateDisplaySpectrum(img_complex, true); // do inverse DFT on filtered image idft(img_complex, img_complex); // split into planes and extract plane 0 as output image split(img_complex, planes); cv::normalize(planes[0], img_output, 0, 1, CV_MINMAX); // do the same with the filter image split(filter, planes); cv::normalize(planes[0], img_output_display, 0, 1, CV_MINMAX); // save image output im_out = img_output.clone(); // show result Mat rgb = im_in.clone(); cv::normalize(rgb, rgb, 0, 1, cv::NORM_MINMAX); cv::imshow(spectrumMagName, img_magnitude); cv::imshow(lowPassName, img_output); cv::imshow(filterName, img_output_display); // Write result Mat img8bit; img_output_display.convertTo(img8bit, CV_8UC1, 255.0); imwrite( "filtered_sinogram.jpg", img8bit); } //----------------------------------------------------------------------------------------------------- /* Function: ForwardRadonTransform Forward Radon Transform Parameters: im_in - input image for forward projection im_out - sinogram */ //----------------------------------------------------------------------------------------------------- void ForwardRadonTransform(Mat & im_in, Mat & im_out) { // Init double w = im_in.cols; double h = im_in.rows; // calculate the diagonal double d = sqrt(w*w + h*h); // find out how much to enlarge the image so that the original version can rotate inside without loss double dw = (d - w) / 2; double dh = (d - h) / 2; // make image wider copyMakeBorder(im_in, im_in, dh, dh, dw, dw, cv::BORDER_CONSTANT, Scalar::all(0)); // the size of the enlarged (square) image w = im_in.cols; h = im_in.rows; // This will put the result im_out = Mat::zeros(h, w, CV_32FC1); // Center point of rotation Point center = Point(w / 2, h / 2); double angle = 0.0; double scale = 1.0; // Rotate the image double angleStep = 1; // Radon transformation (one line - one projection) Mat RadonImg(180.0 / angleStep, w, CV_32FC1); // Rotate the image, put the result in RadonImg for (int i = 0; i < RadonImg.rows; i++) { Mat rot_mat = getRotationMatrix2D(center, angle, scale); warpAffine(im_in, im_out, rot_mat, im_out.size()); reduce(im_out, RadonImg.row(i), 0, CV_REDUCE_SUM); angle += angleStep; } // Average radon im_out /= RadonImg.rows; im_out = RadonImg.clone(); } //----------------------------------------------------------------------------------------------------- /* Function: ConvertMat2Vector Convert Mat image to vector for Thrust Parameters: im_in - input image for forward projection Returns: vector stores data of image */ //----------------------------------------------------------------------------------------------------- vector<float> ConvertMat2Vector(Mat & im_in) { // Init vector std::vector<float> array; // Convert to vector if (im_in.isContinuous()) { array.assign((float*)im_in.datastart, (float*)im_in.dataend); } else { for (int i = 0; i < im_in.rows; ++i) { array.insert(array.end(), (float*)im_in.ptr<float>(i), (float*)im_in.ptr<float>(i) + im_in.cols); } } return array; } //----------------------------------------------------------------------------------------------------- /* Function: ConcatRow2Vector Concat Mat image using only 1 row to vector for Thrust Parameters: im_in - input image for forward projection num_row - row number to concat Returns: vector stores data of concat image */ //----------------------------------------------------------------------------------------------------- vector<float> ConcatRow2Vector(Mat & im_in, int num_row) { // Init vector std::vector<float> array; // Copy specific row and concat it into a predefine matrix for (int i = 0; i < im_in.cols; ++i) { array.insert(array.end(), (float*)im_in.ptr<float>(num_row), (float*)im_in.ptr<float>(num_row) + im_in.cols); } return array; } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformOpenCV Inverse radon transform using OpenCV Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformOpenCV(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Add matrices using OpenCV for (int j = 0; j < im_out.rows; j++) { im_out.row(j) += im_in.row((im_in.rows - 1) - i); } } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformArray Inverse radon transform using array addition Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformArray(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Get row and col of matrix size_t row = im_out.rows, col = im_out.rows; size_t size_matrix = row*col; // Init arrays float *a = new float[size_matrix]; float *b = new float[size_matrix]; float *c = new float[size_matrix]; // Copy data to array for (int j = 0; j < row; j++) for (int k = 0; k < col; k++) { a[j*col + k] = im_out.at<float>(j, k); b[j*col + k] = im_in.at<float>(im_in.rows - 1 - i, k); } // Add 2 arrays for (size_t j = 0; j < size_matrix; j++) c[j] = a[j] + b[j]; // Copy result to image for (int j = 0; j < row; j++) for (int k = 0; k < col; k++) { im_out.at<float>(j, k) = c[j*col + k]; } } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformCuda Inverse radon transform using Cuda without using shared memory Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformCuda(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection int start_s_cop = 0; for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Init int m, n; float *h_A, *h_B, *h_C; float *d_A, *d_B, *d_C; size_t size; // Size of image m = im_out.rows; n = im_out.cols; size = m*n * sizeof(float); // Allocate host memory h_A = (float*)malloc(size); h_B = (float*)malloc(size); h_C = (float*)malloc(size); // Start clocking for copying data int start_s = clock(); // Transfer data to host var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { h_A[j*n + k] = im_out.at<float>(j, k); h_B[j*n + k] = im_in.at<float>(im_in.rows - 1 - i, k); } // Stop cloking for copying data int stop_s = clock(); // Stack timing start_s_cop = start_s_cop + stop_s - start_s; // Allocate matrices in device memory cudaMalloc(&d_A, size); cudaMalloc(&d_B, size); cudaMalloc(&d_C, size); // Copy matrices from host memory to device memory cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice); cudaMemcpy(d_B, h_B, size, cudaMemcpyHostToDevice); // Kernel matrix add MatAddWithoutSharedMemory << <MATRIXWIDTH, MATRIXWIDTH >> > (d_A, d_B, d_C, m, n); // Wait for the kernel to complete cudaThreadSynchronize(); // Copy result from device memory to host memory cudaMemcpy(h_C, d_C, size, cudaMemcpyDeviceToHost); // Copy result from host memory to local var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { im_out.at<float>(j, k) = h_C[j*n + k]; } // Free host memory free(h_A); free(h_B); free(h_C); // Free device memory cudaFree(d_A); cudaFree(d_B); cudaFree(d_C); } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformCudaSharedMemory Inverse radon transform using Cuda with using shared memory Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformCudaSharedMemory(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection int start_s_cop = 0; for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // Init int m, n; float *h_A, *h_B, *h_C; float *d_A, *d_B, *d_C; size_t size; // Size of image m = im_out.rows; n = im_out.cols; size = m*n * sizeof(float); // Allocate host memory h_A = (float*)malloc(size); h_B = (float*)malloc(size); h_C = (float*)malloc(size); // Start clocking for copying data int start_s = clock(); // Transfer data to host var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { h_A[j*n + k] = im_out.at<float>(j, k); h_B[j*n + k] = im_in.at<float>(im_in.rows - 1 - i, k); } // Stop cloking for copying data int stop_s = clock(); // Stack timing start_s_cop = start_s_cop + stop_s - start_s; // Allocate matrices in device memory cudaMalloc(&d_A, size); cudaMalloc(&d_B, size); cudaMalloc(&d_C, size); // Copy matrices from host memory to device memory cudaMemcpy(d_A, h_A, size, cudaMemcpyHostToDevice); cudaMemcpy(d_B, h_B, size, cudaMemcpyHostToDevice); // Init dimgrid and dimblock dim3 dimGrid(MATRIXWIDTH / 32, MATRIXWIDTH / 32); dim3 dimBlock(32, 32); // Kernel matrix add MatAddSharedMemory << <dimGrid, dimBlock >> > (d_A, d_B, d_C, m, n); // Wait for the kernel to complete cudaThreadSynchronize(); // Copy result from device memory to host memory cudaMemcpy(h_C, d_C, size, cudaMemcpyDeviceToHost); // Copy result from host memory to local var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { im_out.at<float>(j, k) = h_C[j*n + k]; } // Free host memory free(h_A); free(h_B); free(h_C); // Free device memory cudaFree(d_A); cudaFree(d_B); cudaFree(d_C); } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: InverseRadonTransformCudaThrust Inverse radon transform using Thrust library Parameters: im_in - filtered sinogram im_out - reconstructed image */ //----------------------------------------------------------------------------------------------------- void InverseRadonTransformCudaThrust(Mat & im_in, Mat & im_out) { // Init im_in.convertTo(im_in, CV_32FC1); double d = im_in.cols; im_out = Mat::zeros(d, d, CV_32FC1); // Center point Point center = Point(d / 2, d / 2); // Angle step rotation double angleStep = 1; // Scale double scale = 1.0; // Rotation matrix Mat rot_mat = getRotationMatrix2D(center, -angleStep, scale); // Start back-projection for (int i = 0; i < im_in.rows; i++) { // Get rotated matrix warpAffine(im_out, im_out, rot_mat, im_out.size()); // thrust method vector<float> v_thrust_in1 = ConvertMat2Vector(im_out); vector<float> v_thrust_in2 = ConcatRow2Vector(im_in, im_in.rows - 1 - i); vector<float> v_thrust_out(im_out.rows*im_out.cols); MatAddThrust(v_thrust_out, v_thrust_in1, v_thrust_in2, im_out.rows*im_out.cols); } // Crop image d = (d - d / (sqrt(2.0)))*0.55; // cut a little more double dw = d; double dh = d; im_out = im_out(Rect(dw, dh, im_out.cols - 2 * dw, im_out.rows - 2 * dh)); } //----------------------------------------------------------------------------------------------------- /* Function: PerformRadonAndInverseRadon Perform Radon and Inverse Radon transform using filtered-back-projection to reconstruct image Parameters: method - method used */ //----------------------------------------------------------------------------------------------------- void PerformRadonAndInverseRadon(string method) { // Read and display image Mat sinogram; Mat img = imread("C:\\Users\\RD\\Google Drive\\Working\\VS2015\\OpenCVTest\\OpenCVTest\\media\\ct2.jpg", 0); // Resize image to defined image width resize(img, img, Size(IMAGEWIDTH, IMAGEWIDTH)); // Display input image namedWindow("SourceImg"); cv::imshow("SourceImg", img); imwrite( "original.jpg", img); // Init vars Mat sinogram_display, sinogram_filtered, img_reconstructed, img_imwrite; // Forward radon transform ForwardRadonTransform(img, sinogram); cv::normalize(sinogram, sinogram_display, 0, 1, cv::NORM_MINMAX); cv::imshow("RadonTransform", sinogram_display); // Save sinogram sinogram_display.convertTo(img_imwrite, CV_8UC1, 255.0); imwrite( "sinogram.jpg", img_imwrite); // Apply Filter string FilterMethod = "Ramp"; ApplyFilter(sinogram, FilterMethod, sinogram_filtered); // Start clocking int start_s = clock(); // Inverse radon transform with different method if (method.compare("opencv") == 0) // opencv InverseRadonTransformOpenCV(sinogram_filtered, img_reconstructed); else if (method.compare("array") == 0) // normal array InverseRadonTransformArray(sinogram_filtered, img_reconstructed); else if (method.compare("cudathrust") == 0) // thrust InverseRadonTransformCudaThrust(sinogram_filtered, img_reconstructed); else if (method.compare("cudanoshare") == 0) // cuda without shared memory InverseRadonTransformCuda(sinogram_filtered, img_reconstructed); else // cuda with shared memory InverseRadonTransformCudaSharedMemory(sinogram_filtered, img_reconstructed); // Stop clocking int stop_s = clock(); // Method timing if (method.compare("opencv") == 0) // opencv { std::cout << "===================================================================" << endl; std::cout << "Without CUDA using OpenCV" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else if (method.compare("array") == 0) // normal array { std::cout << "===================================================================" << endl; std::cout << "Without CUDA using array" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else if (method.compare("cudathrust") == 0) // thrust { std::cout << "===================================================================" << endl; std::cout << "With CUDA using Thrust" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else if (method.compare("cudanoshare") == 0) // cuda without shared memory { std::cout << "===================================================================" << endl; std::cout << "With CUDA without using shared memory" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } else // cuda with shared memory { std::cout << "===================================================================" << endl; std::cout << "With CUDA using shared memory" << endl; std::cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; } // Display and write reconstructed image cv::normalize(img_reconstructed, img_reconstructed, 0, 1, cv::NORM_MINMAX); cv::imshow("ReconstructedImage", img_reconstructed); img_reconstructed.convertTo(img_imwrite, CV_8UC1, 255.0); imwrite( "final.jpg", img_imwrite); } void PerformCuFFT() { // Read image Mat des; Mat img = imread("C:\\Users\\RD\\Google Drive\\Working\\VS2015\\OpenCVTest\\OpenCVTest\\media\\ct.jpeg", 0); resize(img, img, Size(), 0.2, 0.2); namedWindow("SourceImg"); imshow("SourceImg", img); // Radon transform Mat des_print, filterOutput, inverse_img; ForwardRadonTransform(img, des); normalize(des, des_print, 0, 1, cv::NORM_MINMAX); imshow("RadonTransform", des_print); int NX = des.rows; int NY = des.cols; int NN = 1000; std::cout << "NX=" << NX << " ; NY=" << NY << " ; NN=" << NN << std::endl; cufftHandle plan; cufftComplex *dev_data, *res; cudaMalloc((void**)&dev_data, sizeof(cufftComplex)*NX*NY); cudaMalloc((void**)&res, sizeof(cufftComplex)*NX*NY); /* Try to do the same thing than cv::randu() */ cufftComplex* host_data; host_data = (cufftComplex *)malloc(sizeof(cufftComplex)*NX*NY); srand(time(NULL)); float value; int idx; for (int i = 0; i < NX; i++) { for (int j = 0; j < NY; j++) { value = des.at<float>(i, j); idx = i*NX + j - 1; host_data[idx] = make_cuComplex(value, value); } } cudaMemcpy(dev_data, host_data, sizeof(cufftComplex)*NX*NY, cudaMemcpyHostToDevice); /* Warm up ? */ double t = cv::getTickCount(); int start_s = clock(); /* Create a 2D FFT plan. */ cufftPlan2d(&plan, NX, NY, CUFFT_C2C); cufftExecC2C(plan, dev_data, res, CUFFT_FORWARD); int stop_s = clock(); cout << "===================================================================" << endl; cout << "With CUDA FFT" << endl; cout << "time: " << (stop_s - start_s) / double(CLOCKS_PER_SEC) << " seconds" << endl; std::cout << "Cuda time=" << t << " ms" << std::endl; int size_of_one_set = sizeof(cufftComplex) * NX*NY; cufftComplex* result; result = (cufftComplex*)malloc(size_of_one_set); cudaMemcpy(result, res, sizeof(cufftComplex)*NX*NY, cudaMemcpyDeviceToHost); /* Destroy the cuFFT plan. */ cufftDestroy(plan); cudaFree(dev_data); } //----------------------------------------------------------------------------------------------------- /* Function: MatMulPixelwiseWithoutSharedMemory Multiply 2 complex matrices without using shared memory Parameters: A_r - Matrix input 1 real part A_c - Matrix input 1 complex part B_r - Matrix input 2 real part B_c - Matrix input 2 complex part C_r - Matrix output real part C_c - Matrix output complex part m - Matrix row n - Matrix column */ //----------------------------------------------------------------------------------------------------- __global__ void MatMulPixelwiseWithoutSharedMemory(float A_r[], float A_c[], float B_r[], float B_c[], float C_r[], float C_c[], int m, int n) { /* blockDim.x = threads_per_block */ /* First block gets first threads_per_block components. */ /* Second block gets next threads_per_block components, etc. */ int idx = blockDim.x * blockIdx.x + threadIdx.x; /* The test shouldn't be necessary */ if (blockIdx.x < m && threadIdx.x < n) { C_r[idx] = A_r[idx] * B_r[idx] - A_c[idx] * B_c[idx]; C_c[idx] = A_r[idx] * B_c[idx] - A_c[idx] * B_r[idx]; } } //----------------------------------------------------------------------------------------------------- /* Function: MultiplySpectrums Multiply 2 complex matrices Parameters: planes - planes of complex image planes_filter - planes of filter image img_complex - output image */ //----------------------------------------------------------------------------------------------------- void MultiplySpectrums(Mat & planes_r, Mat & planes_c, Mat & planes_filter_r, Mat & planes_filter_c, Mat & img_complex) { vector<float> A_r = ConvertMat2Vector(planes_r); vector<float> A_c = ConvertMat2Vector(planes_c); vector<float> B_r = ConvertMat2Vector(planes_filter_r); vector<float> B_c = ConvertMat2Vector(planes_filter_c); // Init int m, n; float *h_A_r, *h_B_r, *h_C_r; float *h_A_c, *h_B_c, *h_C_c; float *d_A_r, *d_B_r, *d_C_r; float *d_A_c, *d_B_c, *d_C_c; size_t size; // Size of image m = planes_r.rows; n = planes_r.cols; size = m*n * sizeof(float); // Allocate host memory h_A_r = (float*)malloc(size); h_B_r = (float*)malloc(size); h_C_r = (float*)malloc(size); h_A_c = (float*)malloc(size); h_B_c = (float*)malloc(size); h_C_c = (float*)malloc(size); // Start clocking for copying data int start_s = clock(); // Transfer data to host var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { h_A_r[j*n + k] = planes_r.at<float>(j, k); h_B_r[j*n + k] = planes_filter_r.at<float>(j, k); h_A_c[j*n + k] = planes_c.at<float>(j, k); h_B_c[j*n + k] = planes_filter_c.at<float>(j, k); } // Stop cloking for copying data int stop_s = clock(); // Allocate matrices in device memory cudaMalloc(&d_A_r, size); cudaMalloc(&d_B_r, size); cudaMalloc(&d_C_r, size); cudaMalloc(&d_A_c, size); cudaMalloc(&d_B_c, size); cudaMalloc(&d_C_c, size); // Copy matrices from host memory to device memory cudaMemcpy(d_A_r, h_A_r, size, cudaMemcpyHostToDevice); cudaMemcpy(d_B_r, h_B_r, size, cudaMemcpyHostToDevice); cudaMemcpy(d_A_c, h_A_c, size, cudaMemcpyHostToDevice); cudaMemcpy(d_B_c, h_B_c, size, cudaMemcpyHostToDevice); // Kernel matrix add MatMulPixelwiseWithoutSharedMemory << <MATRIXWIDTH, MATRIXWIDTH >> > (d_A_r, d_A_c, d_B_r, d_B_c, d_C_r, d_C_c, m, n); // Wait for the kernel to complete cudaThreadSynchronize(); // Copy result from device memory to host memory cudaMemcpy(h_C_r, d_C_r, size, cudaMemcpyDeviceToHost); cudaMemcpy(h_C_c, d_C_c, size, cudaMemcpyDeviceToHost); // Declare block vars Mat plane_temp[2]; Mat m_A_r_temp = Mat::zeros(img_complex.size(), CV_32F); Mat m_A_c_temp = Mat::zeros(img_complex.size(), CV_32F); // Copy result from host memory to local var for (int j = 0; j < m; j++) for (int k = 0; k < n; k++) { m_A_r_temp.at<float>(j, k) = h_C_r[j*n + k]; m_A_c_temp.at<float>(j, k) = h_C_c[j*n + k]; } plane_temp[0] = m_A_r_temp; plane_temp[1] = m_A_c_temp; merge(plane_temp, 2, img_complex); // Free host memory free(h_A_r); free(h_B_r); free(h_C_r); free(h_A_c); free(h_B_c); free(h_C_c); // Free device memory cudaFree(d_A_r); cudaFree(d_B_r); cudaFree(d_C_r); cudaFree(d_A_c); cudaFree(d_B_c); cudaFree(d_C_c); } //----------------------------------------------------------------------------------------------------- /* Function: ApplyFilterCuda Apply filter to sinogram using cuda when multiplying 2 complex matrices Parameters: im_in - input image filter_method - filter method im_out - output image */ //----------------------------------------------------------------------------------------------------- void ApplyFilterCuda(Mat & im_in, string filter_method, Mat & im_out) { // Init images objects Mat img_gray, img_output, img_output_display; Mat img_padded; Mat img_complex, filter; Mat planes[2], planes_filter[2], img_magnitude; // Fourier image size int N, M; // String constant for image title const string originalName = "Input Image (grayscale)"; // window name const string spectrumMagName = "Magnitude Image (log transformed)"; // window name const string lowPassName = "Ramp Filtered (grayscale)"; // window name const string filterName = "Filter Image"; // window nam // setup the DFT image sizes M = getOptimalDFTSize(im_in.rows); N = getOptimalDFTSize(im_in.cols); // convert input to grayscale if RGB if (im_in.channels() == 3) cvtColor(im_in, img_gray, CV_BGR2GRAY); else img_gray = im_in.clone(); // setup the DFT images copyMakeBorder(img_gray, img_padded, 0, M - img_gray.rows, 0, N - img_gray.cols, BORDER_CONSTANT, Scalar::all(0)); planes[0] = Mat_<float>(img_padded); planes[1] = Mat::zeros(img_padded.size(), CV_32F); merge(planes, 2, img_complex); // do the DFT dft(img_complex, img_complex); // construct the filter (same size as complex image) Mat ramp_filter, hann_filter; filter = img_complex.clone(); ramp_filter = filter.clone(); hann_filter = filter.clone(); CreateRampFilter(ramp_filter, 1.0); CreateHannFilter(hann_filter, 1.0); // select filter to apply filter = ramp_filter.clone(); // apply filter ShiftDftToCenter(img_complex); // HERE! WE CAN PARALLELIZE THE MULTIPLICATION OF 2 COMPLEX MATRICES split(img_complex, planes); split(filter, planes_filter); mulSpectrums(img_complex, filter, img_complex, 1); // shift dft to the center ShiftDftToCenter(img_complex); // create magnitude spectrum for display img_magnitude = CreateDisplaySpectrum(img_complex, true); // do inverse DFT on filtered image idft(img_complex, img_complex); // split into planes and extract plane 0 as output image split(img_complex, planes); cv::normalize(planes[0], img_output, 0, 1, CV_MINMAX); // do the same with the filter image split(filter, planes); cv::normalize(planes[0], img_output_display, 0, 1, CV_MINMAX); // save image output im_out = img_output.clone(); // show result Mat rgb = im_in.clone(); cv::normalize(rgb, rgb, 0, 1, cv::NORM_MINMAX); cv::imshow(spectrumMagName, img_magnitude); cv::imshow(lowPassName, img_output); cv::imshow(filterName, img_output_display); // Write result Mat img8bit; img_output_display.convertTo(img8bit, CV_8UC1, 255.0); imwrite( "filtered_sinogram.jpg", img8bit); }
3ad797cfce82fad9dff0307f7e2fc953577462a7.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 @author Mark Gates @author Azzam Haidar @author Ichitaro Yamazaki @generated from magmablas/zlacpy_sym_in.cu, normal z -> s, Wed Jan 2 14:18:50 2019 */ #include "magma_internal.h" #define BLK_X 64 #define BLK_Y 32 /******************************************************************************/ /* Divides matrix into ceil( m/BLK_X ) x ceil( n/BLK_Y ) blocks. Each block has BLK_X threads. Each thread loops across one row, updating BLK_Y entries. Code similar to slaset, slacpy, slag2d, clag2z, sgeadd. */ static __device__ void slacpy_sym_in_full_device( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { int ind = blockIdx.x*BLK_X + threadIdx.x; int iby = blockIdx.y*BLK_Y; /* check if full block-column */ bool full = (iby + BLK_Y <= n); /* do only rows inside matrix */ if ( ind < m ) { dA += ind + iby*ldda; dB += ind + iby*lddb; if ( full ) { // full block-column #pragma unroll for( int j=0; j < BLK_Y; ++j ) { dB[j*lddb] = dA[j*ldda]; } } else { // partial block-column for( int j=0; j < BLK_Y && iby+j < n; ++j ) { dB[j*lddb] = dA[j*ldda]; } } } } /******************************************************************************/ /* Similar to slacpy_full, but updates only the diagonal and below. Blocks that are fully above the diagonal exit immediately. Code similar to slaset, slacpy, zlat2c, clat2z. */ static __device__ void slacpy_sym_in_lower_device( int m, int n, magma_int_t *rows, magma_int_t *perm, const float *dA, int ldda, float *dB, int lddb ) { int ind = blockIdx.x*BLK_X + threadIdx.x; // row int iby = blockIdx.y*BLK_Y; // col /* check if full block-column && (below diag) */ bool full = (iby + BLK_Y <= n); for (int jj=0; jj < n; jj++) { perm[rows[2*jj+1]] = rows[2*jj]; } /* do only rows inside matrix, and blocks not above diag */ if ( ind < m ) { if ( full ) { // full block-column, off-diagonal block //#pragma unroll for( int jj=0; jj < BLK_Y; ++jj ) { int j = rows[2*(iby+jj)]; if (perm[ind] <= j) dB[ind + (iby+jj)*lddb] = MAGMA_S_CONJ( dA[j + perm[ind]*ldda] ); else dB[ind + (iby+jj)*lddb] = dA[perm[ind] + j*ldda]; } } else { // either partial block-column or diagonal block for( int jj=0; jj < BLK_Y && iby+jj < n; ++jj ) { int j = rows[2*(iby+jj)]; if (perm[ind] <= j) dB[ind + (iby+jj)*lddb] = MAGMA_S_CONJ( dA[j + perm[ind]*ldda] ); else dB[ind + (iby+jj)*lddb] = dA[perm[ind] + j*ldda]; } } } } /* Similar to slacpy_full, but updates only the diagonal and above. Blocks that are fully below the diagonal exit immediately. Code similar to slaset, slacpy, zlat2c, clat2z. */ static __device__ void slacpy_sym_in_upper_device( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { int ind = blockIdx.x*BLK_X + threadIdx.x; int iby = blockIdx.y*BLK_Y; /* check if full block-column && (above diag) */ bool full = (iby + BLK_Y <= n && (ind + BLK_X <= iby)); /* do only rows inside matrix, and blocks not below diag */ if ( ind < m && ind < iby + BLK_Y ) { dA += ind + iby*ldda; dB += ind + iby*lddb; if ( full ) { // full block-column, off-diagonal block #pragma unroll for( int j=0; j < BLK_Y; ++j ) { dB[j*lddb] = dA[j*ldda]; } } else { // either partial block-column or diagonal block for( int j=0; j < BLK_Y && iby+j < n; ++j ) { if ( ind <= iby+j ) { dB[j*lddb] = dA[j*ldda]; } } } } } /******************************************************************************/ /* kernel wrappers to call the device functions. */ __global__ void slacpy_sym_in_full_kernel( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { slacpy_sym_in_full_device(m, n, dA, ldda, dB, lddb); } __global__ void slacpy_sym_in_lower_kernel( int m, int n, magma_int_t *rows, magma_int_t *perm, const float *dA, int ldda, float *dB, int lddb ) { slacpy_sym_in_lower_device(m, n, rows, perm, dA, ldda, dB, lddb); } __global__ void slacpy_sym_in_upper_kernel( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { slacpy_sym_in_upper_device(m, n, dA, ldda, dB, lddb); } /***************************************************************************//** Purpose ------- SLACPY_SYM_IN copies all or part of a two-dimensional matrix dA to another matrix dB. This is the same as SLACPY, but adds queue argument. Arguments --------- @param[in] uplo magma_uplo_t Specifies the part of the matrix dA to be copied to dB. - = MagmaUpper: Upper triangular part - = MagmaLower: Lower triangular part - = MagmaFull: All of the matrix dA @param[in] m INTEGER The number of rows of the matrix dA. M >= 0. @param[in] n INTEGER The number of rows that are swapped. N >= 0. @param[in] rows INTEGER array, on GPU, dimension (2*n) On entry, it stores the new pivots such that rows[i]-th and rows[n+i]-th rows are swapped. @param[in,out] perm INTEGER array, on GPU, dimension (m) On entry, it stores the identity permutation array. On exit, it is updated with the new pivots given by rows such that i-th row will be the original perm[i]-th row after the pivots are applied. @param[in] dA REAL array, dimension (LDDA,N) The M-by-N matrix dA. If UPLO = MagmaUpper, only the upper triangle or trapezoid is accessed; if UPLO = MagmaLower, only the lower triangle or trapezoid is accessed. @param[in] ldda INTEGER The leading dimension of the array dA. LDDA >= max(1,M). @param[out] dB REAL array, dimension (LDDB,N) On exit, dB = stores the columns after the pivots are applied. @param[in] lddb INTEGER The leading dimension of the array dB. LDDB >= max(1,M). @param[in] queue magma_queue_t Queue to execute in. @ingroup magma_lacpy *******************************************************************************/ extern "C" void magmablas_slacpy_sym_in( magma_uplo_t uplo, magma_int_t m, magma_int_t n, magma_int_t *rows, magma_int_t *perm, magmaFloat_const_ptr dA, magma_int_t ldda, magmaFloat_ptr dB, magma_int_t lddb, magma_queue_t queue ) { magma_int_t info = 0; if ( uplo != MagmaLower && uplo != MagmaUpper && uplo != MagmaFull ) info = -1; else if ( m < 0 ) info = -2; else if ( n < 0 ) info = -3; else if ( ldda < max(1,m)) info = -5; else if ( lddb < max(1,m)) info = -7; if ( info != 0 ) { magma_xerbla( __func__, -(info) ); return; //info; } if ( m == 0 || n == 0 ) { return; } dim3 threads( BLK_X, 1 ); dim3 grid( magma_ceildiv(m, BLK_X), magma_ceildiv(n, BLK_Y) ); if ( uplo == MagmaLower ) { hipLaunchKernelGGL(( slacpy_sym_in_lower_kernel), dim3(grid), dim3(threads), 0, queue->cuda_stream() , m, n, rows, perm, dA, ldda, dB, lddb ); } else if ( uplo == MagmaUpper ) { hipLaunchKernelGGL(( slacpy_sym_in_upper_kernel), dim3(grid), dim3(threads), 0, queue->cuda_stream() , m, n, dA, ldda, dB, lddb ); } else { hipLaunchKernelGGL(( slacpy_sym_in_full_kernel) , dim3(grid), dim3(threads), 0, queue->cuda_stream() , m, n, dA, ldda, dB, lddb ); } }
3ad797cfce82fad9dff0307f7e2fc953577462a7.cu
/* -- MAGMA (version 2.5.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2019 @author Mark Gates @author Azzam Haidar @author Ichitaro Yamazaki @generated from magmablas/zlacpy_sym_in.cu, normal z -> s, Wed Jan 2 14:18:50 2019 */ #include "magma_internal.h" #define BLK_X 64 #define BLK_Y 32 /******************************************************************************/ /* Divides matrix into ceil( m/BLK_X ) x ceil( n/BLK_Y ) blocks. Each block has BLK_X threads. Each thread loops across one row, updating BLK_Y entries. Code similar to slaset, slacpy, slag2d, clag2z, sgeadd. */ static __device__ void slacpy_sym_in_full_device( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { int ind = blockIdx.x*BLK_X + threadIdx.x; int iby = blockIdx.y*BLK_Y; /* check if full block-column */ bool full = (iby + BLK_Y <= n); /* do only rows inside matrix */ if ( ind < m ) { dA += ind + iby*ldda; dB += ind + iby*lddb; if ( full ) { // full block-column #pragma unroll for( int j=0; j < BLK_Y; ++j ) { dB[j*lddb] = dA[j*ldda]; } } else { // partial block-column for( int j=0; j < BLK_Y && iby+j < n; ++j ) { dB[j*lddb] = dA[j*ldda]; } } } } /******************************************************************************/ /* Similar to slacpy_full, but updates only the diagonal and below. Blocks that are fully above the diagonal exit immediately. Code similar to slaset, slacpy, zlat2c, clat2z. */ static __device__ void slacpy_sym_in_lower_device( int m, int n, magma_int_t *rows, magma_int_t *perm, const float *dA, int ldda, float *dB, int lddb ) { int ind = blockIdx.x*BLK_X + threadIdx.x; // row int iby = blockIdx.y*BLK_Y; // col /* check if full block-column && (below diag) */ bool full = (iby + BLK_Y <= n); for (int jj=0; jj < n; jj++) { perm[rows[2*jj+1]] = rows[2*jj]; } /* do only rows inside matrix, and blocks not above diag */ if ( ind < m ) { if ( full ) { // full block-column, off-diagonal block //#pragma unroll for( int jj=0; jj < BLK_Y; ++jj ) { int j = rows[2*(iby+jj)]; if (perm[ind] <= j) dB[ind + (iby+jj)*lddb] = MAGMA_S_CONJ( dA[j + perm[ind]*ldda] ); else dB[ind + (iby+jj)*lddb] = dA[perm[ind] + j*ldda]; } } else { // either partial block-column or diagonal block for( int jj=0; jj < BLK_Y && iby+jj < n; ++jj ) { int j = rows[2*(iby+jj)]; if (perm[ind] <= j) dB[ind + (iby+jj)*lddb] = MAGMA_S_CONJ( dA[j + perm[ind]*ldda] ); else dB[ind + (iby+jj)*lddb] = dA[perm[ind] + j*ldda]; } } } } /* Similar to slacpy_full, but updates only the diagonal and above. Blocks that are fully below the diagonal exit immediately. Code similar to slaset, slacpy, zlat2c, clat2z. */ static __device__ void slacpy_sym_in_upper_device( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { int ind = blockIdx.x*BLK_X + threadIdx.x; int iby = blockIdx.y*BLK_Y; /* check if full block-column && (above diag) */ bool full = (iby + BLK_Y <= n && (ind + BLK_X <= iby)); /* do only rows inside matrix, and blocks not below diag */ if ( ind < m && ind < iby + BLK_Y ) { dA += ind + iby*ldda; dB += ind + iby*lddb; if ( full ) { // full block-column, off-diagonal block #pragma unroll for( int j=0; j < BLK_Y; ++j ) { dB[j*lddb] = dA[j*ldda]; } } else { // either partial block-column or diagonal block for( int j=0; j < BLK_Y && iby+j < n; ++j ) { if ( ind <= iby+j ) { dB[j*lddb] = dA[j*ldda]; } } } } } /******************************************************************************/ /* kernel wrappers to call the device functions. */ __global__ void slacpy_sym_in_full_kernel( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { slacpy_sym_in_full_device(m, n, dA, ldda, dB, lddb); } __global__ void slacpy_sym_in_lower_kernel( int m, int n, magma_int_t *rows, magma_int_t *perm, const float *dA, int ldda, float *dB, int lddb ) { slacpy_sym_in_lower_device(m, n, rows, perm, dA, ldda, dB, lddb); } __global__ void slacpy_sym_in_upper_kernel( int m, int n, const float *dA, int ldda, float *dB, int lddb ) { slacpy_sym_in_upper_device(m, n, dA, ldda, dB, lddb); } /***************************************************************************//** Purpose ------- SLACPY_SYM_IN copies all or part of a two-dimensional matrix dA to another matrix dB. This is the same as SLACPY, but adds queue argument. Arguments --------- @param[in] uplo magma_uplo_t Specifies the part of the matrix dA to be copied to dB. - = MagmaUpper: Upper triangular part - = MagmaLower: Lower triangular part - = MagmaFull: All of the matrix dA @param[in] m INTEGER The number of rows of the matrix dA. M >= 0. @param[in] n INTEGER The number of rows that are swapped. N >= 0. @param[in] rows INTEGER array, on GPU, dimension (2*n) On entry, it stores the new pivots such that rows[i]-th and rows[n+i]-th rows are swapped. @param[in,out] perm INTEGER array, on GPU, dimension (m) On entry, it stores the identity permutation array. On exit, it is updated with the new pivots given by rows such that i-th row will be the original perm[i]-th row after the pivots are applied. @param[in] dA REAL array, dimension (LDDA,N) The M-by-N matrix dA. If UPLO = MagmaUpper, only the upper triangle or trapezoid is accessed; if UPLO = MagmaLower, only the lower triangle or trapezoid is accessed. @param[in] ldda INTEGER The leading dimension of the array dA. LDDA >= max(1,M). @param[out] dB REAL array, dimension (LDDB,N) On exit, dB = stores the columns after the pivots are applied. @param[in] lddb INTEGER The leading dimension of the array dB. LDDB >= max(1,M). @param[in] queue magma_queue_t Queue to execute in. @ingroup magma_lacpy *******************************************************************************/ extern "C" void magmablas_slacpy_sym_in( magma_uplo_t uplo, magma_int_t m, magma_int_t n, magma_int_t *rows, magma_int_t *perm, magmaFloat_const_ptr dA, magma_int_t ldda, magmaFloat_ptr dB, magma_int_t lddb, magma_queue_t queue ) { magma_int_t info = 0; if ( uplo != MagmaLower && uplo != MagmaUpper && uplo != MagmaFull ) info = -1; else if ( m < 0 ) info = -2; else if ( n < 0 ) info = -3; else if ( ldda < max(1,m)) info = -5; else if ( lddb < max(1,m)) info = -7; if ( info != 0 ) { magma_xerbla( __func__, -(info) ); return; //info; } if ( m == 0 || n == 0 ) { return; } dim3 threads( BLK_X, 1 ); dim3 grid( magma_ceildiv(m, BLK_X), magma_ceildiv(n, BLK_Y) ); if ( uplo == MagmaLower ) { slacpy_sym_in_lower_kernel<<< grid, threads, 0, queue->cuda_stream() >>> ( m, n, rows, perm, dA, ldda, dB, lddb ); } else if ( uplo == MagmaUpper ) { slacpy_sym_in_upper_kernel<<< grid, threads, 0, queue->cuda_stream() >>> ( m, n, dA, ldda, dB, lddb ); } else { slacpy_sym_in_full_kernel <<< grid, threads, 0, queue->cuda_stream() >>> ( m, n, dA, ldda, dB, lddb ); } }
cde7f7fbbeb8fc7112086bb0ccbd32fadc091968.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // Note this file isn't configured to automatically compile #include <hip/device_functions.h> #include <device_launch_parameters.h> // nvcc -arch sm_50 -m 32 -cubin microbench.cu // maxas.pl -e microbench.cubin microbench_new.sass // maxas.pl -i microbench_new.sass microbench.cubin // Use extern C so C++ doesn't mangle our kernel name extern "C" __global__ void microbench(int *out, int *clocks, int *in) { __shared__ int share[1024]; int tid = threadIdx.x; int bx = blockIdx.x; int by = blockIdx.y; //int blkDimX = blockDim.x; //int blkDimY = blockDim.y; //int blkDimZ = blockDim.z; //int grdDimX = gridDim.x; //int grdDimY = gridDim.y; //int grdDimZ = gridDim.z; int start = clock(); share[tid] = in[by * 65535 + bx]; //tid + blkDimX + blkDimY + blkDimZ + grdDimX + grdDimY + grdDimZ __syncthreads(); int end = clock(); clocks[tid] = (start >> 16) | (end & 0xffff0000); //end - start; //out[tid] = share[tid ^ 1]; } // A note about using the Cuda Runtime. // If that's your preference over the driver API then here's what you'd do: // In your project properties in the Cuda C/C++ panel: // -Set the "Keep Processed Files" (-keep) option // -Add a -v manually to the command line // If compiling on command line just add -keep -v options to nvcc. // Rebuild your solution and look in the log for these lines that follow the ptxas step: // #$ fatbinary --create="Release/kernel.fatbin" -32 --key="a7bce87544c2a492" --ident="C:/Users/Scott/Documents/sgemm6/sgemm6/kernel.cu" --cmdline="-v --opt-level 4 --generate-line-info " "--image=profile=sm_50,file=Release/kernel.sm_50.cubin" "--image=profile=compute_50,file=Release/kernel.ptx" --embedded-fatbin="Release/kernel.fatbin.c" --cuda // #$ cl.exe @Release/kernel.cu.cpp.ii.res > "Release/kernel.cu.cpp.ii" // #$ cl.exe @Release/kernel.cu.obj.res -Fo"Release/kernel.cu.obj" // You just need to manually run these 3 commands (or add them to a build script) // after you've modified the cubin generated from the preceeding ptxas command. // That will give you a new .cu.obj file which will automatically be linked in for you next time you // build your project (or you could manually run the linker step as well). // Having done that you can call your kernel normally using the <<< >>> syntax. // Debugging will have to be with the sass syntax but that's what you'll want to see anyway. // With fatbin you can also keep non-maxwell optimized versions of your code. // I just discovered this also works as a shortcut to the above: // nvcc -lib -arch sm_52 -m 32 -use-cubin code=sm_52,cubin=microbench.cubin -o microbench.lib microbench.cu // The cu kernel definitions above need to have empty bodies. // And, the cu file must be compiled to a lib seperately before linking.
cde7f7fbbeb8fc7112086bb0ccbd32fadc091968.cu
// Note this file isn't configured to automatically compile #include <device_functions.h> #include <device_launch_parameters.h> // nvcc -arch sm_50 -m 32 -cubin microbench.cu // maxas.pl -e microbench.cubin microbench_new.sass // maxas.pl -i microbench_new.sass microbench.cubin // Use extern C so C++ doesn't mangle our kernel name extern "C" __global__ void microbench(int *out, int *clocks, int *in) { __shared__ int share[1024]; int tid = threadIdx.x; int bx = blockIdx.x; int by = blockIdx.y; //int blkDimX = blockDim.x; //int blkDimY = blockDim.y; //int blkDimZ = blockDim.z; //int grdDimX = gridDim.x; //int grdDimY = gridDim.y; //int grdDimZ = gridDim.z; int start = clock(); share[tid] = in[by * 65535 + bx]; //tid + blkDimX + blkDimY + blkDimZ + grdDimX + grdDimY + grdDimZ __syncthreads(); int end = clock(); clocks[tid] = (start >> 16) | (end & 0xffff0000); //end - start; //out[tid] = share[tid ^ 1]; } // A note about using the Cuda Runtime. // If that's your preference over the driver API then here's what you'd do: // In your project properties in the Cuda C/C++ panel: // -Set the "Keep Processed Files" (-keep) option // -Add a -v manually to the command line // If compiling on command line just add -keep -v options to nvcc. // Rebuild your solution and look in the log for these lines that follow the ptxas step: // #$ fatbinary --create="Release/kernel.fatbin" -32 --key="a7bce87544c2a492" --ident="C:/Users/Scott/Documents/sgemm6/sgemm6/kernel.cu" --cmdline="-v --opt-level 4 --generate-line-info " "--image=profile=sm_50,file=Release/kernel.sm_50.cubin" "--image=profile=compute_50,file=Release/kernel.ptx" --embedded-fatbin="Release/kernel.fatbin.c" --cuda // #$ cl.exe @Release/kernel.cu.cpp.ii.res > "Release/kernel.cu.cpp.ii" // #$ cl.exe @Release/kernel.cu.obj.res -Fo"Release/kernel.cu.obj" // You just need to manually run these 3 commands (or add them to a build script) // after you've modified the cubin generated from the preceeding ptxas command. // That will give you a new .cu.obj file which will automatically be linked in for you next time you // build your project (or you could manually run the linker step as well). // Having done that you can call your kernel normally using the <<< >>> syntax. // Debugging will have to be with the sass syntax but that's what you'll want to see anyway. // With fatbin you can also keep non-maxwell optimized versions of your code. // I just discovered this also works as a shortcut to the above: // nvcc -lib -arch sm_52 -m 32 -use-cubin code=sm_52,cubin=microbench.cubin -o microbench.lib microbench.cu // The cu kernel definitions above need to have empty bodies. // And, the cu file must be compiled to a lib seperately before linking.
5c788be46db9cc42f00564c89cb014d91c3f721c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* Copyright 2020 The OneFlow Authors. 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. */ #ifdef WITH_CUDA #include <unordered_map> #include "oneflow/core/framework/framework.h" #include "oneflow/core/device/cudnn_util.h" #include "oneflow/core/kernel/new_kernel_util.h" namespace oneflow { namespace { #if (CUDNN_VERSION >= 7401) #define BN_ENABLE_EX_API class CudnnHandleWrapper { public: CudnnHandleWrapper() { OF_CUDNN_CHECK(cudnnCreate(&handle_)); } ~CudnnHandleWrapper() { OF_CUDNN_CHECK(cudnnDestroy(handle_)); } cudnnHandle_t handle() const { return handle_; } private: cudnnHandle_t handle_; }; cudnnHandle_t GetOrCreateCudnnHandle() { static std::unordered_map<int, CudnnHandleWrapper> device_id2handle; int device_id; OF_CUDA_CHECK(hipGetDevice(&device_id)); // operator [] will create and insert a CudnnHandleWrapper // if key `device_id` does not exist return device_id2handle[device_id].handle(); } #endif void InferDimSizeAndDataFormat(const ShapeView& x_shape, const int32_t axis, int32_t* n, int32_t* c, int32_t* h, int32_t* w, cudnnTensorFormat_t* format) { if (x_shape.Count(axis + 1) == 1) { if (axis == 0) { *n = 1; *h = 1; } else { *n = x_shape.At(0); *h = x_shape.Count(1, axis); } *w = 1; *c = x_shape.At(axis); *format = CUDNN_TENSOR_NHWC; } else { *n = x_shape.Count(0, axis); *c = x_shape.At(axis); *h = x_shape.Count(axis + 1); *w = 1; *format = CUDNN_TENSOR_NCHW; } } void InferXYCudnnTensorDesc(const ShapeView& xy_shape, const DataType& data_type, const int32_t axis, cudnnTensorDescriptor_t xy_desc) { int32_t n, c, h, w; cudnnTensorFormat_t format; InferDimSizeAndDataFormat(xy_shape, axis, &n, &c, &h, &w, &format); OF_CUDNN_CHECK( cudnnSetTensor4dDescriptor(xy_desc, format, GetCudnnDataType(data_type), n, c, h, w)); } void InferParamCudnnTensorDesc(const cudnnTensorDescriptor_t xy_desc, cudnnBatchNormMode_t mode, cudnnTensorDescriptor_t param_desc) { OF_CUDNN_CHECK(cudnnDeriveBNTensorDescriptor(param_desc, xy_desc, mode)); } class CudnnTensorDescHelper final { public: OF_DISALLOW_COPY_AND_MOVE(CudnnTensorDescHelper); CudnnTensorDescHelper(const ShapeView& xy_shape, const DataType& data_type, const int32_t axis, cudnnBatchNormMode_t mode) { OF_CUDNN_CHECK(cudnnCreateTensorDescriptor(&xy_desc_)); InferXYCudnnTensorDesc(xy_shape, data_type, axis, xy_desc_); OF_CUDNN_CHECK(cudnnCreateTensorDescriptor(&param_desc_)); InferParamCudnnTensorDesc(xy_desc_, mode, param_desc_); int n, c, h, w, n_stride, c_stride, h_stride, w_stride; OF_CUDNN_CHECK(cudnnGetTensor4dDescriptor(param_desc_, &param_data_type_, &n, &c, &h, &w, &n_stride, &c_stride, &h_stride, &w_stride)); param_size_ = c; } ~CudnnTensorDescHelper() { OF_CUDNN_CHECK(cudnnDestroyTensorDescriptor(param_desc_)); OF_CUDNN_CHECK(cudnnDestroyTensorDescriptor(xy_desc_)); } cudnnTensorDescriptor_t xy_desc() const { return xy_desc_; } cudnnTensorDescriptor_t param_desc() const { return param_desc_; } void CheckParamTensor(const user_op::Tensor* tensor) const { CHECK_EQ(tensor->shape().NumAxes(), 1); CHECK_EQ(tensor->shape().At(0), param_size_); CHECK_EQ(GetCudnnDataType(tensor->data_type()), param_data_type_); } private: cudnnTensorDescriptor_t xy_desc_ = nullptr; cudnnTensorDescriptor_t param_desc_ = nullptr; cudnnDataType_t param_data_type_; int32_t param_size_ = 0; }; size_t InferTrainWorkspaceSize(const ShapeView& x_shape, const DataType data_type, const int32_t axis) { #if defined(BN_ENABLE_EX_API) const CudnnTensorDescHelper desc_helper(x_shape, data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &size_in_bytes)); return ::max(size_in_bytes, static_cast<size_t>(1)); #else return 1; #endif } size_t InferTrainTmpSize(user_op::InferContext* ctx) { const auto& x = ctx->InputTensorDesc("x", 0); const auto axis = ctx->Attr<int32_t>("axis"); return InferTrainWorkspaceSize(x.shape(), x.data_type(), axis); } size_t InferGradWorkspaceSize(const ShapeView& x_shape, const DataType data_type, const int32_t axis) { #if defined(BN_ENABLE_EX_API) const CudnnTensorDescHelper desc_helper(x_shape, data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &size_in_bytes)); return ::max(size_in_bytes, static_cast<size_t>(1)); #else return 1; #endif } size_t InferGradTmpSize(user_op::InferContext* ctx) { const auto& dy = ctx->InputTensorDesc("dy", 0); const auto axis = ctx->Attr<int32_t>("axis"); size_t tmp_size = 0; if (ctx->op_type_name() == "normalization_add_relu_grad" && !ctx->has_output("addend_diff", 0)) { tmp_size += GetCudaAlignedSize(dy.shape().elem_cnt() * GetSizeOfDataType(dy.data_type())); } tmp_size += GetCudaAlignedSize(InferGradWorkspaceSize(dy.shape(), dy.data_type(), axis)); return tmp_size; } template<typename T> class NormalizationInferenceKernel final : public user_op::OpKernel { public: NormalizationInferenceKernel() = default; ~NormalizationInferenceKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const bool training = ctx->Attr<bool>("training"); CHECK(!training); const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* moving_mean = ctx->Tensor4ArgNameAndIndex("moving_mean", 0); auto* moving_variance = ctx->Tensor4ArgNameAndIndex("moving_variance", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const DataType data_type = x->data_type(); CHECK_EQ(x->shape(), y->shape()); CHECK_EQ(y->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(moving_mean); desc_helper.CheckParamTensor(moving_variance); const void* sp_alpha = CudnnSPOnePtr<T>(); const void* sp_beta; if (ctx->has_input("_add_to_output", 0)) { const user_op::Tensor* add_to_output = ctx->Tensor4ArgNameAndIndex("_add_to_output", 0); CHECK_EQ(add_to_output->data_type(), y->data_type()); CHECK_EQ(add_to_output->shape(), y->shape()); Memcpy<DeviceType::kGPU>( ctx->device_ctx(), y->mut_dptr<void>(), add_to_output->dptr<void>(), add_to_output->shape().elem_cnt() * GetSizeOfDataType(add_to_output->data_type())); sp_beta = CudnnSPOnePtr<T>(); } else { sp_beta = CudnnSPZeroPtr<T>(); } OF_CUDNN_CHECK(cudnnBatchNormalizationForwardInference( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), moving_mean->dptr(), moving_variance->dptr(), epsilon)); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_BN_INFERENCE_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization") \ .SetCreateFn<NormalizationInferenceKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value) \ & (user_op::HobAttr<bool>("training") == false)) \ .SetInplaceProposalFn([](const user_op::InferContext& ctx, \ user_op::AddInplaceArgPair AddInplaceArgPairFn) -> Maybe<void> { \ if (ctx.has_input("_add_to_output", 0)) { \ OF_RETURN_IF_ERROR(AddInplaceArgPairFn("y", 0, "_add_to_output", 0, true)); \ } \ return Maybe<void>::Ok(); \ }); REGISTER_BN_INFERENCE_KERNEL(float16) REGISTER_BN_INFERENCE_KERNEL(float) REGISTER_BN_INFERENCE_KERNEL(double) #undef REGISTER_BN_INFERENCE_KERNEL constexpr int64_t kCudaWarpSize = 32; template<typename T> __global__ void ReluGpu(int64_t n, const T* x, T* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; CUDA_1D_KERNEL_LOOP(i, n) { const T x_val = x[i]; const bool is_positive = (x_val > 0); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? x_val : 0; } } template<> __global__ void ReluGpu<half>(int64_t n, const half* x, half* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; const half zero = __float2half(0.0f); CUDA_1D_KERNEL_LOOP(i, n) { const half x_val = x[i]; const bool is_positive = __hgt(x_val, zero); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? x_val : zero; } } template<typename T> __global__ void AddReluGpu(int64_t n, const T* x, const T* addend, T* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; CUDA_1D_KERNEL_LOOP(i, n) { const T sum = x[i] + addend[i]; const bool is_positive = (sum > 0); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? sum : 0; } } template<> __global__ void AddReluGpu<half>(int64_t n, const half* x, const half* addend, half* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; const half zero = __float2half(0.0f); CUDA_1D_KERNEL_LOOP(i, n) { const half sum = __hadd(x[i], addend[i]); const bool is_positive = __hgt(sum, zero); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? sum : zero; } } template<typename T> void Relu(DeviceCtx* device_ctx, int64_t n, const T* x, T* y, int32_t* mask) { hipLaunchKernelGGL(( ReluGpu<T>), dim3(BlocksNum4ThreadsNum(n)), dim3(kCudaThreadsNumPerBlock), 0, device_ctx->cuda_stream(), n, x, y, mask); } template<> void Relu<float16>(DeviceCtx* device_ctx, int64_t n, const float16* x, float16* y, int32_t* mask) { Relu<half>(device_ctx, n, reinterpret_cast<const half*>(x), reinterpret_cast<half*>(y), mask); } template<typename T> void AddRelu(DeviceCtx* device_ctx, int64_t n, const T* x, const T* addend, T* y, int32_t* mask) { hipLaunchKernelGGL(( AddReluGpu<T>), dim3(BlocksNum4ThreadsNum(n)), dim3(kCudaThreadsNumPerBlock), 0, device_ctx->cuda_stream(), n, x, addend, y, mask); } template<> void AddRelu<float16>(DeviceCtx* device_ctx, int64_t n, const float16* x, const float16* addend, float16* y, int32_t* mask) { AddRelu<half>(device_ctx, n, reinterpret_cast<const half*>(x), reinterpret_cast<const half*>(addend), reinterpret_cast<half*>(y), mask); } template<typename T> __global__ void ReluBackwardGpu(int64_t n, const int32_t* mask, const T* dy, T* addend_diff) { int32_t lane_id = threadIdx.x % kCudaWarpSize; CUDA_1D_KERNEL_LOOP(i, n) { int32_t mask_val = mask[i / kCudaWarpSize]; bool is_positive = mask_val & (1 << lane_id); addend_diff[i] = static_cast<T>(is_positive) * dy[i]; } } template<typename T> void ReluBackward(DeviceCtx* device_ctx, int64_t n, const int32_t* mask, const T* dy, T* addend_diff) { hipLaunchKernelGGL(( ReluBackwardGpu<T>) , dim3(BlocksNum4ThreadsNum(n)), dim3(kCudaThreadsNumPerBlock), 0, device_ctx->cuda_stream(), n, mask, dy, addend_diff); } template<> void ReluBackward<float16>(DeviceCtx* device_ctx, int64_t n, const int32_t* mask, const float16* dy, float16* addend_diff) { ReluBackward<half>(device_ctx, n, mask, reinterpret_cast<const half*>(dy), reinterpret_cast<half*>(addend_diff)); } template<typename T> class NormalizationTrainKernel final : public user_op::OpKernel { public: NormalizationTrainKernel() = default; ~NormalizationTrainKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { if (ctx->op_type_name() == "normalization") { CHECK(ctx->Attr<bool>("training")); } const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* moving_mean = ctx->Tensor4ArgNameAndIndex("moving_mean", 0); auto* moving_variance = ctx->Tensor4ArgNameAndIndex("moving_variance", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const auto momentum = ctx->Attr<float>("momentum"); auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); const DataType data_type = x->data_type(); CHECK_EQ(x->shape(), y->shape()); CHECK_EQ(y->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(moving_mean); desc_helper.CheckParamTensor(moving_variance); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); const void* sp_alpha = CudnnSPOnePtr<T>(); const void* sp_beta; if (ctx->has_input("_add_to_output", 0)) { const user_op::Tensor* add_to_output = ctx->Tensor4ArgNameAndIndex("_add_to_output", 0); CHECK_EQ(add_to_output->data_type(), y->data_type()); CHECK_EQ(add_to_output->shape(), y->shape()); Memcpy<DeviceType::kGPU>( ctx->device_ctx(), y->mut_dptr<void>(), add_to_output->dptr<void>(), add_to_output->shape().elem_cnt() * GetSizeOfDataType(add_to_output->data_type())); sp_beta = CudnnSPOnePtr<T>(); } else { sp_beta = CudnnSPZeroPtr<T>(); } #if defined(BN_ENABLE_EX_API) size_t workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &workspace_size)); size_t reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, nullptr, desc_helper.xy_desc(), &reserve_space_size)); auto* workspace = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); if (reserve_space_size == 0 && workspace_size <= workspace->shape().elem_cnt()) { OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTrainingEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), nullptr, nullptr, desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr(), nullptr, workspace->mut_dptr(), workspace->shape().elem_cnt(), nullptr, 0)); } else { OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTraining( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr())); } #else OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTraining( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr())); #endif if (ctx->op_type_name() == "normalization_add_relu") { CHECK(!ctx->has_input("_add_to_output", 0)); const int64_t elem_cnt = x->shape().elem_cnt(); auto* mask = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); if (ctx->has_input("addend", 0)) { const auto* addend = ctx->Tensor4ArgNameAndIndex("addend", 0); AddRelu(ctx->device_ctx(), elem_cnt, y->dptr<T>(), addend->dptr<T>(), y->mut_dptr<T>(), mask->mut_dptr<int32_t>()); } else { Relu(ctx->device_ctx(), elem_cnt, y->dptr<T>(), y->mut_dptr<T>(), mask->mut_dptr<int32_t>()); } } } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_BN_TRAIN_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization") \ .SetCreateFn<NormalizationTrainKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value) \ & (user_op::HobAttr<bool>("training") == true)) \ .SetInferTmpSizeFn(InferTrainTmpSize) \ .SetInplaceProposalFn([](const user_op::InferContext& ctx, \ user_op::AddInplaceArgPair AddInplaceArgPairFn) -> Maybe<void> { \ if (ctx.has_input("_add_to_output", 0)) { \ OF_RETURN_IF_ERROR(AddInplaceArgPairFn("y", 0, "_add_to_output", 0, true)); \ } \ return Maybe<void>::Ok(); \ }); REGISTER_BN_TRAIN_KERNEL(float16) REGISTER_BN_TRAIN_KERNEL(float) REGISTER_BN_TRAIN_KERNEL(double) #define REGISTER_BN_ADD_RELU_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization_add_relu") \ .SetCreateFn<NormalizationTrainKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferTrainTmpSize); REGISTER_BN_ADD_RELU_KERNEL(float16) REGISTER_BN_ADD_RELU_KERNEL(float) REGISTER_BN_ADD_RELU_KERNEL(double) template<typename T> class NormalizationGradUserKernel final : public user_op::OpKernel { public: NormalizationGradUserKernel() = default; ~NormalizationGradUserKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* dx = ctx->Tensor4ArgNameAndIndex("dx", 0); const auto* dy = ctx->Tensor4ArgNameAndIndex("dy", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); auto* gamma_diff = ctx->Tensor4ArgNameAndIndex("gamma_diff", 0); auto* beta_diff = ctx->Tensor4ArgNameAndIndex("beta_diff", 0); const auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); const auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); auto* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const DataType data_type = x->data_type(); CHECK_EQ(dy->shape(), x->shape()); CHECK_EQ(dy->data_type(), data_type); CHECK_EQ(dx->shape(), x->shape()); CHECK_EQ(dx->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(gamma_diff); desc_helper.CheckParamTensor(beta_diff); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); void* bn_workspace_ptr; size_t bn_workspace_size; const void* bn_dy_ptr; if (ctx->op_type_name() == "normalization_grad") { bn_workspace_ptr = tmp_buffer->mut_dptr(); bn_workspace_size = tmp_buffer->shape().elem_cnt(); bn_dy_ptr = dy->dptr(); } else if (ctx->op_type_name() == "normalization_add_relu_grad") { const int64_t elem_cnt = dy->shape().elem_cnt(); const auto* mask = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); user_op::Tensor* y = ctx->Tensor4ArgNameAndIndex("y", 0); if (ctx->has_output("addend_diff", 0)) { user_op::Tensor* addend_diff = ctx->Tensor4ArgNameAndIndex("addend_diff", 0); ReluBackward(ctx->device_ctx(), elem_cnt, mask->dptr<int32_t>(), dy->dptr<T>(), addend_diff->mut_dptr<T>()); bn_workspace_ptr = tmp_buffer->mut_dptr(); bn_workspace_size = tmp_buffer->shape().elem_cnt(); bn_dy_ptr = addend_diff->dptr(); } else { const size_t tmp_buffer_size = tmp_buffer->shape().elem_cnt(); const size_t relu_dx_size = GetCudaAlignedSize(dy->shape().elem_cnt() * GetSizeOfDataType(dy->data_type())); CHECK_GE(tmp_buffer_size, relu_dx_size); ReluBackward(ctx->device_ctx(), elem_cnt, mask->dptr<int32_t>(), dy->dptr<T>(), reinterpret_cast<T*>(tmp_buffer->mut_dptr())); bn_workspace_ptr = tmp_buffer->mut_dptr<char>() + relu_dx_size; bn_workspace_size = tmp_buffer_size - relu_dx_size; bn_dy_ptr = tmp_buffer->dptr(); } } else { UNIMPLEMENTED(); } #if defined(BN_ENABLE_EX_API) size_t workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &workspace_size)); size_t reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, nullptr, desc_helper.xy_desc(), &reserve_space_size)); if (reserve_space_size == 0 && workspace_size <= bn_workspace_size) { OF_CUDNN_CHECK(cudnnBatchNormalizationBackwardEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), nullptr, nullptr, desc_helper.xy_desc(), bn_dy_ptr, nullptr, nullptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), nullptr, gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr(), nullptr, bn_workspace_ptr, bn_workspace_size, nullptr, 0)); } else { OF_CUDNN_CHECK(cudnnBatchNormalizationBackward( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), bn_dy_ptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr())); } #else OF_CUDNN_CHECK(cudnnBatchNormalizationBackward( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), bn_dy_ptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr())); #endif } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_BN_GRAD_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization_grad") \ .SetCreateFn<NormalizationGradUserKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("dx", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferGradTmpSize); REGISTER_BN_GRAD_KERNEL(float16) REGISTER_BN_GRAD_KERNEL(float) REGISTER_BN_GRAD_KERNEL(double) #define REGISTER_BN_ADD_RELU_GRAD_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization_add_relu_grad") \ .SetCreateFn<NormalizationGradUserKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("dx", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferGradTmpSize); REGISTER_BN_ADD_RELU_GRAD_KERNEL(float16) REGISTER_BN_ADD_RELU_GRAD_KERNEL(float) REGISTER_BN_ADD_RELU_GRAD_KERNEL(double) #if (CUDNN_VERSION >= 7401) size_t InferFusedNormalizationAddReluTmpSize(user_op::InferContext* ctx) { const auto& x = ctx->InputTensorDesc("x", 0); const auto axis = ctx->Attr<int32_t>("axis"); const CudnnTensorDescHelper desc_helper(x.shape(), x.data_type(), axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnBatchNormOps_t ops; cudnnTensorDescriptor_t z_desc; if (ctx->has_input("addend", 0)) { ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; z_desc = desc_helper.xy_desc(); } else { ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; z_desc = nullptr; } OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), z_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &size_in_bytes)); return ::max(size_in_bytes, static_cast<size_t>(1)); } size_t InferFusedNormalizationAddReluGradTmpSize(user_op::InferContext* ctx) { const auto& x = ctx->InputTensorDesc("x", 0); const auto axis = ctx->Attr<int32_t>("axis"); const CudnnTensorDescHelper desc_helper(x.shape(), x.data_type(), axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnBatchNormOps_t ops; cudnnTensorDescriptor_t z_desc; if (ctx->has_output("addend_diff", 0)) { ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; z_desc = desc_helper.xy_desc(); } else { ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; z_desc = nullptr; } OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), desc_helper.xy_desc(), desc_helper.xy_desc(), z_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &size_in_bytes)); return ::max(size_in_bytes, static_cast<size_t>(1)); } template<typename T> class FusedNormalizationAddReluKernel final : public user_op::OpKernel { public: FusedNormalizationAddReluKernel() = default; ~FusedNormalizationAddReluKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* moving_mean = ctx->Tensor4ArgNameAndIndex("moving_mean", 0); auto* moving_variance = ctx->Tensor4ArgNameAndIndex("moving_variance", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const auto momentum = ctx->Attr<float>("momentum"); auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); auto* reserve_space = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); auto* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); const DataType data_type = x->data_type(); CHECK_EQ(x->shape(), y->shape()); CHECK_EQ(y->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(moving_mean); desc_helper.CheckParamTensor(moving_variance); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnTensorDescriptor_t z_desc; const void* z_ptr; cudnnBatchNormOps_t ops; if (ctx->has_input("addend", 0)) { z_desc = desc_helper.xy_desc(); z_ptr = ctx->Tensor4ArgNameAndIndex("addend", 0)->dptr(); ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; } else { z_desc = nullptr; z_ptr = nullptr; ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; } size_t min_workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), z_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &min_workspace_size)); const size_t workspace_size = tmp_buffer->shape().elem_cnt(); CHECK_GE(workspace_size, min_workspace_size); size_t min_reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, activation_desc.Get(), desc_helper.xy_desc(), &min_reserve_space_size)); const size_t reserve_space_size = reserve_space->shape().elem_cnt(); CHECK_GE(reserve_space_size, min_reserve_space_size); OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTrainingEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), z_desc, z_ptr, desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr(), activation_desc.Get(), tmp_buffer->mut_dptr(), workspace_size, reserve_space->mut_dptr(), reserve_space_size)); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_FUSED_BN_ADD_RELU_KERNEL(dtype) \ REGISTER_USER_KERNEL("cudnn_fused_normalization_add_relu") \ .SetCreateFn<FusedNormalizationAddReluKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferFusedNormalizationAddReluTmpSize); REGISTER_FUSED_BN_ADD_RELU_KERNEL(float16) template<typename T> class FusedNormalizationAddReluGradUserKernel final : public user_op::OpKernel { public: FusedNormalizationAddReluGradUserKernel() = default; ~FusedNormalizationAddReluGradUserKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); const auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); auto* dx = ctx->Tensor4ArgNameAndIndex("dx", 0); const auto* dy = ctx->Tensor4ArgNameAndIndex("dy", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* gamma_diff = ctx->Tensor4ArgNameAndIndex("gamma_diff", 0); auto* beta_diff = ctx->Tensor4ArgNameAndIndex("beta_diff", 0); const auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); const auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); const auto* reserve_space = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); auto* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const DataType data_type = x->data_type(); CHECK_EQ(dy->shape(), x->shape()); CHECK_EQ(dy->data_type(), data_type); CHECK_EQ(dx->shape(), x->shape()); CHECK_EQ(dx->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(gamma_diff); desc_helper.CheckParamTensor(beta_diff); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnTensorDescriptor_t dz_desc; void* dz_ptr; cudnnBatchNormOps_t ops; if (ctx->has_output("addend_diff", 0)) { dz_desc = desc_helper.xy_desc(); dz_ptr = ctx->Tensor4ArgNameAndIndex("addend_diff", 0)->mut_dptr(); ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; } else { dz_desc = nullptr; dz_ptr = nullptr; ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; } size_t min_workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), desc_helper.xy_desc(), desc_helper.xy_desc(), dz_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &min_workspace_size)); const size_t workspace_size = tmp_buffer->shape().elem_cnt(); CHECK_GE(workspace_size, min_workspace_size); size_t min_reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, activation_desc.Get(), desc_helper.xy_desc(), &min_reserve_space_size)); const size_t reserve_space_size = reserve_space->shape().elem_cnt(); CHECK_GE(reserve_space_size, min_reserve_space_size); OF_CUDNN_CHECK(cudnnBatchNormalizationBackwardEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->dptr(), desc_helper.xy_desc(), dy->dptr(), dz_desc, dz_ptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr(), activation_desc.Get(), tmp_buffer->mut_dptr(), workspace_size, const_cast<void*>(reserve_space->dptr()), reserve_space_size)); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_FUSED_BN_ADD_RELU_GRAD_KERNEL(dtype) \ REGISTER_USER_KERNEL("cudnn_fused_normalization_add_relu_grad") \ .SetCreateFn<FusedNormalizationAddReluGradUserKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("dx", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferFusedNormalizationAddReluGradTmpSize); REGISTER_FUSED_BN_ADD_RELU_GRAD_KERNEL(float16) #endif } // namespace } // namespace oneflow #endif
5c788be46db9cc42f00564c89cb014d91c3f721c.cu
/* Copyright 2020 The OneFlow Authors. 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. */ #ifdef WITH_CUDA #include <unordered_map> #include "oneflow/core/framework/framework.h" #include "oneflow/core/device/cudnn_util.h" #include "oneflow/core/kernel/new_kernel_util.h" namespace oneflow { namespace { #if (CUDNN_VERSION >= 7401) #define BN_ENABLE_EX_API class CudnnHandleWrapper { public: CudnnHandleWrapper() { OF_CUDNN_CHECK(cudnnCreate(&handle_)); } ~CudnnHandleWrapper() { OF_CUDNN_CHECK(cudnnDestroy(handle_)); } cudnnHandle_t handle() const { return handle_; } private: cudnnHandle_t handle_; }; cudnnHandle_t GetOrCreateCudnnHandle() { static std::unordered_map<int, CudnnHandleWrapper> device_id2handle; int device_id; OF_CUDA_CHECK(cudaGetDevice(&device_id)); // operator [] will create and insert a CudnnHandleWrapper // if key `device_id` does not exist return device_id2handle[device_id].handle(); } #endif void InferDimSizeAndDataFormat(const ShapeView& x_shape, const int32_t axis, int32_t* n, int32_t* c, int32_t* h, int32_t* w, cudnnTensorFormat_t* format) { if (x_shape.Count(axis + 1) == 1) { if (axis == 0) { *n = 1; *h = 1; } else { *n = x_shape.At(0); *h = x_shape.Count(1, axis); } *w = 1; *c = x_shape.At(axis); *format = CUDNN_TENSOR_NHWC; } else { *n = x_shape.Count(0, axis); *c = x_shape.At(axis); *h = x_shape.Count(axis + 1); *w = 1; *format = CUDNN_TENSOR_NCHW; } } void InferXYCudnnTensorDesc(const ShapeView& xy_shape, const DataType& data_type, const int32_t axis, cudnnTensorDescriptor_t xy_desc) { int32_t n, c, h, w; cudnnTensorFormat_t format; InferDimSizeAndDataFormat(xy_shape, axis, &n, &c, &h, &w, &format); OF_CUDNN_CHECK( cudnnSetTensor4dDescriptor(xy_desc, format, GetCudnnDataType(data_type), n, c, h, w)); } void InferParamCudnnTensorDesc(const cudnnTensorDescriptor_t xy_desc, cudnnBatchNormMode_t mode, cudnnTensorDescriptor_t param_desc) { OF_CUDNN_CHECK(cudnnDeriveBNTensorDescriptor(param_desc, xy_desc, mode)); } class CudnnTensorDescHelper final { public: OF_DISALLOW_COPY_AND_MOVE(CudnnTensorDescHelper); CudnnTensorDescHelper(const ShapeView& xy_shape, const DataType& data_type, const int32_t axis, cudnnBatchNormMode_t mode) { OF_CUDNN_CHECK(cudnnCreateTensorDescriptor(&xy_desc_)); InferXYCudnnTensorDesc(xy_shape, data_type, axis, xy_desc_); OF_CUDNN_CHECK(cudnnCreateTensorDescriptor(&param_desc_)); InferParamCudnnTensorDesc(xy_desc_, mode, param_desc_); int n, c, h, w, n_stride, c_stride, h_stride, w_stride; OF_CUDNN_CHECK(cudnnGetTensor4dDescriptor(param_desc_, &param_data_type_, &n, &c, &h, &w, &n_stride, &c_stride, &h_stride, &w_stride)); param_size_ = c; } ~CudnnTensorDescHelper() { OF_CUDNN_CHECK(cudnnDestroyTensorDescriptor(param_desc_)); OF_CUDNN_CHECK(cudnnDestroyTensorDescriptor(xy_desc_)); } cudnnTensorDescriptor_t xy_desc() const { return xy_desc_; } cudnnTensorDescriptor_t param_desc() const { return param_desc_; } void CheckParamTensor(const user_op::Tensor* tensor) const { CHECK_EQ(tensor->shape().NumAxes(), 1); CHECK_EQ(tensor->shape().At(0), param_size_); CHECK_EQ(GetCudnnDataType(tensor->data_type()), param_data_type_); } private: cudnnTensorDescriptor_t xy_desc_ = nullptr; cudnnTensorDescriptor_t param_desc_ = nullptr; cudnnDataType_t param_data_type_; int32_t param_size_ = 0; }; size_t InferTrainWorkspaceSize(const ShapeView& x_shape, const DataType data_type, const int32_t axis) { #if defined(BN_ENABLE_EX_API) const CudnnTensorDescHelper desc_helper(x_shape, data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &size_in_bytes)); return std::max(size_in_bytes, static_cast<size_t>(1)); #else return 1; #endif } size_t InferTrainTmpSize(user_op::InferContext* ctx) { const auto& x = ctx->InputTensorDesc("x", 0); const auto axis = ctx->Attr<int32_t>("axis"); return InferTrainWorkspaceSize(x.shape(), x.data_type(), axis); } size_t InferGradWorkspaceSize(const ShapeView& x_shape, const DataType data_type, const int32_t axis) { #if defined(BN_ENABLE_EX_API) const CudnnTensorDescHelper desc_helper(x_shape, data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &size_in_bytes)); return std::max(size_in_bytes, static_cast<size_t>(1)); #else return 1; #endif } size_t InferGradTmpSize(user_op::InferContext* ctx) { const auto& dy = ctx->InputTensorDesc("dy", 0); const auto axis = ctx->Attr<int32_t>("axis"); size_t tmp_size = 0; if (ctx->op_type_name() == "normalization_add_relu_grad" && !ctx->has_output("addend_diff", 0)) { tmp_size += GetCudaAlignedSize(dy.shape().elem_cnt() * GetSizeOfDataType(dy.data_type())); } tmp_size += GetCudaAlignedSize(InferGradWorkspaceSize(dy.shape(), dy.data_type(), axis)); return tmp_size; } template<typename T> class NormalizationInferenceKernel final : public user_op::OpKernel { public: NormalizationInferenceKernel() = default; ~NormalizationInferenceKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const bool training = ctx->Attr<bool>("training"); CHECK(!training); const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* moving_mean = ctx->Tensor4ArgNameAndIndex("moving_mean", 0); auto* moving_variance = ctx->Tensor4ArgNameAndIndex("moving_variance", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const DataType data_type = x->data_type(); CHECK_EQ(x->shape(), y->shape()); CHECK_EQ(y->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(moving_mean); desc_helper.CheckParamTensor(moving_variance); const void* sp_alpha = CudnnSPOnePtr<T>(); const void* sp_beta; if (ctx->has_input("_add_to_output", 0)) { const user_op::Tensor* add_to_output = ctx->Tensor4ArgNameAndIndex("_add_to_output", 0); CHECK_EQ(add_to_output->data_type(), y->data_type()); CHECK_EQ(add_to_output->shape(), y->shape()); Memcpy<DeviceType::kGPU>( ctx->device_ctx(), y->mut_dptr<void>(), add_to_output->dptr<void>(), add_to_output->shape().elem_cnt() * GetSizeOfDataType(add_to_output->data_type())); sp_beta = CudnnSPOnePtr<T>(); } else { sp_beta = CudnnSPZeroPtr<T>(); } OF_CUDNN_CHECK(cudnnBatchNormalizationForwardInference( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), moving_mean->dptr(), moving_variance->dptr(), epsilon)); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_BN_INFERENCE_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization") \ .SetCreateFn<NormalizationInferenceKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value) \ & (user_op::HobAttr<bool>("training") == false)) \ .SetInplaceProposalFn([](const user_op::InferContext& ctx, \ user_op::AddInplaceArgPair AddInplaceArgPairFn) -> Maybe<void> { \ if (ctx.has_input("_add_to_output", 0)) { \ OF_RETURN_IF_ERROR(AddInplaceArgPairFn("y", 0, "_add_to_output", 0, true)); \ } \ return Maybe<void>::Ok(); \ }); REGISTER_BN_INFERENCE_KERNEL(float16) REGISTER_BN_INFERENCE_KERNEL(float) REGISTER_BN_INFERENCE_KERNEL(double) #undef REGISTER_BN_INFERENCE_KERNEL constexpr int64_t kCudaWarpSize = 32; template<typename T> __global__ void ReluGpu(int64_t n, const T* x, T* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; CUDA_1D_KERNEL_LOOP(i, n) { const T x_val = x[i]; const bool is_positive = (x_val > 0); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? x_val : 0; } } template<> __global__ void ReluGpu<half>(int64_t n, const half* x, half* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; const half zero = __float2half(0.0f); CUDA_1D_KERNEL_LOOP(i, n) { const half x_val = x[i]; const bool is_positive = __hgt(x_val, zero); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? x_val : zero; } } template<typename T> __global__ void AddReluGpu(int64_t n, const T* x, const T* addend, T* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; CUDA_1D_KERNEL_LOOP(i, n) { const T sum = x[i] + addend[i]; const bool is_positive = (sum > 0); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? sum : 0; } } template<> __global__ void AddReluGpu<half>(int64_t n, const half* x, const half* addend, half* y, int32_t* mask) { const int32_t lane_id = threadIdx.x % kCudaWarpSize; const half zero = __float2half(0.0f); CUDA_1D_KERNEL_LOOP(i, n) { const half sum = __hadd(x[i], addend[i]); const bool is_positive = __hgt(sum, zero); int32_t warp_mask = __ballot_sync(__activemask(), static_cast<int>(is_positive)); if (lane_id == 0) { mask[i / kCudaWarpSize] = warp_mask; } y[i] = is_positive ? sum : zero; } } template<typename T> void Relu(DeviceCtx* device_ctx, int64_t n, const T* x, T* y, int32_t* mask) { ReluGpu<T><<<BlocksNum4ThreadsNum(n), kCudaThreadsNumPerBlock, 0, device_ctx->cuda_stream()>>>( n, x, y, mask); } template<> void Relu<float16>(DeviceCtx* device_ctx, int64_t n, const float16* x, float16* y, int32_t* mask) { Relu<half>(device_ctx, n, reinterpret_cast<const half*>(x), reinterpret_cast<half*>(y), mask); } template<typename T> void AddRelu(DeviceCtx* device_ctx, int64_t n, const T* x, const T* addend, T* y, int32_t* mask) { AddReluGpu<T><<<BlocksNum4ThreadsNum(n), kCudaThreadsNumPerBlock, 0, device_ctx->cuda_stream()>>>( n, x, addend, y, mask); } template<> void AddRelu<float16>(DeviceCtx* device_ctx, int64_t n, const float16* x, const float16* addend, float16* y, int32_t* mask) { AddRelu<half>(device_ctx, n, reinterpret_cast<const half*>(x), reinterpret_cast<const half*>(addend), reinterpret_cast<half*>(y), mask); } template<typename T> __global__ void ReluBackwardGpu(int64_t n, const int32_t* mask, const T* dy, T* addend_diff) { int32_t lane_id = threadIdx.x % kCudaWarpSize; CUDA_1D_KERNEL_LOOP(i, n) { int32_t mask_val = mask[i / kCudaWarpSize]; bool is_positive = mask_val & (1 << lane_id); addend_diff[i] = static_cast<T>(is_positive) * dy[i]; } } template<typename T> void ReluBackward(DeviceCtx* device_ctx, int64_t n, const int32_t* mask, const T* dy, T* addend_diff) { ReluBackwardGpu<T> <<<BlocksNum4ThreadsNum(n), kCudaThreadsNumPerBlock, 0, device_ctx->cuda_stream()>>>( n, mask, dy, addend_diff); } template<> void ReluBackward<float16>(DeviceCtx* device_ctx, int64_t n, const int32_t* mask, const float16* dy, float16* addend_diff) { ReluBackward<half>(device_ctx, n, mask, reinterpret_cast<const half*>(dy), reinterpret_cast<half*>(addend_diff)); } template<typename T> class NormalizationTrainKernel final : public user_op::OpKernel { public: NormalizationTrainKernel() = default; ~NormalizationTrainKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { if (ctx->op_type_name() == "normalization") { CHECK(ctx->Attr<bool>("training")); } const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* moving_mean = ctx->Tensor4ArgNameAndIndex("moving_mean", 0); auto* moving_variance = ctx->Tensor4ArgNameAndIndex("moving_variance", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const auto momentum = ctx->Attr<float>("momentum"); auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); const DataType data_type = x->data_type(); CHECK_EQ(x->shape(), y->shape()); CHECK_EQ(y->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(moving_mean); desc_helper.CheckParamTensor(moving_variance); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); const void* sp_alpha = CudnnSPOnePtr<T>(); const void* sp_beta; if (ctx->has_input("_add_to_output", 0)) { const user_op::Tensor* add_to_output = ctx->Tensor4ArgNameAndIndex("_add_to_output", 0); CHECK_EQ(add_to_output->data_type(), y->data_type()); CHECK_EQ(add_to_output->shape(), y->shape()); Memcpy<DeviceType::kGPU>( ctx->device_ctx(), y->mut_dptr<void>(), add_to_output->dptr<void>(), add_to_output->shape().elem_cnt() * GetSizeOfDataType(add_to_output->data_type())); sp_beta = CudnnSPOnePtr<T>(); } else { sp_beta = CudnnSPZeroPtr<T>(); } #if defined(BN_ENABLE_EX_API) size_t workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &workspace_size)); size_t reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, nullptr, desc_helper.xy_desc(), &reserve_space_size)); auto* workspace = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); if (reserve_space_size == 0 && workspace_size <= workspace->shape().elem_cnt()) { OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTrainingEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), nullptr, nullptr, desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr(), nullptr, workspace->mut_dptr(), workspace->shape().elem_cnt(), nullptr, 0)); } else { OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTraining( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr())); } #else OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTraining( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, sp_alpha, sp_beta, desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr())); #endif if (ctx->op_type_name() == "normalization_add_relu") { CHECK(!ctx->has_input("_add_to_output", 0)); const int64_t elem_cnt = x->shape().elem_cnt(); auto* mask = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); if (ctx->has_input("addend", 0)) { const auto* addend = ctx->Tensor4ArgNameAndIndex("addend", 0); AddRelu(ctx->device_ctx(), elem_cnt, y->dptr<T>(), addend->dptr<T>(), y->mut_dptr<T>(), mask->mut_dptr<int32_t>()); } else { Relu(ctx->device_ctx(), elem_cnt, y->dptr<T>(), y->mut_dptr<T>(), mask->mut_dptr<int32_t>()); } } } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_BN_TRAIN_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization") \ .SetCreateFn<NormalizationTrainKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value) \ & (user_op::HobAttr<bool>("training") == true)) \ .SetInferTmpSizeFn(InferTrainTmpSize) \ .SetInplaceProposalFn([](const user_op::InferContext& ctx, \ user_op::AddInplaceArgPair AddInplaceArgPairFn) -> Maybe<void> { \ if (ctx.has_input("_add_to_output", 0)) { \ OF_RETURN_IF_ERROR(AddInplaceArgPairFn("y", 0, "_add_to_output", 0, true)); \ } \ return Maybe<void>::Ok(); \ }); REGISTER_BN_TRAIN_KERNEL(float16) REGISTER_BN_TRAIN_KERNEL(float) REGISTER_BN_TRAIN_KERNEL(double) #define REGISTER_BN_ADD_RELU_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization_add_relu") \ .SetCreateFn<NormalizationTrainKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferTrainTmpSize); REGISTER_BN_ADD_RELU_KERNEL(float16) REGISTER_BN_ADD_RELU_KERNEL(float) REGISTER_BN_ADD_RELU_KERNEL(double) template<typename T> class NormalizationGradUserKernel final : public user_op::OpKernel { public: NormalizationGradUserKernel() = default; ~NormalizationGradUserKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* dx = ctx->Tensor4ArgNameAndIndex("dx", 0); const auto* dy = ctx->Tensor4ArgNameAndIndex("dy", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); auto* gamma_diff = ctx->Tensor4ArgNameAndIndex("gamma_diff", 0); auto* beta_diff = ctx->Tensor4ArgNameAndIndex("beta_diff", 0); const auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); const auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); auto* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const DataType data_type = x->data_type(); CHECK_EQ(dy->shape(), x->shape()); CHECK_EQ(dy->data_type(), data_type); CHECK_EQ(dx->shape(), x->shape()); CHECK_EQ(dx->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(gamma_diff); desc_helper.CheckParamTensor(beta_diff); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); void* bn_workspace_ptr; size_t bn_workspace_size; const void* bn_dy_ptr; if (ctx->op_type_name() == "normalization_grad") { bn_workspace_ptr = tmp_buffer->mut_dptr(); bn_workspace_size = tmp_buffer->shape().elem_cnt(); bn_dy_ptr = dy->dptr(); } else if (ctx->op_type_name() == "normalization_add_relu_grad") { const int64_t elem_cnt = dy->shape().elem_cnt(); const auto* mask = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); user_op::Tensor* y = ctx->Tensor4ArgNameAndIndex("y", 0); if (ctx->has_output("addend_diff", 0)) { user_op::Tensor* addend_diff = ctx->Tensor4ArgNameAndIndex("addend_diff", 0); ReluBackward(ctx->device_ctx(), elem_cnt, mask->dptr<int32_t>(), dy->dptr<T>(), addend_diff->mut_dptr<T>()); bn_workspace_ptr = tmp_buffer->mut_dptr(); bn_workspace_size = tmp_buffer->shape().elem_cnt(); bn_dy_ptr = addend_diff->dptr(); } else { const size_t tmp_buffer_size = tmp_buffer->shape().elem_cnt(); const size_t relu_dx_size = GetCudaAlignedSize(dy->shape().elem_cnt() * GetSizeOfDataType(dy->data_type())); CHECK_GE(tmp_buffer_size, relu_dx_size); ReluBackward(ctx->device_ctx(), elem_cnt, mask->dptr<int32_t>(), dy->dptr<T>(), reinterpret_cast<T*>(tmp_buffer->mut_dptr())); bn_workspace_ptr = tmp_buffer->mut_dptr<char>() + relu_dx_size; bn_workspace_size = tmp_buffer_size - relu_dx_size; bn_dy_ptr = tmp_buffer->dptr(); } } else { UNIMPLEMENTED(); } #if defined(BN_ENABLE_EX_API) size_t workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), nullptr, desc_helper.xy_desc(), desc_helper.param_desc(), nullptr, &workspace_size)); size_t reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, nullptr, desc_helper.xy_desc(), &reserve_space_size)); if (reserve_space_size == 0 && workspace_size <= bn_workspace_size) { OF_CUDNN_CHECK(cudnnBatchNormalizationBackwardEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CUDNN_BATCHNORM_OPS_BN, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), nullptr, nullptr, desc_helper.xy_desc(), bn_dy_ptr, nullptr, nullptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), nullptr, gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr(), nullptr, bn_workspace_ptr, bn_workspace_size, nullptr, 0)); } else { OF_CUDNN_CHECK(cudnnBatchNormalizationBackward( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), bn_dy_ptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr())); } #else OF_CUDNN_CHECK(cudnnBatchNormalizationBackward( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), bn_dy_ptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr())); #endif } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_BN_GRAD_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization_grad") \ .SetCreateFn<NormalizationGradUserKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("dx", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferGradTmpSize); REGISTER_BN_GRAD_KERNEL(float16) REGISTER_BN_GRAD_KERNEL(float) REGISTER_BN_GRAD_KERNEL(double) #define REGISTER_BN_ADD_RELU_GRAD_KERNEL(dtype) \ REGISTER_USER_KERNEL("normalization_add_relu_grad") \ .SetCreateFn<NormalizationGradUserKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("dx", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferGradTmpSize); REGISTER_BN_ADD_RELU_GRAD_KERNEL(float16) REGISTER_BN_ADD_RELU_GRAD_KERNEL(float) REGISTER_BN_ADD_RELU_GRAD_KERNEL(double) #if (CUDNN_VERSION >= 7401) size_t InferFusedNormalizationAddReluTmpSize(user_op::InferContext* ctx) { const auto& x = ctx->InputTensorDesc("x", 0); const auto axis = ctx->Attr<int32_t>("axis"); const CudnnTensorDescHelper desc_helper(x.shape(), x.data_type(), axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnBatchNormOps_t ops; cudnnTensorDescriptor_t z_desc; if (ctx->has_input("addend", 0)) { ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; z_desc = desc_helper.xy_desc(); } else { ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; z_desc = nullptr; } OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), z_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &size_in_bytes)); return std::max(size_in_bytes, static_cast<size_t>(1)); } size_t InferFusedNormalizationAddReluGradTmpSize(user_op::InferContext* ctx) { const auto& x = ctx->InputTensorDesc("x", 0); const auto axis = ctx->Attr<int32_t>("axis"); const CudnnTensorDescHelper desc_helper(x.shape(), x.data_type(), axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); size_t size_in_bytes; cudnnHandle_t handle = GetOrCreateCudnnHandle(); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnBatchNormOps_t ops; cudnnTensorDescriptor_t z_desc; if (ctx->has_output("addend_diff", 0)) { ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; z_desc = desc_helper.xy_desc(); } else { ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; z_desc = nullptr; } OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( handle, CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), desc_helper.xy_desc(), desc_helper.xy_desc(), z_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &size_in_bytes)); return std::max(size_in_bytes, static_cast<size_t>(1)); } template<typename T> class FusedNormalizationAddReluKernel final : public user_op::OpKernel { public: FusedNormalizationAddReluKernel() = default; ~FusedNormalizationAddReluKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* moving_mean = ctx->Tensor4ArgNameAndIndex("moving_mean", 0); auto* moving_variance = ctx->Tensor4ArgNameAndIndex("moving_variance", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const auto momentum = ctx->Attr<float>("momentum"); auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); auto* reserve_space = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); auto* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); const DataType data_type = x->data_type(); CHECK_EQ(x->shape(), y->shape()); CHECK_EQ(y->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(moving_mean); desc_helper.CheckParamTensor(moving_variance); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnTensorDescriptor_t z_desc; const void* z_ptr; cudnnBatchNormOps_t ops; if (ctx->has_input("addend", 0)) { z_desc = desc_helper.xy_desc(); z_ptr = ctx->Tensor4ArgNameAndIndex("addend", 0)->dptr(); ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; } else { z_desc = nullptr; z_ptr = nullptr; ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; } size_t min_workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationForwardTrainingExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), z_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &min_workspace_size)); const size_t workspace_size = tmp_buffer->shape().elem_cnt(); CHECK_GE(workspace_size, min_workspace_size); size_t min_reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, activation_desc.Get(), desc_helper.xy_desc(), &min_reserve_space_size)); const size_t reserve_space_size = reserve_space->shape().elem_cnt(); CHECK_GE(reserve_space_size, min_reserve_space_size); OF_CUDNN_CHECK(cudnnBatchNormalizationForwardTrainingEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), z_desc, z_ptr, desc_helper.xy_desc(), y->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), 1.0 - momentum, moving_mean->mut_dptr(), moving_variance->mut_dptr(), epsilon, mean->mut_dptr(), inv_variance->mut_dptr(), activation_desc.Get(), tmp_buffer->mut_dptr(), workspace_size, reserve_space->mut_dptr(), reserve_space_size)); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_FUSED_BN_ADD_RELU_KERNEL(dtype) \ REGISTER_USER_KERNEL("cudnn_fused_normalization_add_relu") \ .SetCreateFn<FusedNormalizationAddReluKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("y", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferFusedNormalizationAddReluTmpSize); REGISTER_FUSED_BN_ADD_RELU_KERNEL(float16) template<typename T> class FusedNormalizationAddReluGradUserKernel final : public user_op::OpKernel { public: FusedNormalizationAddReluGradUserKernel() = default; ~FusedNormalizationAddReluGradUserKernel() override = default; private: void Compute(user_op::KernelComputeContext* ctx) const override { const auto* x = ctx->Tensor4ArgNameAndIndex("x", 0); const auto* y = ctx->Tensor4ArgNameAndIndex("y", 0); auto* dx = ctx->Tensor4ArgNameAndIndex("dx", 0); const auto* dy = ctx->Tensor4ArgNameAndIndex("dy", 0); const auto* gamma = ctx->Tensor4ArgNameAndIndex("gamma", 0); const auto* beta = ctx->Tensor4ArgNameAndIndex("beta", 0); auto* gamma_diff = ctx->Tensor4ArgNameAndIndex("gamma_diff", 0); auto* beta_diff = ctx->Tensor4ArgNameAndIndex("beta_diff", 0); const auto* mean = ctx->Tensor4ArgNameAndIndex("mean", 0); const auto* inv_variance = ctx->Tensor4ArgNameAndIndex("inv_variance", 0); const auto* reserve_space = ctx->Tensor4ArgNameAndIndex("reserve_space", 0); auto* tmp_buffer = ctx->Tensor4ArgNameAndIndex("tmp_buffer", 0); const auto axis = ctx->Attr<int32_t>("axis"); const auto epsilon = ctx->Attr<float>("epsilon"); const DataType data_type = x->data_type(); CHECK_EQ(dy->shape(), x->shape()); CHECK_EQ(dy->data_type(), data_type); CHECK_EQ(dx->shape(), x->shape()); CHECK_EQ(dx->data_type(), data_type); CHECK_GE(axis, 0); CHECK_LT(axis, x->shape().NumAxes()); const CudnnTensorDescHelper desc_helper(x->shape(), data_type, axis, CUDNN_BATCHNORM_SPATIAL_PERSISTENT); desc_helper.CheckParamTensor(gamma); desc_helper.CheckParamTensor(beta); desc_helper.CheckParamTensor(gamma_diff); desc_helper.CheckParamTensor(beta_diff); desc_helper.CheckParamTensor(mean); desc_helper.CheckParamTensor(inv_variance); CudnnActivationDesc activation_desc(CUDNN_ACTIVATION_RELU, CUDNN_PROPAGATE_NAN, 0); cudnnTensorDescriptor_t dz_desc; void* dz_ptr; cudnnBatchNormOps_t ops; if (ctx->has_output("addend_diff", 0)) { dz_desc = desc_helper.xy_desc(); dz_ptr = ctx->Tensor4ArgNameAndIndex("addend_diff", 0)->mut_dptr(); ops = CUDNN_BATCHNORM_OPS_BN_ADD_ACTIVATION; } else { dz_desc = nullptr; dz_ptr = nullptr; ops = CUDNN_BATCHNORM_OPS_BN_ACTIVATION; } size_t min_workspace_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationBackwardExWorkspaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, desc_helper.xy_desc(), desc_helper.xy_desc(), desc_helper.xy_desc(), dz_desc, desc_helper.xy_desc(), desc_helper.param_desc(), activation_desc.Get(), &min_workspace_size)); const size_t workspace_size = tmp_buffer->shape().elem_cnt(); CHECK_GE(workspace_size, min_workspace_size); size_t min_reserve_space_size; OF_CUDNN_CHECK(cudnnGetBatchNormalizationTrainingExReserveSpaceSize( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, activation_desc.Get(), desc_helper.xy_desc(), &min_reserve_space_size)); const size_t reserve_space_size = reserve_space->shape().elem_cnt(); CHECK_GE(reserve_space_size, min_reserve_space_size); OF_CUDNN_CHECK(cudnnBatchNormalizationBackwardEx( ctx->device_ctx()->cudnn_handle(), CUDNN_BATCHNORM_SPATIAL_PERSISTENT, ops, CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), CudnnSPOnePtr<T>(), CudnnSPZeroPtr<T>(), desc_helper.xy_desc(), x->dptr(), desc_helper.xy_desc(), y->dptr(), desc_helper.xy_desc(), dy->dptr(), dz_desc, dz_ptr, desc_helper.xy_desc(), dx->mut_dptr(), desc_helper.param_desc(), gamma->dptr(), beta->dptr(), gamma_diff->mut_dptr(), beta_diff->mut_dptr(), epsilon, mean->dptr(), inv_variance->dptr(), activation_desc.Get(), tmp_buffer->mut_dptr(), workspace_size, const_cast<void*>(reserve_space->dptr()), reserve_space_size)); } bool AlwaysComputeWhenAllOutputsEmpty() const override { return false; } }; #define REGISTER_FUSED_BN_ADD_RELU_GRAD_KERNEL(dtype) \ REGISTER_USER_KERNEL("cudnn_fused_normalization_add_relu_grad") \ .SetCreateFn<FusedNormalizationAddReluGradUserKernel<dtype>>() \ .SetIsMatchedHob((user_op::HobDeviceTag() == "gpu") \ & (user_op::HobDataType("dx", 0) == GetDataType<dtype>::value)) \ .SetInferTmpSizeFn(InferFusedNormalizationAddReluGradTmpSize); REGISTER_FUSED_BN_ADD_RELU_GRAD_KERNEL(float16) #endif } // namespace } // namespace oneflow #endif
90faaef7cdb289ac6de1efe704f05dcb1a942f22.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> __global__ void device_hello(){ //uncomment this line to print only one time (unless you have multiple blocks) //if(threadIdx.x==0) int block = (blockIdx.x + blockIdx.y * gridDim.x) * (blockDim.x * blockDim.y * blockDim.z) ; int thread = (threadIdx.z * (blockDim.x * blockDim.y) ) + (threadIdx.y * blockDim.x) + threadIdx.x; int global_id = block + thread; printf("Hello world! from the device! Global_Thread_Id:%d\n",global_id); return; } int main(void){ // rather than calling fflush setbuf(stdout, NULL); // greet from the host printf("Hello world! from the host!\n"); // launch a kernel with a block of threads to greet from the device dim3 blockSize(2,2,2); dim3 gridSize(2,2,1); // run several variations by playing with the block and grid sizes // above -- if you change the y or z dimensions change the print // statement to reflect that. hipLaunchKernelGGL(( device_hello), dim3(gridSize),dim3(blockSize), 0, 0, ); // comment this line out and see what happens hipDeviceSynchronize(); printf("Goodbye world! from the host!\n"); return 0; }
90faaef7cdb289ac6de1efe704f05dcb1a942f22.cu
#include <stdio.h> __global__ void device_hello(){ //uncomment this line to print only one time (unless you have multiple blocks) //if(threadIdx.x==0) int block = (blockIdx.x + blockIdx.y * gridDim.x) * (blockDim.x * blockDim.y * blockDim.z) ; int thread = (threadIdx.z * (blockDim.x * blockDim.y) ) + (threadIdx.y * blockDim.x) + threadIdx.x; int global_id = block + thread; printf("Hello world! from the device! Global_Thread_Id:%d\n",global_id); return; } int main(void){ // rather than calling fflush setbuf(stdout, NULL); // greet from the host printf("Hello world! from the host!\n"); // launch a kernel with a block of threads to greet from the device dim3 blockSize(2,2,2); dim3 gridSize(2,2,1); // run several variations by playing with the block and grid sizes // above -- if you change the y or z dimensions change the print // statement to reflect that. device_hello<<<gridSize,blockSize>>>(); // comment this line out and see what happens cudaDeviceSynchronize(); printf("Goodbye world! from the host!\n"); return 0; }
dd3e94492fd04436c09fda941282bc063d4ecbcc.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /*! \file simpleFunc.cu \author Andrew Kerr <arkerr@gatech.edu> \brief demonstrates function calls in CUDA - this thoroughly chokes Ocelot */ #include <stdio.h> extern "C" __noinline__ __device__ float square(float f) { return f * f; } extern "C" __global__ void kernel(float *A, int N) { int i = threadIdx.x + blockDim.x * blockIdx.x; if (i < N) { A[i] = square(A[i]); } } int main() { float *A_gpu, *A_cpu; const int N = 32; size_t bytes = sizeof(float)*N; int errors = 0; A_cpu = (float *)malloc(bytes); hipMalloc((void **)&A_gpu, bytes); dim3 block(32, 1); dim3 grid((N + 31) / 32, 1); for (int i = 0; i < N; i++) { A_cpu[i] = (float)i; } hipMemcpy(A_gpu, A_cpu, bytes, hipMemcpyHostToDevice); hipLaunchKernelGGL(( kernel), dim3(grid), dim3(block) , 0, 0, A_gpu, N); hipDeviceSynchronize(); hipMemcpy(A_cpu, A_gpu, bytes, hipMemcpyDeviceToHost); for (int i = 0; i < N; i++) { float got = A_cpu[i]; float expected = (float)i * (float)i; if (::fabs(got - expected) > 0.001) { ++errors; if (errors >= 5) { printf("Error[ %d ] - expected %f, got %f\n", i, expected, got); break; } } } free(A_cpu); hipFree(A_gpu); printf("Pass/Fail : %s\n", (errors ? "Fail": "Pass")); return 0; }
dd3e94492fd04436c09fda941282bc063d4ecbcc.cu
/*! \file simpleFunc.cu \author Andrew Kerr <arkerr@gatech.edu> \brief demonstrates function calls in CUDA - this thoroughly chokes Ocelot */ #include <stdio.h> extern "C" __noinline__ __device__ float square(float f) { return f * f; } extern "C" __global__ void kernel(float *A, int N) { int i = threadIdx.x + blockDim.x * blockIdx.x; if (i < N) { A[i] = square(A[i]); } } int main() { float *A_gpu, *A_cpu; const int N = 32; size_t bytes = sizeof(float)*N; int errors = 0; A_cpu = (float *)malloc(bytes); cudaMalloc((void **)&A_gpu, bytes); dim3 block(32, 1); dim3 grid((N + 31) / 32, 1); for (int i = 0; i < N; i++) { A_cpu[i] = (float)i; } cudaMemcpy(A_gpu, A_cpu, bytes, cudaMemcpyHostToDevice); kernel<<< grid, block >>>(A_gpu, N); cudaThreadSynchronize(); cudaMemcpy(A_cpu, A_gpu, bytes, cudaMemcpyDeviceToHost); for (int i = 0; i < N; i++) { float got = A_cpu[i]; float expected = (float)i * (float)i; if (std::fabs(got - expected) > 0.001) { ++errors; if (errors >= 5) { printf("Error[ %d ] - expected %f, got %f\n", i, expected, got); break; } } } free(A_cpu); cudaFree(A_gpu); printf("Pass/Fail : %s\n", (errors ? "Fail": "Pass")); return 0; }
a69969f96157b6f056b5a4b0e33d7526eb81ed37.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include <Environment.h> #include <loops/transform_strict.h> #include <types/types.h> #include <op_boilerplate.h> #include <loops/legacy_ops.h> #include <helpers/DebugHelper.h> using namespace simdOps; template <typename X, typename OpType> __global__ void transformStrictSimple(void *x, Nd4jLong *xShapeInfo, int xRank, void *params, void *z, Nd4jLong *zShapeInfo, int zRank, int *allocationPointer, void *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { functions::transform::TransformStrict<X>::template transformCuda<OpType>(x,xShapeInfo,params,z,zShapeInfo,allocationPointer,reductionPointer,tadShapeInfo, tadOffsets); } namespace functions { namespace transform { template<typename X> _CUDA_H void TransformStrict<X>::executeTransformShaped(dim3 launchDims, hipStream_t *stream, int opNum, void *x, Nd4jLong *xShape, int xRank, void *extraParams, void *z, Nd4jLong *zShape, int zRank, int *allocationPointer, void *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { DISPATCH_BY_OPNUM_T(intermediateShaped, PARAMS(launchDims, stream, x, xShape, xRank, extraParams, z, zShape, zRank, allocationPointer, reductionPointer, tadShapeInfo, tadOffsets), TRANSFORM_STRICT_OPS); DEBUG_KERNEL(stream, opNum); } template<typename X> template <typename OpType> __device__ void TransformStrict<X>::transformCuda(void *vx, Nd4jLong *xShapeInfo, void *vparams, void *vz, Nd4jLong *zShapeInfo, int *allocationPointer, void *vreductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { auto x = static_cast<X*>(vx); auto z = static_cast<X*>(vz); auto params = static_cast<X*>(vparams); auto reductionPointer = static_cast<X*>(vreductionPointer); if(OpType::requiresSpecial) { OpType::execSpecialCuda(x,xShapeInfo,z,zShapeInfo,params, allocationPointer, reductionPointer, tadShapeInfo, tadOffsets); return; } else { __shared__ Nd4jLong xEws; __shared__ Nd4jLong zEws; __shared__ char xOrder; __shared__ char zOrder; __shared__ Nd4jLong length; if (threadIdx.x == 0) { xEws = shape::elementWiseStride(xShapeInfo); zEws = shape::elementWiseStride(zShapeInfo); xOrder = shape::order(xShapeInfo); zOrder = shape::order(zShapeInfo); length = shape::length(xShapeInfo); } __syncthreads(); auto tid = blockIdx.x * blockDim.x + threadIdx.x; int totalThreads = gridDim.x * blockDim.x; if(xEws > 0 && zEws > 0 && xOrder == zOrder) { for (int i = tid; i < length; i += totalThreads) z[i * zEws] = OpType::op(x[i * xEws], params); } else { if(vx == vz) { for (Nd4jLong i = tid; i < length; i+= totalThreads) { auto xOffset = shape::getIndexOffset(i, xShapeInfo); z[xOffset] = OpType::op(x[xOffset], params); } } else { for (Nd4jLong i = tid; i < length; i+= totalThreads) { auto xOffset = shape::getIndexOffset(i, xShapeInfo); auto zOffset = shape::getIndexOffset(i, zShapeInfo); z[zOffset] = OpType::op(x[xOffset], params); } } } } }; template<typename X> template <typename OpType> _CUDA_H void TransformStrict<X>::intermediateShaped(dim3 launchDims, hipStream_t *stream, void *x, Nd4jLong *xShape, int xRank, void *extraParams, void *z, Nd4jLong *zShape, int zRank, int *allocationPointer, void *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { hipLaunchKernelGGL(( transformStrictSimple<X, OpType>), dim3(launchDims.x), dim3(launchDims.x), launchDims.z, *stream, x, xShape, xRank, extraParams, z, zShape, zRank, allocationPointer, reductionPointer, tadShapeInfo, tadOffsets); nd4j::DebugHelper::checkErrorCode(stream, "transformStrict(...) failed"); } BUILD_SINGLE_TEMPLATE(template class ND4J_EXPORT TransformStrict, , FLOAT_TYPES); } }
a69969f96157b6f056b5a4b0e33d7526eb81ed37.cu
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ // // @author raver119@gmail.com // #include <Environment.h> #include <loops/transform_strict.h> #include <types/types.h> #include <op_boilerplate.h> #include <loops/legacy_ops.h> #include <helpers/DebugHelper.h> using namespace simdOps; template <typename X, typename OpType> __global__ void transformStrictSimple(void *x, Nd4jLong *xShapeInfo, int xRank, void *params, void *z, Nd4jLong *zShapeInfo, int zRank, int *allocationPointer, void *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { functions::transform::TransformStrict<X>::template transformCuda<OpType>(x,xShapeInfo,params,z,zShapeInfo,allocationPointer,reductionPointer,tadShapeInfo, tadOffsets); } namespace functions { namespace transform { template<typename X> _CUDA_H void TransformStrict<X>::executeTransformShaped(dim3 launchDims, cudaStream_t *stream, int opNum, void *x, Nd4jLong *xShape, int xRank, void *extraParams, void *z, Nd4jLong *zShape, int zRank, int *allocationPointer, void *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { DISPATCH_BY_OPNUM_T(intermediateShaped, PARAMS(launchDims, stream, x, xShape, xRank, extraParams, z, zShape, zRank, allocationPointer, reductionPointer, tadShapeInfo, tadOffsets), TRANSFORM_STRICT_OPS); DEBUG_KERNEL(stream, opNum); } template<typename X> template <typename OpType> __device__ void TransformStrict<X>::transformCuda(void *vx, Nd4jLong *xShapeInfo, void *vparams, void *vz, Nd4jLong *zShapeInfo, int *allocationPointer, void *vreductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { auto x = static_cast<X*>(vx); auto z = static_cast<X*>(vz); auto params = static_cast<X*>(vparams); auto reductionPointer = static_cast<X*>(vreductionPointer); if(OpType::requiresSpecial) { OpType::execSpecialCuda(x,xShapeInfo,z,zShapeInfo,params, allocationPointer, reductionPointer, tadShapeInfo, tadOffsets); return; } else { __shared__ Nd4jLong xEws; __shared__ Nd4jLong zEws; __shared__ char xOrder; __shared__ char zOrder; __shared__ Nd4jLong length; if (threadIdx.x == 0) { xEws = shape::elementWiseStride(xShapeInfo); zEws = shape::elementWiseStride(zShapeInfo); xOrder = shape::order(xShapeInfo); zOrder = shape::order(zShapeInfo); length = shape::length(xShapeInfo); } __syncthreads(); auto tid = blockIdx.x * blockDim.x + threadIdx.x; int totalThreads = gridDim.x * blockDim.x; if(xEws > 0 && zEws > 0 && xOrder == zOrder) { for (int i = tid; i < length; i += totalThreads) z[i * zEws] = OpType::op(x[i * xEws], params); } else { if(vx == vz) { for (Nd4jLong i = tid; i < length; i+= totalThreads) { auto xOffset = shape::getIndexOffset(i, xShapeInfo); z[xOffset] = OpType::op(x[xOffset], params); } } else { for (Nd4jLong i = tid; i < length; i+= totalThreads) { auto xOffset = shape::getIndexOffset(i, xShapeInfo); auto zOffset = shape::getIndexOffset(i, zShapeInfo); z[zOffset] = OpType::op(x[xOffset], params); } } } } }; template<typename X> template <typename OpType> _CUDA_H void TransformStrict<X>::intermediateShaped(dim3 launchDims, cudaStream_t *stream, void *x, Nd4jLong *xShape, int xRank, void *extraParams, void *z, Nd4jLong *zShape, int zRank, int *allocationPointer, void *reductionPointer, Nd4jLong *tadShapeInfo, Nd4jLong *tadOffsets) { transformStrictSimple<X, OpType><<<launchDims.x, launchDims.x, launchDims.z, *stream>>>(x, xShape, xRank, extraParams, z, zShape, zRank, allocationPointer, reductionPointer, tadShapeInfo, tadOffsets); nd4j::DebugHelper::checkErrorCode(stream, "transformStrict(...) failed"); } BUILD_SINGLE_TEMPLATE(template class ND4J_EXPORT TransformStrict, , FLOAT_TYPES); } }
eafdaebd624bd0035e18a81ae0c296d71174727d.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #ifndef THCS_GENERIC_FILE #define THCS_GENERIC_FILE "generic/THCSTensor.cu" #else #include "THHThrustAllocator.cuh" #include "THHTensor.hpp" #include <thrust/device_ptr.h> #include <thrust/device_vector.h> #include <thrust/gather.h> #include <thrust/generate.h> #include <thrust/scan.h> #include <thrust/sequence.h> #include <thrust/sort.h> #include <thrust/transform.h> #include <thrust/unique.h> #if TORCH_HIP_VERSION >= 7000 #include <thrust/system/hip/execution_policy.h> #endif #define I_INFO(tensor) getTensorInfo<THCIndexTensor, uint64_t>(state, tensor) #define V_INFO(tensor) getTensorInfo<THCTensor, uint64_t>(state, tensor) THCTensor *THCSTensor_(toDense)(THCState *state, THCSTensor *self) { THLongStorage *size; THCTensor *dst; // set up the new tensor size = THCSTensor_(newSizeOf)(state, self); dst = THCTensor_(newWithSize)(state, size, NULL); THLongStorage_free(size); THCTensor_(zero)(state, dst); real one = ScalarConvert<int, real>::to(1); THCSTensor_(spcadd)(state, dst, dst, one, self); THCudaCheck(hipGetLastError()); return dst; } THCSTensor *THCSTensor_(newCoalesce)(THCState *state, THCSTensor *self) { ptrdiff_t nnz = self->nnz; if (nnz < 2) { self->coalesced = 1; } if (self->coalesced) { THCSTensor_(retain)(state, self); return self; } #if TORCH_HIP_VERSION >= 7000 THCThrustAllocator thrustAlloc(state); #define THRUST_EXEC(fn, ...) fn(thrust::hip::par(thrustAlloc).on(THCState_getCurrentStream(state)), ##__VA_ARGS__) #else #define THRUST_EXEC(fn, ...) fn(##__VA_ARGS__) #endif // For indices, a simple sort + unique suffices // For values, we use a custom kernel for segmented reduction (can't use Thrust due to indirection). THCTensor *values_ = THCSTensor_(newValues)(state, self); THCTensor *values = THCTensor_(newContiguous)(state, values_); THCTensor_(free)(state, values_); int nDimI = self->nDimensionI; int64_t stride = values->stride[0]; hipStream_t stream = THCState_getCurrentStream(state); // indices will be modified by Thrust, so we have to clone or use new storage // here. THCIndexTensor *indices1D = THCSTensor_(newFlattenedIndices)(state, self, 1); THCIndexTensor *origIndices = THCIndexTensor_(newWithSize1d)(state, nnz); THCIndexTensor *uniqueOffsets = THCIndexTensor_(newWithSize1d)(state, nnz); typedef thrust::device_ptr<int64_t> thrust_ptr; thrust_ptr indicesIter(THCIndexTensor_(data)(state, indices1D)); thrust_ptr origIndicesIter(THCIndexTensor_(data)(state, origIndices)); thrust_ptr uniqueOffsetsIter(THCIndexTensor_(data)(state, uniqueOffsets)); // Fill sortedOrigIndices with sequential indices thrust::counting_iterator<int64_t> countIterI(TH_INDEX_BASE); thrust::counting_iterator<int64_t> countIterO(TH_INDEX_BASE); THRUST_EXEC(thrust::copy, countIterI, countIterI + nnz, origIndicesIter); THRUST_EXEC(thrust::copy, countIterO, countIterO + nnz, uniqueOffsetsIter); THRUST_EXEC(thrust::sort_by_key, indicesIter, indicesIter + nnz, origIndicesIter, ThrustLTOp<int64_t>() ); // this forces device-host synchronization! thrust::pair<thrust_ptr, thrust_ptr> newEnd = THRUST_EXEC( thrust::unique_by_key, indicesIter, indicesIter + nnz, uniqueOffsetsIter ); int64_t newNnz = newEnd.first - indicesIter; THCIndexTensor_(resize2d)(state, indices1D, 1, newNnz); THCTensor *newValues = THCTensor_(new)(state); THCTensor_(resizeNd)(state, newValues, values->nDimension, values->size, NULL); newValues->size[0] = newNnz; dim3 grid(THCCeilDiv(newNnz, (int64_t) 4), THCCeilDiv(stride, (int64_t) 128)); dim3 block(32, 4); hipLaunchKernelGGL(( THCSTensor_coalesceValuesKernel<real, accreal>), dim3(grid), dim3(block), 0, stream, THCIndexTensor_(data)(state, uniqueOffsets), THCIndexTensor_(data)(state, origIndices), THCTensor_(data)(state, values), THCTensor_(data)(state, newValues), nnz, newNnz, stride ); // this grid-strided version is slower but probably more flexible // to different sizes // int64_t blockX = min(stride, (int64_t) 512); // dim3 block(blockX, 512 / blockX); // int64_t grid = min((int64_t) 1024, THCCeilDiv((int64_t) newNnz * stride, (int64_t) block.x * block.y)); // THCSTensor_coalesceValuesKernel_gridStrided<real, accreal><<<grid, block, 0, stream>>>( // THCIndexTensor_(data)(state, uniqueOffsets), // THCIndexTensor_(data)(state, origIndices), // THCTensor_(data)(state, values), // THCTensor_(data)(state, newValues), // nnz, // newNnz, // stride // ); THCIndexTensor_(free)(state, origIndices); THCIndexTensor_(free)(state, uniqueOffsets); //////////////////////////////////////////////////////////// // unflatten indices if necessary THCIndexTensor *newIndices; if (nDimI == 1) { newIndices = indices1D; } else { newIndices = THCIndexTensor_(newWithSize2d)(state, nDimI, newNnz); THCIndexTensor *indicesSlice = THCIndexTensor_(new)(state); if (TH_INDEX_BASE != 0) { THCIndexTensor_(add)(state, indices1D, indices1D, -1); } for (int64_t d = nDimI - 1; d >= 0; d--) { THCIndexTensor_(select)(state, indicesSlice, newIndices, 0, d); THCIndexTensor_(copy)(state, indicesSlice, indices1D); THCIndexTensor_(div)(state, indices1D, indices1D, self->size[d]); THCIndexTensor_(cadd)(state, indicesSlice, indicesSlice, -self->size[d], indices1D); } if (TH_INDEX_BASE != 0) { THCIndexTensor_(add)(state, newIndices, newIndices, 1); } THCIndexTensor_(free)(state, indices1D); THCIndexTensor_(free)(state, indicesSlice); } //////////////////////////////////////////////////////////// THLongStorage *size = THCSTensor_(newSizeOf)(state, self); THCSTensor *dst = THCSTensor_(newWithTensorAndSize)(state, newIndices, newValues, size); THLongStorage_free(size); THCTensor_(free)(state, values); THCIndexTensor_(free)(state, newIndices); THCTensor_(free)(state, newValues); dst->coalesced = 1; THCudaCheck(hipGetLastError()); return dst; #undef THRUST_EXEC } // forceClone is intended to use as a boolean, if set, the result will forced to // be a clone of self. THCIndexTensor* THCSTensor_(newFlattenedIndices)(THCState *state, THCSTensor *self, int forceClone) { THCIndexTensor *indices = THCSTensor_(newIndices)(state, self); int nDimI = self->nDimensionI; if (nDimI == 1) { if (forceClone) { THCIndexTensor *indices_clone = THCIndexTensor_(newClone)(state, indices); THCIndexTensor_(free)(state, indices); return indices_clone; } else { return indices; } } else { // FIXME TH_INDEX_BASE int64_t factor = 1; THCIndexTensor *indices1D = THCIndexTensor_(newWithSize2d)(state, 1, self->nnz); THCIndexTensor_(fill)(state, indices1D, TH_INDEX_BASE); THCIndexTensor *indicesSlice = THCIndexTensor_(new)(state); for (int64_t d = nDimI - 1; d >= 0; d--) { THCIndexTensor_(select)(state, indicesSlice, indices, 0, d); THCIndexTensor_(cadd)(state, indices1D, indices1D, factor, indicesSlice); if (TH_INDEX_BASE != 0) { THCIndexTensor_(add)(state, indices1D, indices1D, -TH_INDEX_BASE); } factor *= self->size[d]; } THCIndexTensor_(free)(state, indices); THCIndexTensor_(free)(state, indicesSlice); return indices1D; } } // In place transpose void THCSTensor_(transpose)(THCState *state, THCSTensor *self, int d1, int d2) { int64_t nDimI = THCSTensor_(nDimensionI)(state, self); int64_t nDimV = THCSTensor_(nDimensionV)(state, self); THArgCheck(d1 < nDimI && d2 < nDimI, 1, "Transposed dimensions should be sparse. Got nDimI: %ld, d1: %ld, d2: %ld", nDimI, d1, d2); THCIndexTensor *indices = THCSTensor_(newIndices)(state, self); int64_t nnz = THCSTensor_(nnz)(state, self); THCIndexTensor *buffer = THCIndexTensor_(newWithSize1d)(state, nnz); THCIndexTensor *slice1 = THCIndexTensor_(newSelect)(state, indices, 0, d1); THCIndexTensor *slice2 = THCIndexTensor_(newSelect)(state, indices, 0, d2); THCIndexTensor_(copy)(state, buffer, slice1); THCIndexTensor_(copy)(state, slice1, slice2); THCIndexTensor_(copy)(state, slice2, buffer); int64_t i = self->size[d1]; self->size[d1] = self->size[d2]; self->size[d2] = i; THCIndexTensor_(free)(state, indices); THCIndexTensor_(free)(state, buffer); THCIndexTensor_(free)(state, slice1); THCIndexTensor_(free)(state, slice2); } int THCSTensor_(getDevice)(THCState* state, const THCSTensor* tensor) { if (!tensor->values || !tensor->values->storage) return -1; return THCStorage_(getDevice)(state, tensor->values->storage); } #endif
eafdaebd624bd0035e18a81ae0c296d71174727d.cu
#ifndef THCS_GENERIC_FILE #define THCS_GENERIC_FILE "generic/THCSTensor.cu" #else #include "THCThrustAllocator.cuh" #include "THCTensor.hpp" #include <thrust/device_ptr.h> #include <thrust/device_vector.h> #include <thrust/gather.h> #include <thrust/generate.h> #include <thrust/scan.h> #include <thrust/sequence.h> #include <thrust/sort.h> #include <thrust/transform.h> #include <thrust/unique.h> #if CUDA_VERSION >= 7000 #include <thrust/system/cuda/execution_policy.h> #endif #define I_INFO(tensor) getTensorInfo<THCIndexTensor, uint64_t>(state, tensor) #define V_INFO(tensor) getTensorInfo<THCTensor, uint64_t>(state, tensor) THCTensor *THCSTensor_(toDense)(THCState *state, THCSTensor *self) { THLongStorage *size; THCTensor *dst; // set up the new tensor size = THCSTensor_(newSizeOf)(state, self); dst = THCTensor_(newWithSize)(state, size, NULL); THLongStorage_free(size); THCTensor_(zero)(state, dst); real one = ScalarConvert<int, real>::to(1); THCSTensor_(spcadd)(state, dst, dst, one, self); THCudaCheck(cudaGetLastError()); return dst; } THCSTensor *THCSTensor_(newCoalesce)(THCState *state, THCSTensor *self) { ptrdiff_t nnz = self->nnz; if (nnz < 2) { self->coalesced = 1; } if (self->coalesced) { THCSTensor_(retain)(state, self); return self; } #if CUDA_VERSION >= 7000 THCThrustAllocator thrustAlloc(state); #define THRUST_EXEC(fn, ...) fn(thrust::cuda::par(thrustAlloc).on(THCState_getCurrentStream(state)), ##__VA_ARGS__) #else #define THRUST_EXEC(fn, ...) fn(##__VA_ARGS__) #endif // For indices, a simple sort + unique suffices // For values, we use a custom kernel for segmented reduction (can't use Thrust due to indirection). THCTensor *values_ = THCSTensor_(newValues)(state, self); THCTensor *values = THCTensor_(newContiguous)(state, values_); THCTensor_(free)(state, values_); int nDimI = self->nDimensionI; int64_t stride = values->stride[0]; cudaStream_t stream = THCState_getCurrentStream(state); // indices will be modified by Thrust, so we have to clone or use new storage // here. THCIndexTensor *indices1D = THCSTensor_(newFlattenedIndices)(state, self, 1); THCIndexTensor *origIndices = THCIndexTensor_(newWithSize1d)(state, nnz); THCIndexTensor *uniqueOffsets = THCIndexTensor_(newWithSize1d)(state, nnz); typedef thrust::device_ptr<int64_t> thrust_ptr; thrust_ptr indicesIter(THCIndexTensor_(data)(state, indices1D)); thrust_ptr origIndicesIter(THCIndexTensor_(data)(state, origIndices)); thrust_ptr uniqueOffsetsIter(THCIndexTensor_(data)(state, uniqueOffsets)); // Fill sortedOrigIndices with sequential indices thrust::counting_iterator<int64_t> countIterI(TH_INDEX_BASE); thrust::counting_iterator<int64_t> countIterO(TH_INDEX_BASE); THRUST_EXEC(thrust::copy, countIterI, countIterI + nnz, origIndicesIter); THRUST_EXEC(thrust::copy, countIterO, countIterO + nnz, uniqueOffsetsIter); THRUST_EXEC(thrust::sort_by_key, indicesIter, indicesIter + nnz, origIndicesIter, ThrustLTOp<int64_t>() ); // this forces device-host synchronization! thrust::pair<thrust_ptr, thrust_ptr> newEnd = THRUST_EXEC( thrust::unique_by_key, indicesIter, indicesIter + nnz, uniqueOffsetsIter ); int64_t newNnz = newEnd.first - indicesIter; THCIndexTensor_(resize2d)(state, indices1D, 1, newNnz); THCTensor *newValues = THCTensor_(new)(state); THCTensor_(resizeNd)(state, newValues, values->nDimension, values->size, NULL); newValues->size[0] = newNnz; dim3 grid(THCCeilDiv(newNnz, (int64_t) 4), THCCeilDiv(stride, (int64_t) 128)); dim3 block(32, 4); THCSTensor_coalesceValuesKernel<real, accreal><<<grid, block, 0, stream>>>( THCIndexTensor_(data)(state, uniqueOffsets), THCIndexTensor_(data)(state, origIndices), THCTensor_(data)(state, values), THCTensor_(data)(state, newValues), nnz, newNnz, stride ); // this grid-strided version is slower but probably more flexible // to different sizes // int64_t blockX = min(stride, (int64_t) 512); // dim3 block(blockX, 512 / blockX); // int64_t grid = min((int64_t) 1024, THCCeilDiv((int64_t) newNnz * stride, (int64_t) block.x * block.y)); // THCSTensor_coalesceValuesKernel_gridStrided<real, accreal><<<grid, block, 0, stream>>>( // THCIndexTensor_(data)(state, uniqueOffsets), // THCIndexTensor_(data)(state, origIndices), // THCTensor_(data)(state, values), // THCTensor_(data)(state, newValues), // nnz, // newNnz, // stride // ); THCIndexTensor_(free)(state, origIndices); THCIndexTensor_(free)(state, uniqueOffsets); //////////////////////////////////////////////////////////// // unflatten indices if necessary THCIndexTensor *newIndices; if (nDimI == 1) { newIndices = indices1D; } else { newIndices = THCIndexTensor_(newWithSize2d)(state, nDimI, newNnz); THCIndexTensor *indicesSlice = THCIndexTensor_(new)(state); if (TH_INDEX_BASE != 0) { THCIndexTensor_(add)(state, indices1D, indices1D, -1); } for (int64_t d = nDimI - 1; d >= 0; d--) { THCIndexTensor_(select)(state, indicesSlice, newIndices, 0, d); THCIndexTensor_(copy)(state, indicesSlice, indices1D); THCIndexTensor_(div)(state, indices1D, indices1D, self->size[d]); THCIndexTensor_(cadd)(state, indicesSlice, indicesSlice, -self->size[d], indices1D); } if (TH_INDEX_BASE != 0) { THCIndexTensor_(add)(state, newIndices, newIndices, 1); } THCIndexTensor_(free)(state, indices1D); THCIndexTensor_(free)(state, indicesSlice); } //////////////////////////////////////////////////////////// THLongStorage *size = THCSTensor_(newSizeOf)(state, self); THCSTensor *dst = THCSTensor_(newWithTensorAndSize)(state, newIndices, newValues, size); THLongStorage_free(size); THCTensor_(free)(state, values); THCIndexTensor_(free)(state, newIndices); THCTensor_(free)(state, newValues); dst->coalesced = 1; THCudaCheck(cudaGetLastError()); return dst; #undef THRUST_EXEC } // forceClone is intended to use as a boolean, if set, the result will forced to // be a clone of self. THCIndexTensor* THCSTensor_(newFlattenedIndices)(THCState *state, THCSTensor *self, int forceClone) { THCIndexTensor *indices = THCSTensor_(newIndices)(state, self); int nDimI = self->nDimensionI; if (nDimI == 1) { if (forceClone) { THCIndexTensor *indices_clone = THCIndexTensor_(newClone)(state, indices); THCIndexTensor_(free)(state, indices); return indices_clone; } else { return indices; } } else { // FIXME TH_INDEX_BASE int64_t factor = 1; THCIndexTensor *indices1D = THCIndexTensor_(newWithSize2d)(state, 1, self->nnz); THCIndexTensor_(fill)(state, indices1D, TH_INDEX_BASE); THCIndexTensor *indicesSlice = THCIndexTensor_(new)(state); for (int64_t d = nDimI - 1; d >= 0; d--) { THCIndexTensor_(select)(state, indicesSlice, indices, 0, d); THCIndexTensor_(cadd)(state, indices1D, indices1D, factor, indicesSlice); if (TH_INDEX_BASE != 0) { THCIndexTensor_(add)(state, indices1D, indices1D, -TH_INDEX_BASE); } factor *= self->size[d]; } THCIndexTensor_(free)(state, indices); THCIndexTensor_(free)(state, indicesSlice); return indices1D; } } // In place transpose void THCSTensor_(transpose)(THCState *state, THCSTensor *self, int d1, int d2) { int64_t nDimI = THCSTensor_(nDimensionI)(state, self); int64_t nDimV = THCSTensor_(nDimensionV)(state, self); THArgCheck(d1 < nDimI && d2 < nDimI, 1, "Transposed dimensions should be sparse. Got nDimI: %ld, d1: %ld, d2: %ld", nDimI, d1, d2); THCIndexTensor *indices = THCSTensor_(newIndices)(state, self); int64_t nnz = THCSTensor_(nnz)(state, self); THCIndexTensor *buffer = THCIndexTensor_(newWithSize1d)(state, nnz); THCIndexTensor *slice1 = THCIndexTensor_(newSelect)(state, indices, 0, d1); THCIndexTensor *slice2 = THCIndexTensor_(newSelect)(state, indices, 0, d2); THCIndexTensor_(copy)(state, buffer, slice1); THCIndexTensor_(copy)(state, slice1, slice2); THCIndexTensor_(copy)(state, slice2, buffer); int64_t i = self->size[d1]; self->size[d1] = self->size[d2]; self->size[d2] = i; THCIndexTensor_(free)(state, indices); THCIndexTensor_(free)(state, buffer); THCIndexTensor_(free)(state, slice1); THCIndexTensor_(free)(state, slice2); } int THCSTensor_(getDevice)(THCState* state, const THCSTensor* tensor) { if (!tensor->values || !tensor->values->storage) return -1; return THCStorage_(getDevice)(state, tensor->values->storage); } #endif
7dc21bf2eafd93f474e7ab17f98ecd3c0304551c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ #ifndef NDARRAY_CPP #define NDARRAY_CPP #include "../NDArray.h" #include "../NDArrayFactory.h" #include "NativeOpExecutioner.h" #include <memory/Workspace.h> #include <memory/MemoryRegistrator.h> #include <ops.h> #include <ops/gemm.h> #include <pointercast.h> #include <stdexcept> #include <memory> #include <helpers/logger.h> #include <loops/pairwise_transform.h> #include <loops/transform_same.h> #include <loops/random.h> #include <loops/broadcasting.h> #include <indexing/NDIndex.h> #include <indexing/IndicesList.h> #include <helpers/ShapeUtils.h> #include <sstream> #include <helpers/ArrayUtils.h> #include <MmulHelper.h> #include <helpers/threshold.h> #include <exceptions/datatype_exception.h> #include <exceptions/cuda_exception.h> #include <specials_cuda.h> #include <loops/special_kernels.h> #include <PointersManager.h> #include "../NDArray.hpp" #include <ConstantShapeHelper.h> namespace nd4j { void* NDArray::platformBuffer() { return specialBuffer(); } void* NDArray::getPlatformBuffer() const { return getSpecialBuffer(); } Nd4jLong* NDArray::getPlatformShapeInfo() const { return getSpecialShapeInfo(); } Nd4jLong* NDArray::platformShapeInfo() { return specialShapeInfo(); } void NDArray::syncToDevice() const { _buffer->syncToSpecial(); } void NDArray::syncToHost() const { _buffer->syncToPrimary(getContext()); } void NDArray::tickWriteHost() const { _buffer->writePrimary(); } void NDArray::tickWriteDevice() const { _buffer->writeSpecial(); } void NDArray::tickReadHost() const { _buffer->readPrimary(); } void NDArray::tickReadDevice() const { _buffer->readSpecial(); } void NDArray::tickBothActual() const { _buffer->writePrimary(); _buffer->readSpecial(); } bool NDArray::isActualOnHostSide() const { return _buffer->isPrimaryActual(); } bool NDArray::isActualOnDeviceSide() const { return _buffer->isSpecialActual(); } void NDArray::makeBothBuffersActual() const { if(!isActualOnHostSide()) syncToHost(); if(!isActualOnDeviceSide()) syncToDevice(); } /////////////////////////////////////////////////////////////////// template<typename T> __global__ static void fillAsTriangularCuda(const void* vx, const Nd4jLong* xShapeInfo, void* vz, const Nd4jLong* zShapeInfo, const T val, const int lower, const int upper) { const auto x = reinterpret_cast<const T*>(vx); auto z = reinterpret_cast<T*>(vz); __shared__ int zRank, xRank, areSameOffsets; // xRank == zRank always, except when xRank = 1, in this case zRank = 2 __shared__ Nd4jLong zLen, totalThreads, *sharedMem; // xLen == zLen, except when xRank = 1, in this case zLen = 2*xLen if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; sharedMem = reinterpret_cast<Nd4jLong*>(shmem); areSameOffsets = shape::haveSameShapeAndStrides(xShapeInfo, zShapeInfo); xRank = shape::rank(xShapeInfo); zRank = shape::rank(zShapeInfo); zLen = shape::length(zShapeInfo); totalThreads = gridDim.x * blockDim.x; } __syncthreads(); auto coords = sharedMem + threadIdx.x * zRank; const auto tid = blockIdx.x * blockDim.x + threadIdx.x; for (Nd4jLong i = tid; i < zLen; i += totalThreads) { shape::index2coords(zRank, shape::shapeOf(const_cast<Nd4jLong*>(zShapeInfo)), i, zLen, coords); const auto zOffset = shape::getOffset(0, shape::shapeOf(const_cast<Nd4jLong*>(zShapeInfo)), shape::stride(const_cast<Nd4jLong*>(zShapeInfo)), coords, zRank); // if( (row + upper < col) || (row + lower > col) ) if((coords[zRank - 2] + upper < coords[zRank - 1]) || (coords[zRank - 2] + lower > coords[zRank - 1])) z[zOffset] = val; else if(vx != vz) { // when x and z are different arrays if(xRank != zRank) coords[0] = coords[1]; const auto xOffset = areSameOffsets ? zOffset : shape::getOffset(0, shape::shapeOf(const_cast<Nd4jLong*>(xShapeInfo)), shape::stride(const_cast<Nd4jLong*>(xShapeInfo)), coords, xRank); z[zOffset] = x[xOffset]; } } } /////////////////////////////////////////////////////////////////// template<typename T> void NDArray::fillAsTriangular(const float val, int lower, int upper, const char direction, NDArray* target) { if (isS()) throw std::runtime_error("NDArray::fillAsTriangular: you can't use this method on String array!"); if(target == nullptr) target = this; if(!isSameShape(target) && !(rankOf() == 1 && target->rankOf() == 2 && sizeAt(0) == target->sizeAt(0) && sizeAt(0) == target->sizeAt(1))) throw std::string("NDArray::fillAsTriangular method: wrong shape of target array !"); if (direction == 'u') lower = -target->sizeAt(-2); else if (direction == 'l') upper = target->sizeAt(-1); const int threadsPerBlock = MAX_NUM_THREADS / 4; const int blocksPerGrid = (target->lengthOf() + threadsPerBlock - 1) / threadsPerBlock; const int sharedMem = threadsPerBlock * sizeof(decltype(*target->getShapeInfo())) * target->rankOf() + 128; PointersManager manager(getContext(), "NDArray::fillAsTriangular"); NDArray::prepareSpecialUse({target}, {this}); hipLaunchKernelGGL(( fillAsTriangularCuda<T>), dim3(blocksPerGrid), dim3(threadsPerBlock), sharedMem, *getContext()->getCudaStream(), getPlatformBuffer(), getPlatformShapeInfo(), target->getPlatformBuffer(), target->getPlatformShapeInfo(), static_cast<T>(val), lower, upper); NDArray::registerSpecialUse({target}, {this}); manager.synchronize(); } BUILD_SINGLE_TEMPLATE(template void NDArray::fillAsTriangular, (const float val, int lower, int upper, const char direction, NDArray* target), LIBND4J_TYPES); //////////////////////////////////////////////////////////////////////// template<typename T> __global__ static void identityMatrixCuda(void* vx, const Nd4jLong* xShapeInfo, const T val) { auto x = reinterpret_cast<T*>(vx); __shared__ int rank; __shared__ Nd4jLong len, totalThreads, *sharedMem; // xLen == zLen, except when xRank = 1, in this case zLen = 2*xLen if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; sharedMem = reinterpret_cast<Nd4jLong*>(shmem); rank = shape::rank(xShapeInfo); len = shape::length(xShapeInfo); totalThreads = gridDim.x * blockDim.x; } __syncthreads(); auto coords = sharedMem + threadIdx.x * rank; const auto tid = blockIdx.x * blockDim.x + threadIdx.x; for (Nd4jLong i = tid; i < len; i += totalThreads) { shape::index2coords(rank, shape::shapeOf(const_cast<Nd4jLong*>(xShapeInfo)), i, len, coords); const auto offset = shape::getOffset(0, shape::shapeOf(const_cast<Nd4jLong*>(xShapeInfo)), shape::stride(const_cast<Nd4jLong*>(xShapeInfo)), coords, rank); if(coords[rank - 2] == coords[rank - 1]) // row == col -> on diagonal x[offset] = val; else x[offset] = static_cast<T>(0); } } /////////////////////////////////////////////////////////////////// template<typename T> static void identityMatrixCudaLauncher(const int blocksPerGrid, const int threadsPerBlock, const int sharedMem, const hipStream_t *stream, void* vx, const Nd4jLong *xShapeInfo, const float val) { hipLaunchKernelGGL(( identityMatrixCuda<T>), dim3(blocksPerGrid), dim3(threadsPerBlock), sharedMem, *stream, vx, xShapeInfo, static_cast<T>(val)); } BUILD_SINGLE_TEMPLATE(template void identityMatrixCudaLauncher, (const int blocksPerGrid, const int threadsPerBlock, const int sharedMem, const hipStream_t *stream, void* vx, const Nd4jLong *xShapeInfo, const float val), LIBND4J_TYPES); //////////////////////////////////////////////////////////////////////// void NDArray::setIdentity() { if (isS()) throw std::runtime_error("NDArray::setIdentity: you can't use this method on String array!"); // if (rankOf() != 2) // throw std::runtime_error("NDArray::setIdentity: method should work only for 2D tensors. But " + toStringValue(rankOf()) + " was given."); const int threadsPerBlock = MAX_NUM_THREADS / 4; const int blocksPerGrid = (lengthOf() + threadsPerBlock - 1) / threadsPerBlock; const int sharedMem = threadsPerBlock * sizeof(decltype(getShapeInfo())) * rankOf() + 128; PointersManager manager(getContext(), "NDArray::setIdentity"); syncToDevice(); BUILD_SINGLE_SELECTOR(dataType(), identityMatrixCudaLauncher, (blocksPerGrid, threadsPerBlock, sharedMem, getContext()->getCudaStream(), getPlatformBuffer(), getPlatformShapeInfo(), 1.f), LIBND4J_TYPES); tickWriteDevice(); manager.synchronize(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void NDArray::swapUnsafe(NDArray& other) { auto xType = this->dataType(); if (xType != other.dataType()) throw std::runtime_error("NDArray::swapUnsage method: both arrays must have the same data type"); if(specialBuffer() == nullptr || other.specialBuffer() == nullptr) throw std::runtime_error("NDArray::swapUnsafe method: input array should not be empty!"); if(lengthOf() != other.lengthOf()) throw std::runtime_error("NDArray::swapUnsafe method: input arrays should have the same length!"); BUILD_SINGLE_SELECTOR(xType, templatedSwapUnsafe, (specialBuffer(), specialShapeInfo(), other.specialBuffer(), other.specialShapeInfo(), getContext()->getCudaStream()), LIBND4J_TYPES); } //////////////////////////////////////////////////////////////////////// void NDArray::synchronize(const char* msg) const { auto res = hipStreamSynchronize(*(getContext()->getCudaStream())); if (res != 0) throw std::runtime_error(msg + std::string(": synchronization failed !")); } //////////////////////////////////////////////////////////////////////// void NDArray::prepareSpecialUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList, bool synchronizeWritables) { for (const auto& a : readList) if(a != nullptr) a->syncToDevice(); for (const auto& a : writeList) { if (a != nullptr) { a->getDataBuffer()->allocateSpecial(); if (synchronizeWritables) a->syncToDevice(); } } } //////////////////////////////////////////////////////////////////////// void NDArray::registerSpecialUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList) { for (const auto& p : readList) if(p != nullptr) p->tickReadDevice(); for (const auto& p : writeList) if (p != nullptr) p->tickWriteDevice(); } //////////////////////////////////////////////////////////////////////// void NDArray::preparePrimaryUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList, bool synchronizeWritables) { for (const auto& a : readList) if(a != nullptr) a->syncToHost(); for (const auto& a : writeList) { if (a != nullptr) { a->getDataBuffer()->allocatePrimary(); if (synchronizeWritables) a->syncToHost(); } } } //////////////////////////////////////////////////////////////////////// void NDArray::registerPrimaryUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList) { for (const auto& p : readList) if(p != nullptr) p->tickReadHost(); for (const auto& p : writeList) if (p != nullptr) p->tickWriteHost(); } ////////////////////////////////////////////////////////////////////////// void NDArray::syncShape() const { hipMemcpy(getSpecialShapeInfo(), getShapeInfo(), shape::shapeInfoByteLength(getShapeInfo()), hipMemcpyHostToDevice); } ////////////////////////////////////////////////////////////////////////// void* NDArray::specialBufferWithOffset(Nd4jLong offset) const { return getSpecialBuffer() != nullptr ? static_cast<int8_t*>(getSpecialBuffer()) + (offset * sizeOfT()) : nullptr; } ////////////////////////////////////////////////////////////////////////// // change an array by repeating it the number of times given by reps. NDArray NDArray::tile(const std::vector<Nd4jLong>& reps) const { int dim = reps.size(); int product = 1; for(const auto& item : reps) product *= item; if(product == 0) throw std::runtime_error("NDArray::tile method: one of the elements in reps array is zero !"); int rankOld = rankOf(); int diff = rankOld - dim; if(product==1) { // in this case 2 possibilities are present: just reshape or nothing to do NDArray result(*this); if(diff < 0) { // reshape to higher dimension std::vector<Nd4jLong> shapeNew = reps; // need to have unities at first "diff" positions of new shape memcpy(&shapeNew[-diff], result.getShapeInfo()+1, rankOld * sizeof(Nd4jLong)); // put old shape numbers at rest of positions result.reshapei(ordering(), shapeNew); } return result; // nothing to do, if diff >= 0 -> identity tile } // evaluate shapeInfo for resulting array auto newShapeInfo = ShapeUtils::evalTileShapeInfo(*this, reps, getContext()->getWorkspace()); // create new buffer, in any case the memory amount new buffer points to is bigger then those for old _buffer std::shared_ptr<DataBuffer> newBuff = std::make_shared<DataBuffer>(shape::length(newShapeInfo) * sizeOfT(), dataType(), getContext()->getWorkspace(), true); // assign new shape and new buffer to resulting array NDArray result(newBuff, ShapeDescriptor(newShapeInfo), getContext()); // fill newBuff, loop through all elements of newBuff // looping through getBuffer() goes automatically by means of getSubArrayIndex applying const auto resultLen = result.lengthOf(); auto xType = this->dataType(); auto stream = getContext()->getCudaStream(); prepareSpecialUse({&result}, {this}); BUILD_SINGLE_SELECTOR(xType, tileKernelH, (this->getSpecialBuffer(), this->getSpecialShapeInfo(), result.getSpecialBuffer(), result.getSpecialShapeInfo(), resultLen, stream), LIBND4J_TYPES); registerSpecialUse({&result}, {this}); return result; } ////////////////////////////////////////////////////////////////////////// // change an array by repeating it the number of times given by reps. void NDArray::tile(const std::vector<Nd4jLong>& reps, NDArray& target) const { // evaluate true tile shapeInfo for comparison with target shapeInfo auto newShapeInfo = ShapeUtils::evalTileShapeInfo(*this, reps, getContext()->getWorkspace()); if(!shape::equalsSoft(newShapeInfo, target.getShapeInfo())) { throw std::runtime_error("NDArray::tile method - shapeInfo of target array is not suitable for tile operation !"); } // fill newBuff, loop through all elements of newBuff // looping through getBuffer() goes automatically by means of getSubArrayIndex applying const int ews = target.ews(); const int targetLen = target.lengthOf(); auto stream = getContext()->getCudaStream(); prepareSpecialUse({&target}, {this}); BUILD_DOUBLE_SELECTOR(target.dataType(), dataType(), tileKernelHH, (getSpecialBuffer(), getSpecialShapeInfo(), target.getSpecialBuffer(), target.getSpecialShapeInfo(), targetLen, ews, stream), LIBND4J_TYPES, LIBND4J_TYPES); registerSpecialUse({&target}, {this}); } ////////////////////////////////////////////////////////////////////////// void NDArray::tile(NDArray& target) const { if(rankOf() > target.rankOf()) throw std::runtime_error("NDArray::tile method - rank of target array must be bigger or equal to the rank of this array !"); if(!ShapeUtils::areShapesBroadcastable(*this, target)) throw std::runtime_error("NDArray::tile method - shapeInfo of target array is not suitable for tile operation !"); // fill newBuff, loop through all elements of newBuff // looping through getBuffer() goes automatically by means of getSubArrayIndex applying const auto ews = target.ews(); const auto targetLen = target.lengthOf(); auto stream = getContext()->getCudaStream(); prepareSpecialUse({&target}, {this}); BUILD_DOUBLE_SELECTOR(target.dataType(), dataType(), tileKernelHH, (getSpecialBuffer(), getSpecialShapeInfo(), target.getSpecialBuffer(), target.getSpecialShapeInfo(), targetLen, ews, stream), LIBND4J_TYPES, LIBND4J_TYPES); registerSpecialUse({&target}, {this}); } ////////////////////////////////////////////////////////////////////////// // create new array by repeating it the number of times given by reps NDArray* NDArray::repeat(int dimension, const std::vector<Nd4jLong>& repeats) const { auto outShape = ShapeUtils::evalRepeatShape(dimension, repeats, *this); // the size of outShape == rank int rank = rankOf(); // = outShape.size() std::vector<Nd4jLong> newShape(rank); for (int i = 0; i < rank; i++) newShape[i] = outShape[i]; auto ret = new NDArray('c', outShape, dataType(), getContext()); auto repeatDelta = shape::prodLong(newShape.data(), rank) / this->lengthOf(); std::vector<int> dimsToExclude = ShapeUtils::evalDimsToExclude(rankOf(), {dimension}); const Nd4jLong numTads = ShapeUtils::getNumOfSubArrs(getShapeInfo(), dimsToExclude); //this->tensorsAlongDimension({dimension}); std::vector<int> copy({dimension}); auto packX = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(this->getShapeInfo(), copy); auto packZ = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(ret->getShapeInfo(), copy); prepareSpecialUse({ret}, {this}); auto stream = getContext()->getCudaStream(); BUILD_SINGLE_SELECTOR(dataType(), repeatKernelH, (getSpecialBuffer(), ret->getSpecialBuffer(), numTads, lengthOf(), ret->lengthOf(), packX.platformShapeInfo(), packX.platformOffsets(), packZ.platformShapeInfo(), packZ.platformOffsets(), *stream), LIBND4J_TYPES); registerSpecialUse({ret}, {this}); return ret; } ////////////////////////////////////////////////////////////////////////// // fill array by repeating it the number of times given by reps void NDArray::repeat(int dimension, NDArray& target) const { if(dimension < 0) dimension += rankOf(); if(rankOf() != target.rankOf()) throw std::invalid_argument("NDArray::repeat(int dimension, NDArray& target) method: wrong rank of target array it must be equal to this array rank!"); Nd4jLong repeatDelta = target.sizeAt(dimension) / sizeAt(dimension); if(repeatDelta == 0) throw std::invalid_argument("NDArray::repeat(int dimension, NDArray& target) method: wrong shape of target array!"); std::vector<int> dimsToExclude = ShapeUtils::evalDimsToExclude(rankOf(), {dimension}); const Nd4jLong numTads = ShapeUtils::getNumOfSubArrs(getShapeInfo(), dimsToExclude); std::vector<int> copy({dimension}); auto packX = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(this->getShapeInfo(), copy); auto packZ = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(target.getShapeInfo(), copy); NDArray::prepareSpecialUse({&target}, {this}); auto stream = getContext()->getCudaStream(); BUILD_DOUBLE_SELECTOR(target.dataType(), dataType(), repeatKernelHH, (getSpecialBuffer(), target.getSpecialBuffer(), numTads, lengthOf(), packX.platformShapeInfo(), packX.platformOffsets(), packZ.platformShapeInfo(), packZ.platformOffsets(), *stream), LIBND4J_TYPES, LIBND4J_TYPES); NDArray::registerSpecialUse({&target}, {this}); } //////////////////////////////////////////////////////////////////////// void* NDArray::specialBuffer() { if (_buffer->special() == nullptr) return getBuffer(); // FIXME: this should be fixed once CUDA backend added return static_cast<int8_t*>(_buffer->special()) + (_offset * sizeOfT()); } //////////////////////////////////////////////////////////////////////// void* NDArray::getSpecialBuffer() const { if (_buffer->special() == nullptr) return getBuffer(); // FIXME: this should be fixed once CUDA backend added return static_cast<int8_t*>(_buffer->special()) + (_offset * sizeOfT()); } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray::printCurrentBuffer(const bool host, const char* msg, const int precision) const { if(_length == 0) { printf("NDArray::printActualBuffer: array length is zero !\n"); return; } if(msg) printf("%s", msg); if(host) { if(getBuffer() == nullptr || _length == 0) { printf("NDArray::printActualBuffer: host buffer is nullptr !\n"); return; } const T* buff = bufferAsT<T>(); for (uint i = 0; i < _length; i++) printf("%.*f, ", precision, (double)buff[getOffset(i)]); printf("\n"); } else { if(getSpecialBuffer() == nullptr || _length == 0) { printf("NDArray::printSpecialBuffer: special buffer is nullptr !\n"); return; } void* pHost = operator new(sizeof(T) * _length); if (ews() != 1) { for (uint i = 0; i < _length; i++) hipMemcpyAsync(reinterpret_cast<T*>(pHost) + i, specialBufferWithOffset(i), sizeof(T), hipMemcpyDeviceToHost, *(getContext()->getCudaStream())); } else hipMemcpyAsync(pHost, getSpecialBuffer(), sizeOfT() * _length, hipMemcpyDeviceToHost, *getContext()->getCudaStream()); hipError_t cudaResult = hipStreamSynchronize(*getContext()->getCudaStream()); if(cudaResult != 0) throw std::runtime_error("NDArray::printSpecialBuffer: hipStreamSynchronize failed!"); for (uint i = 0; i < _length; i++) printf("%.*f, ", precision, (double)reinterpret_cast<T*>(pHost)[i]); printf("\n"); operator delete(pHost); } } template void NDArray::printCurrentBuffer<int>(const bool host,const char* msg, const int precision) const; template void NDArray::printCurrentBuffer<float>(const bool host, const char* msg, const int precision) const; template void NDArray::printCurrentBuffer<double>(const bool host, const char* msg, const int precision) const; #if defined(__HIPCC__) && !defined(BUILD_TESTS) //#include <cpu/NDArrayLambda.hpp> #endif } // end namespace nd4j #endif
7dc21bf2eafd93f474e7ab17f98ecd3c0304551c.cu
/******************************************************************************* * Copyright (c) 2015-2018 Skymind, Inc. * * This program and the accompanying materials are made available under the * terms of the Apache License, Version 2.0 which is available at * https://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. * * SPDX-License-Identifier: Apache-2.0 ******************************************************************************/ #ifndef NDARRAY_CPP #define NDARRAY_CPP #include "../NDArray.h" #include "../NDArrayFactory.h" #include "NativeOpExecutioner.h" #include <memory/Workspace.h> #include <memory/MemoryRegistrator.h> #include <ops.h> #include <ops/gemm.h> #include <pointercast.h> #include <stdexcept> #include <memory> #include <helpers/logger.h> #include <loops/pairwise_transform.h> #include <loops/transform_same.h> #include <loops/random.h> #include <loops/broadcasting.h> #include <indexing/NDIndex.h> #include <indexing/IndicesList.h> #include <helpers/ShapeUtils.h> #include <sstream> #include <helpers/ArrayUtils.h> #include <MmulHelper.h> #include <helpers/threshold.h> #include <exceptions/datatype_exception.h> #include <exceptions/cuda_exception.h> #include <specials_cuda.h> #include <loops/special_kernels.h> #include <PointersManager.h> #include "../NDArray.hpp" #include <ConstantShapeHelper.h> namespace nd4j { void* NDArray::platformBuffer() { return specialBuffer(); } void* NDArray::getPlatformBuffer() const { return getSpecialBuffer(); } Nd4jLong* NDArray::getPlatformShapeInfo() const { return getSpecialShapeInfo(); } Nd4jLong* NDArray::platformShapeInfo() { return specialShapeInfo(); } void NDArray::syncToDevice() const { _buffer->syncToSpecial(); } void NDArray::syncToHost() const { _buffer->syncToPrimary(getContext()); } void NDArray::tickWriteHost() const { _buffer->writePrimary(); } void NDArray::tickWriteDevice() const { _buffer->writeSpecial(); } void NDArray::tickReadHost() const { _buffer->readPrimary(); } void NDArray::tickReadDevice() const { _buffer->readSpecial(); } void NDArray::tickBothActual() const { _buffer->writePrimary(); _buffer->readSpecial(); } bool NDArray::isActualOnHostSide() const { return _buffer->isPrimaryActual(); } bool NDArray::isActualOnDeviceSide() const { return _buffer->isSpecialActual(); } void NDArray::makeBothBuffersActual() const { if(!isActualOnHostSide()) syncToHost(); if(!isActualOnDeviceSide()) syncToDevice(); } /////////////////////////////////////////////////////////////////// template<typename T> __global__ static void fillAsTriangularCuda(const void* vx, const Nd4jLong* xShapeInfo, void* vz, const Nd4jLong* zShapeInfo, const T val, const int lower, const int upper) { const auto x = reinterpret_cast<const T*>(vx); auto z = reinterpret_cast<T*>(vz); __shared__ int zRank, xRank, areSameOffsets; // xRank == zRank always, except when xRank = 1, in this case zRank = 2 __shared__ Nd4jLong zLen, totalThreads, *sharedMem; // xLen == zLen, except when xRank = 1, in this case zLen = 2*xLen if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; sharedMem = reinterpret_cast<Nd4jLong*>(shmem); areSameOffsets = shape::haveSameShapeAndStrides(xShapeInfo, zShapeInfo); xRank = shape::rank(xShapeInfo); zRank = shape::rank(zShapeInfo); zLen = shape::length(zShapeInfo); totalThreads = gridDim.x * blockDim.x; } __syncthreads(); auto coords = sharedMem + threadIdx.x * zRank; const auto tid = blockIdx.x * blockDim.x + threadIdx.x; for (Nd4jLong i = tid; i < zLen; i += totalThreads) { shape::index2coords(zRank, shape::shapeOf(const_cast<Nd4jLong*>(zShapeInfo)), i, zLen, coords); const auto zOffset = shape::getOffset(0, shape::shapeOf(const_cast<Nd4jLong*>(zShapeInfo)), shape::stride(const_cast<Nd4jLong*>(zShapeInfo)), coords, zRank); // if( (row + upper < col) || (row + lower > col) ) if((coords[zRank - 2] + upper < coords[zRank - 1]) || (coords[zRank - 2] + lower > coords[zRank - 1])) z[zOffset] = val; else if(vx != vz) { // when x and z are different arrays if(xRank != zRank) coords[0] = coords[1]; const auto xOffset = areSameOffsets ? zOffset : shape::getOffset(0, shape::shapeOf(const_cast<Nd4jLong*>(xShapeInfo)), shape::stride(const_cast<Nd4jLong*>(xShapeInfo)), coords, xRank); z[zOffset] = x[xOffset]; } } } /////////////////////////////////////////////////////////////////// template<typename T> void NDArray::fillAsTriangular(const float val, int lower, int upper, const char direction, NDArray* target) { if (isS()) throw std::runtime_error("NDArray::fillAsTriangular: you can't use this method on String array!"); if(target == nullptr) target = this; if(!isSameShape(target) && !(rankOf() == 1 && target->rankOf() == 2 && sizeAt(0) == target->sizeAt(0) && sizeAt(0) == target->sizeAt(1))) throw std::string("NDArray::fillAsTriangular method: wrong shape of target array !"); if (direction == 'u') lower = -target->sizeAt(-2); else if (direction == 'l') upper = target->sizeAt(-1); const int threadsPerBlock = MAX_NUM_THREADS / 4; const int blocksPerGrid = (target->lengthOf() + threadsPerBlock - 1) / threadsPerBlock; const int sharedMem = threadsPerBlock * sizeof(decltype(*target->getShapeInfo())) * target->rankOf() + 128; PointersManager manager(getContext(), "NDArray::fillAsTriangular"); NDArray::prepareSpecialUse({target}, {this}); fillAsTriangularCuda<T><<<blocksPerGrid, threadsPerBlock, sharedMem, *getContext()->getCudaStream()>>>(getPlatformBuffer(), getPlatformShapeInfo(), target->getPlatformBuffer(), target->getPlatformShapeInfo(), static_cast<T>(val), lower, upper); NDArray::registerSpecialUse({target}, {this}); manager.synchronize(); } BUILD_SINGLE_TEMPLATE(template void NDArray::fillAsTriangular, (const float val, int lower, int upper, const char direction, NDArray* target), LIBND4J_TYPES); //////////////////////////////////////////////////////////////////////// template<typename T> __global__ static void identityMatrixCuda(void* vx, const Nd4jLong* xShapeInfo, const T val) { auto x = reinterpret_cast<T*>(vx); __shared__ int rank; __shared__ Nd4jLong len, totalThreads, *sharedMem; // xLen == zLen, except when xRank = 1, in this case zLen = 2*xLen if (threadIdx.x == 0) { extern __shared__ unsigned char shmem[]; sharedMem = reinterpret_cast<Nd4jLong*>(shmem); rank = shape::rank(xShapeInfo); len = shape::length(xShapeInfo); totalThreads = gridDim.x * blockDim.x; } __syncthreads(); auto coords = sharedMem + threadIdx.x * rank; const auto tid = blockIdx.x * blockDim.x + threadIdx.x; for (Nd4jLong i = tid; i < len; i += totalThreads) { shape::index2coords(rank, shape::shapeOf(const_cast<Nd4jLong*>(xShapeInfo)), i, len, coords); const auto offset = shape::getOffset(0, shape::shapeOf(const_cast<Nd4jLong*>(xShapeInfo)), shape::stride(const_cast<Nd4jLong*>(xShapeInfo)), coords, rank); if(coords[rank - 2] == coords[rank - 1]) // row == col -> on diagonal x[offset] = val; else x[offset] = static_cast<T>(0); } } /////////////////////////////////////////////////////////////////// template<typename T> static void identityMatrixCudaLauncher(const int blocksPerGrid, const int threadsPerBlock, const int sharedMem, const cudaStream_t *stream, void* vx, const Nd4jLong *xShapeInfo, const float val) { identityMatrixCuda<T><<<blocksPerGrid, threadsPerBlock, sharedMem, *stream>>>(vx, xShapeInfo, static_cast<T>(val)); } BUILD_SINGLE_TEMPLATE(template void identityMatrixCudaLauncher, (const int blocksPerGrid, const int threadsPerBlock, const int sharedMem, const cudaStream_t *stream, void* vx, const Nd4jLong *xShapeInfo, const float val), LIBND4J_TYPES); //////////////////////////////////////////////////////////////////////// void NDArray::setIdentity() { if (isS()) throw std::runtime_error("NDArray::setIdentity: you can't use this method on String array!"); // if (rankOf() != 2) // throw std::runtime_error("NDArray::setIdentity: method should work only for 2D tensors. But " + toStringValue(rankOf()) + " was given."); const int threadsPerBlock = MAX_NUM_THREADS / 4; const int blocksPerGrid = (lengthOf() + threadsPerBlock - 1) / threadsPerBlock; const int sharedMem = threadsPerBlock * sizeof(decltype(getShapeInfo())) * rankOf() + 128; PointersManager manager(getContext(), "NDArray::setIdentity"); syncToDevice(); BUILD_SINGLE_SELECTOR(dataType(), identityMatrixCudaLauncher, (blocksPerGrid, threadsPerBlock, sharedMem, getContext()->getCudaStream(), getPlatformBuffer(), getPlatformShapeInfo(), 1.f), LIBND4J_TYPES); tickWriteDevice(); manager.synchronize(); } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void NDArray::swapUnsafe(NDArray& other) { auto xType = this->dataType(); if (xType != other.dataType()) throw std::runtime_error("NDArray::swapUnsage method: both arrays must have the same data type"); if(specialBuffer() == nullptr || other.specialBuffer() == nullptr) throw std::runtime_error("NDArray::swapUnsafe method: input array should not be empty!"); if(lengthOf() != other.lengthOf()) throw std::runtime_error("NDArray::swapUnsafe method: input arrays should have the same length!"); BUILD_SINGLE_SELECTOR(xType, templatedSwapUnsafe, (specialBuffer(), specialShapeInfo(), other.specialBuffer(), other.specialShapeInfo(), getContext()->getCudaStream()), LIBND4J_TYPES); } //////////////////////////////////////////////////////////////////////// void NDArray::synchronize(const char* msg) const { auto res = cudaStreamSynchronize(*(getContext()->getCudaStream())); if (res != 0) throw std::runtime_error(msg + std::string(": synchronization failed !")); } //////////////////////////////////////////////////////////////////////// void NDArray::prepareSpecialUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList, bool synchronizeWritables) { for (const auto& a : readList) if(a != nullptr) a->syncToDevice(); for (const auto& a : writeList) { if (a != nullptr) { a->getDataBuffer()->allocateSpecial(); if (synchronizeWritables) a->syncToDevice(); } } } //////////////////////////////////////////////////////////////////////// void NDArray::registerSpecialUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList) { for (const auto& p : readList) if(p != nullptr) p->tickReadDevice(); for (const auto& p : writeList) if (p != nullptr) p->tickWriteDevice(); } //////////////////////////////////////////////////////////////////////// void NDArray::preparePrimaryUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList, bool synchronizeWritables) { for (const auto& a : readList) if(a != nullptr) a->syncToHost(); for (const auto& a : writeList) { if (a != nullptr) { a->getDataBuffer()->allocatePrimary(); if (synchronizeWritables) a->syncToHost(); } } } //////////////////////////////////////////////////////////////////////// void NDArray::registerPrimaryUse(const std::initializer_list<const NDArray*>& writeList, const std::initializer_list<const NDArray*>& readList) { for (const auto& p : readList) if(p != nullptr) p->tickReadHost(); for (const auto& p : writeList) if (p != nullptr) p->tickWriteHost(); } ////////////////////////////////////////////////////////////////////////// void NDArray::syncShape() const { cudaMemcpy(getSpecialShapeInfo(), getShapeInfo(), shape::shapeInfoByteLength(getShapeInfo()), cudaMemcpyHostToDevice); } ////////////////////////////////////////////////////////////////////////// void* NDArray::specialBufferWithOffset(Nd4jLong offset) const { return getSpecialBuffer() != nullptr ? static_cast<int8_t*>(getSpecialBuffer()) + (offset * sizeOfT()) : nullptr; } ////////////////////////////////////////////////////////////////////////// // change an array by repeating it the number of times given by reps. NDArray NDArray::tile(const std::vector<Nd4jLong>& reps) const { int dim = reps.size(); int product = 1; for(const auto& item : reps) product *= item; if(product == 0) throw std::runtime_error("NDArray::tile method: one of the elements in reps array is zero !"); int rankOld = rankOf(); int diff = rankOld - dim; if(product==1) { // in this case 2 possibilities are present: just reshape or nothing to do NDArray result(*this); if(diff < 0) { // reshape to higher dimension std::vector<Nd4jLong> shapeNew = reps; // need to have unities at first "diff" positions of new shape memcpy(&shapeNew[-diff], result.getShapeInfo()+1, rankOld * sizeof(Nd4jLong)); // put old shape numbers at rest of positions result.reshapei(ordering(), shapeNew); } return result; // nothing to do, if diff >= 0 -> identity tile } // evaluate shapeInfo for resulting array auto newShapeInfo = ShapeUtils::evalTileShapeInfo(*this, reps, getContext()->getWorkspace()); // create new buffer, in any case the memory amount new buffer points to is bigger then those for old _buffer std::shared_ptr<DataBuffer> newBuff = std::make_shared<DataBuffer>(shape::length(newShapeInfo) * sizeOfT(), dataType(), getContext()->getWorkspace(), true); // assign new shape and new buffer to resulting array NDArray result(newBuff, ShapeDescriptor(newShapeInfo), getContext()); // fill newBuff, loop through all elements of newBuff // looping through getBuffer() goes automatically by means of getSubArrayIndex applying const auto resultLen = result.lengthOf(); auto xType = this->dataType(); auto stream = getContext()->getCudaStream(); prepareSpecialUse({&result}, {this}); BUILD_SINGLE_SELECTOR(xType, tileKernelH, (this->getSpecialBuffer(), this->getSpecialShapeInfo(), result.getSpecialBuffer(), result.getSpecialShapeInfo(), resultLen, stream), LIBND4J_TYPES); registerSpecialUse({&result}, {this}); return result; } ////////////////////////////////////////////////////////////////////////// // change an array by repeating it the number of times given by reps. void NDArray::tile(const std::vector<Nd4jLong>& reps, NDArray& target) const { // evaluate true tile shapeInfo for comparison with target shapeInfo auto newShapeInfo = ShapeUtils::evalTileShapeInfo(*this, reps, getContext()->getWorkspace()); if(!shape::equalsSoft(newShapeInfo, target.getShapeInfo())) { throw std::runtime_error("NDArray::tile method - shapeInfo of target array is not suitable for tile operation !"); } // fill newBuff, loop through all elements of newBuff // looping through getBuffer() goes automatically by means of getSubArrayIndex applying const int ews = target.ews(); const int targetLen = target.lengthOf(); auto stream = getContext()->getCudaStream(); prepareSpecialUse({&target}, {this}); BUILD_DOUBLE_SELECTOR(target.dataType(), dataType(), tileKernelHH, (getSpecialBuffer(), getSpecialShapeInfo(), target.getSpecialBuffer(), target.getSpecialShapeInfo(), targetLen, ews, stream), LIBND4J_TYPES, LIBND4J_TYPES); registerSpecialUse({&target}, {this}); } ////////////////////////////////////////////////////////////////////////// void NDArray::tile(NDArray& target) const { if(rankOf() > target.rankOf()) throw std::runtime_error("NDArray::tile method - rank of target array must be bigger or equal to the rank of this array !"); if(!ShapeUtils::areShapesBroadcastable(*this, target)) throw std::runtime_error("NDArray::tile method - shapeInfo of target array is not suitable for tile operation !"); // fill newBuff, loop through all elements of newBuff // looping through getBuffer() goes automatically by means of getSubArrayIndex applying const auto ews = target.ews(); const auto targetLen = target.lengthOf(); auto stream = getContext()->getCudaStream(); prepareSpecialUse({&target}, {this}); BUILD_DOUBLE_SELECTOR(target.dataType(), dataType(), tileKernelHH, (getSpecialBuffer(), getSpecialShapeInfo(), target.getSpecialBuffer(), target.getSpecialShapeInfo(), targetLen, ews, stream), LIBND4J_TYPES, LIBND4J_TYPES); registerSpecialUse({&target}, {this}); } ////////////////////////////////////////////////////////////////////////// // create new array by repeating it the number of times given by reps NDArray* NDArray::repeat(int dimension, const std::vector<Nd4jLong>& repeats) const { auto outShape = ShapeUtils::evalRepeatShape(dimension, repeats, *this); // the size of outShape == rank int rank = rankOf(); // = outShape.size() std::vector<Nd4jLong> newShape(rank); for (int i = 0; i < rank; i++) newShape[i] = outShape[i]; auto ret = new NDArray('c', outShape, dataType(), getContext()); auto repeatDelta = shape::prodLong(newShape.data(), rank) / this->lengthOf(); std::vector<int> dimsToExclude = ShapeUtils::evalDimsToExclude(rankOf(), {dimension}); const Nd4jLong numTads = ShapeUtils::getNumOfSubArrs(getShapeInfo(), dimsToExclude); //this->tensorsAlongDimension({dimension}); std::vector<int> copy({dimension}); auto packX = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(this->getShapeInfo(), copy); auto packZ = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(ret->getShapeInfo(), copy); prepareSpecialUse({ret}, {this}); auto stream = getContext()->getCudaStream(); BUILD_SINGLE_SELECTOR(dataType(), repeatKernelH, (getSpecialBuffer(), ret->getSpecialBuffer(), numTads, lengthOf(), ret->lengthOf(), packX.platformShapeInfo(), packX.platformOffsets(), packZ.platformShapeInfo(), packZ.platformOffsets(), *stream), LIBND4J_TYPES); registerSpecialUse({ret}, {this}); return ret; } ////////////////////////////////////////////////////////////////////////// // fill array by repeating it the number of times given by reps void NDArray::repeat(int dimension, NDArray& target) const { if(dimension < 0) dimension += rankOf(); if(rankOf() != target.rankOf()) throw std::invalid_argument("NDArray::repeat(int dimension, NDArray& target) method: wrong rank of target array it must be equal to this array rank!"); Nd4jLong repeatDelta = target.sizeAt(dimension) / sizeAt(dimension); if(repeatDelta == 0) throw std::invalid_argument("NDArray::repeat(int dimension, NDArray& target) method: wrong shape of target array!"); std::vector<int> dimsToExclude = ShapeUtils::evalDimsToExclude(rankOf(), {dimension}); const Nd4jLong numTads = ShapeUtils::getNumOfSubArrs(getShapeInfo(), dimsToExclude); std::vector<int> copy({dimension}); auto packX = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(this->getShapeInfo(), copy); auto packZ = nd4j::ConstantTadHelper::getInstance()->tadForDimensions(target.getShapeInfo(), copy); NDArray::prepareSpecialUse({&target}, {this}); auto stream = getContext()->getCudaStream(); BUILD_DOUBLE_SELECTOR(target.dataType(), dataType(), repeatKernelHH, (getSpecialBuffer(), target.getSpecialBuffer(), numTads, lengthOf(), packX.platformShapeInfo(), packX.platformOffsets(), packZ.platformShapeInfo(), packZ.platformOffsets(), *stream), LIBND4J_TYPES, LIBND4J_TYPES); NDArray::registerSpecialUse({&target}, {this}); } //////////////////////////////////////////////////////////////////////// void* NDArray::specialBuffer() { if (_buffer->special() == nullptr) return getBuffer(); // FIXME: this should be fixed once CUDA backend added return static_cast<int8_t*>(_buffer->special()) + (_offset * sizeOfT()); } //////////////////////////////////////////////////////////////////////// void* NDArray::getSpecialBuffer() const { if (_buffer->special() == nullptr) return getBuffer(); // FIXME: this should be fixed once CUDA backend added return static_cast<int8_t*>(_buffer->special()) + (_offset * sizeOfT()); } ////////////////////////////////////////////////////////////////////////// template<typename T> void NDArray::printCurrentBuffer(const bool host, const char* msg, const int precision) const { if(_length == 0) { printf("NDArray::printActualBuffer: array length is zero !\n"); return; } if(msg) printf("%s", msg); if(host) { if(getBuffer() == nullptr || _length == 0) { printf("NDArray::printActualBuffer: host buffer is nullptr !\n"); return; } const T* buff = bufferAsT<T>(); for (uint i = 0; i < _length; i++) printf("%.*f, ", precision, (double)buff[getOffset(i)]); printf("\n"); } else { if(getSpecialBuffer() == nullptr || _length == 0) { printf("NDArray::printSpecialBuffer: special buffer is nullptr !\n"); return; } void* pHost = operator new(sizeof(T) * _length); if (ews() != 1) { for (uint i = 0; i < _length; i++) cudaMemcpyAsync(reinterpret_cast<T*>(pHost) + i, specialBufferWithOffset(i), sizeof(T), cudaMemcpyDeviceToHost, *(getContext()->getCudaStream())); } else cudaMemcpyAsync(pHost, getSpecialBuffer(), sizeOfT() * _length, cudaMemcpyDeviceToHost, *getContext()->getCudaStream()); cudaError_t cudaResult = cudaStreamSynchronize(*getContext()->getCudaStream()); if(cudaResult != 0) throw std::runtime_error("NDArray::printSpecialBuffer: cudaStreamSynchronize failed!"); for (uint i = 0; i < _length; i++) printf("%.*f, ", precision, (double)reinterpret_cast<T*>(pHost)[i]); printf("\n"); operator delete(pHost); } } template void NDArray::printCurrentBuffer<int>(const bool host,const char* msg, const int precision) const; template void NDArray::printCurrentBuffer<float>(const bool host, const char* msg, const int precision) const; template void NDArray::printCurrentBuffer<double>(const bool host, const char* msg, const int precision) const; #if defined(__CUDACC__) && !defined(BUILD_TESTS) //#include <cpu/NDArrayLambda.hpp> #endif } // end namespace nd4j #endif
ff1e3b59e41f6eb7ed6c8bf83c7eb3f6901a1336.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /*Created on Mon Feb 10 10:00:00 2014 Oren Freifeld Email: freifeld@csail.mit.edu */ #ifndef DIM #define DIM 3 #endif #ifndef TESS_TYPE #define TESS_TYPE 2 #endif __device__ inline void A_times_b(double x[], double A[], double b[]) { // Result is computed inside x. x[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2] + A[3]; x[1] = A[4]*b[0] + A[5]*b[1] + A[6]*b[2] + A[7]; x[2] = A[8]*b[0] + A[9]*b[1] + A[10]*b[2] + A[11]; }; __device__ inline void const_A_times_b(double x[], const double A[], double b[]) { // Result is computed inside x. x[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2] + A[3]; x[1] = A[4]*b[0] + A[5]*b[1] + A[6]*b[2] + A[7]; x[2] = A[8]*b[0] + A[9]*b[1] + A[10]*b[2] + A[11]; }; __device__ inline int compute_cell_idx(double* p, int nC0, int nC1, int nC2, double inc_x,double inc_y, double inc_z) { int cell_idx=0; if (TESS_TYPE == 2){ cell_idx = round(min(double(nC0-1),max(0.0,(p[0] - fmod(p[0] , inc_x))/inc_x))) + round(min(double(nC1-1),max(0.0,(p[1] - fmod(p[1] , inc_y))/inc_y))) * nC0 + round(min(double(nC2-1),max(0.0,(p[2] - fmod(p[2] , inc_z))/inc_z))) * nC1*nC0 ; } else { double p0 = min((nC0*inc_x-0.0000000001),max(0.0,p[0])) ; double p1 = min((nC1*inc_y-0.0000000001),max(0.0,p[1])) ; double p2 = min((nC2*inc_x-0.0000000001),max(0.0,p[2])) ; double xmod = fmod(p0,inc_x); double ymod = fmod(p1,inc_y); double zmod = fmod(p2,inc_z); // We already too care of case negative values. // But for values that are too high we still need to check // since above we used nC0 and nC1, and not nC0-1 and nC1-1. int i = round(min(double(nC0-1),((p0 - xmod)/inc_x))); int j = round(min(double(nC1-1),((p1 - ymod)/inc_y))); int k = round(min(double(nC2-1),((p2 - zmod)/inc_z))); cell_idx = i + j * nC0 + k * nC1 * nC0; cell_idx *=5; // every rect consists of 5 tetra hedra // Need to adjust the value from above // (reason: avoid issues with the circularity) // Now bring it [0,1] range double x = xmod/inc_x; double y = ymod/inc_y; double z = zmod/inc_z; bool tf = false; if (k%2==0){ if ((i%2==0 && j%2==1) || (i%2==1 && j%2==0)){ tf = true; } } else if((i%2==0 && j%2==0) || (i%2==1 && j%2==1)){ tf = true; } if (tf){ double tmp = x; x = y; y = 1-tmp; } // Let ti be the index of the tetrahedron. // ti = 0 is the centeral. // For ti = 1: // -x -y +z >= 0 (it passes thrugh the origin; no offset) // For ti = 2: // x+y+z - 2 >= 0 // For ti = 3: // -x+y-z >= 0 (it passes thrugh the origin; no offset) // For ti = 4: // x-y-z >= 0 (it passes thrugh the origin; no offset) if (-x -y +z >= 0){ cell_idx+=1; } else if (x+y+z - 2 >= 0){ cell_idx+=2; } else if (-x+y-z >= 0){ cell_idx+=3; } else if (x-y-z >= 0){ cell_idx+=4; } // if none of the conditions above was triggered: // It is in the central tetrahedron. So "cell_idx+=0;". } return cell_idx; }; __device__ inline bool inBoundary(double *p, double *bbs) { return ( bbs[0*2] <= p[0] && p[0] < bbs[0*2+1]) && ( bbs[1*2] <= p[1] && p[1] < bbs[1*2+1]) && ( bbs[2*2] <= p[1] && p[2] < bbs[2*2+1]); } __device__ void solveODE(double *p, double* As, const double h, const int nStepsOdeSolver, const int nC0, const int nC1, const int nC2, const double inc_x, const double inc_y, const double inc_z) { //modifies p double v[DIM]; double pMid[DIM]; int cell_idx; for(int t=0; t<nStepsOdeSolver; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); int mi = cell_idx*DIM*(DIM+1); // index of As // compute at the current location A_times_b(v,As+mi,p); // compute mid point #pragma unroll for(int i=0; i<DIM; ++i){ pMid[i] = p[i] + h*v[i]/2.; } // compute velocity at mid point A_times_b(v,As+mi,pMid); // update p p[0] += v[0]*h; p[1] += v[1]*h; p[2] += v[2]*h; } } __device__ void solveODE2(double *p, double* As, double* Bs, double* grad_per_point, // shape: (nPts,dim_range,d=len(BasMats)), int idx, int d, int nPts, const double h, const int nStepsOdeSolver, const int nC0, const int nC1, const int nC2, const double inc_x, const double inc_y, const double inc_z) { //modifies p double v[DIM]; double pMid[DIM]; double vMid[DIM]; double q[DIM]; double qMid[DIM]; double u[DIM]; double uMid[DIM]; double B_times_T[DIM]; double A_times_dTdAlpha[DIM]; int cell_idx; int nEntries = DIM*(DIM+1); // set to zero for (int j=0; j<d; j++){ #pragma unroll for(int i=0; i<DIM; ++i){ // nPts,dim_range,d grad_per_point[idx*DIM*d + i * d + j] = 0; } } for(int t=0; t<nStepsOdeSolver; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); int mi = cell_idx*nEntries; // index of As // compute at the current location A_times_b(v,As+mi,p); // compute mid point #pragma unroll for(int i=0; i<DIM; ++i){ pMid[i] = p[i] + h*v[i]/2.; } // compute velocity at mid point A_times_b(vMid,As+mi,pMid); for (int j=0; j<d; j++){ int bi = j * nEntries*N_CELLS + mi ; // index of the Bs // copy q #pragma unroll for(int i=0; i<DIM; ++i){ // nPts,dim_range,d q[i] = grad_per_point[idx*DIM*d + i * d + j]; } // Step 1: Compute u using the old location // Find current RHS (term1 + term2) // Term1 A_times_b(B_times_T,Bs+ bi , p); // Term2 A_times_b(A_times_dTdAlpha,As+mi , q); // Sum both terms #pragma unroll for(int i=0; i<DIM; ++i){ u[i] = B_times_T[i] + A_times_dTdAlpha[i] ; } // Step 2: Compute mid "point" #pragma unroll for(int i=0; i<DIM; ++i){ qMid[i] = q[i] + h*u[i]/2.; } // Step 3: compute uMid // Term1 A_times_b(B_times_T,Bs+ bi , pMid); // Term2 A_times_b(A_times_dTdAlpha,As+mi , qMid); // Sum both terms #pragma unroll for(int i=0; i<DIM; ++i){ uMid[i] = B_times_T[i] + A_times_dTdAlpha[i] ; } // update q #pragma unroll for(int i=0; i<DIM; ++i){ q[i] += uMid[i]*h; } // #pragma unroll for(int i=0; i<DIM; ++i){ // nPts,dim_range,d grad_per_point[idx*DIM*d + i * d + j] = q[i]; } } // update p #pragma unroll for(int i=0; i<DIM; ++i){ p[i] += vMid[i]*h; } } } __global__ void calc_cell_idx(double* pts, int* cell_idx, const int nPts,const int nC0, const int nC1, const int nC2, double inc_x,double inc_y,double inc_z){ //int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; // Do we still need the command below? __syncthreads(); if(idx >= nPts) return; double p[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) p[i] = pts[idx*DIM+i]; cell_idx[idx] = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); } __global__ void calc_T(const double* pos0,double* pos ,const double* Trels, const double* As, const double dt, const int nTimeSteps, const int nStepsOdeSolver, const int nPts , const int nC0, const int nC1, const int nC2, const double inc_x,const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i){ As_[i] = As[i]; } } __syncthreads(); if(idx < nPts) { double p[DIM]; double pNew[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) { pos[idx*DIM+i]=pos0[idx*DIM+i]; // copy the initial location p[i] = pos[idx*DIM+i]; } double h = dt/double(nStepsOdeSolver); int cell_idx=0; int cell_idx_new =0; for (int t=0; t<nTimeSteps; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); const_A_times_b(pNew,Trels + cell_idx*DIM*(DIM+1),p); cell_idx_new = compute_cell_idx(pNew,nC0,nC1,nC2,inc_x,inc_y,inc_z); if (cell_idx_new == cell_idx){ // great, we didn't leave the cell #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pNew[i]; } } else{ // compute using ODE solver solveODE(p, As_, h, nStepsOdeSolver,nC0,nC1,nC2,inc_x,inc_y,inc_z); } } #pragma unroll for(int i=0; i<DIM; ++i) pos[idx*DIM+i] = p[i]; } } __global__ void calc_T_simple(const double* pos0,double* pos , const double* As, const double dt, const int nTimeSteps, const int nStepsOdeSolver, const int nPts , const int nC0, const int nC1, const int nC2, const double inc_x,const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { double p[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) { p[i]=pos0[idx*DIM+i]; // copy the initial location } double h = dt/double(nStepsOdeSolver); solveODE(p, As_, h, nStepsOdeSolver * nTimeSteps, nC0,nC1,nC2,inc_x,inc_y,inc_z); #pragma unroll for(int i=0; i<DIM; ++i) pos[idx*DIM+i] = p[i]; } } __global__ void calc_grad_alpha(const double* pos0,double* pos , const double* As, double* Bs, double* grad_per_point, // shape: (nPts,dim_range,d=len(BasMats)), const int d, const double dt, const int nTimeSteps, const int nStepsOdeSolver, const int nPts , const int nC0, const int nC1, const int nC2, const double inc_x,const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { double p[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) { p[i]=pos0[idx*DIM+i]; // copy the initial location } double h = dt/double(nStepsOdeSolver); solveODE2(p, As_, Bs, grad_per_point, idx, d, nPts, h, nStepsOdeSolver * nTimeSteps, nC0,nC1,nC2,inc_x,inc_y,inc_z); #pragma unroll for(int i=0; i<DIM; ++i) pos[idx*DIM+i] = p[i]; } } __global__ void calc_trajectory(double* pos, const double* Trels, const double* As, double dt, int nTimeSteps, int nStepsOdeSolver, const int nPts,const int nC0,const int nC1,const int nC2, const double inc_x, const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { double p[DIM]; double pNew[DIM]; #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pos[idx*DIM+i]; // copy initial location } double h = dt/double(nStepsOdeSolver); int cell_idx=0; int cell_idx_new =0; for (int t=0; t<nTimeSteps; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); const_A_times_b(pNew,Trels + cell_idx*DIM*(DIM+1),p); cell_idx_new = compute_cell_idx(pNew,nC0,nC1,nC2,inc_x,inc_y,inc_z); if (cell_idx_new == cell_idx){ // great, we didn't leave the cell. So we can use pNew. #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pNew[i]; } } else{// We stepped outside the cell. So discard pNew // and compute using ODE solver instead. solveODE(p, As_, h, nStepsOdeSolver,nC0,nC1,nC2,inc_x,inc_y,inc_z); } #pragma unroll for(int i=0; i<DIM; ++i) pos[(idx+t*nPts)*DIM+i] = p[i]; } } } __global__ void calc_v(double* pos, double* vel, double* As, int nPts,int nC0,int nC1,int nC2,double inc_x, double inc_y, double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); i++) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { int cell_idx=0; double p[DIM]; double v[DIM]; #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pos[idx*DIM+i]; v[i] = vel[idx*DIM+i]; } cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); A_times_b(v,As_ + cell_idx*DIM*(DIM+1),p); #pragma unroll for(int i=0; i<DIM; ++i){ vel[idx*DIM+i] = v[i]; } } }
ff1e3b59e41f6eb7ed6c8bf83c7eb3f6901a1336.cu
/*Created on Mon Feb 10 10:00:00 2014 Oren Freifeld Email: freifeld@csail.mit.edu */ #ifndef DIM #define DIM 3 #endif #ifndef TESS_TYPE #define TESS_TYPE 2 #endif __device__ inline void A_times_b(double x[], double A[], double b[]) { // Result is computed inside x. x[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2] + A[3]; x[1] = A[4]*b[0] + A[5]*b[1] + A[6]*b[2] + A[7]; x[2] = A[8]*b[0] + A[9]*b[1] + A[10]*b[2] + A[11]; }; __device__ inline void const_A_times_b(double x[], const double A[], double b[]) { // Result is computed inside x. x[0] = A[0]*b[0] + A[1]*b[1] + A[2]*b[2] + A[3]; x[1] = A[4]*b[0] + A[5]*b[1] + A[6]*b[2] + A[7]; x[2] = A[8]*b[0] + A[9]*b[1] + A[10]*b[2] + A[11]; }; __device__ inline int compute_cell_idx(double* p, int nC0, int nC1, int nC2, double inc_x,double inc_y, double inc_z) { int cell_idx=0; if (TESS_TYPE == 2){ cell_idx = round(min(double(nC0-1),max(0.0,(p[0] - fmod(p[0] , inc_x))/inc_x))) + round(min(double(nC1-1),max(0.0,(p[1] - fmod(p[1] , inc_y))/inc_y))) * nC0 + round(min(double(nC2-1),max(0.0,(p[2] - fmod(p[2] , inc_z))/inc_z))) * nC1*nC0 ; } else { double p0 = min((nC0*inc_x-0.0000000001),max(0.0,p[0])) ; double p1 = min((nC1*inc_y-0.0000000001),max(0.0,p[1])) ; double p2 = min((nC2*inc_x-0.0000000001),max(0.0,p[2])) ; double xmod = fmod(p0,inc_x); double ymod = fmod(p1,inc_y); double zmod = fmod(p2,inc_z); // We already too care of case negative values. // But for values that are too high we still need to check // since above we used nC0 and nC1, and not nC0-1 and nC1-1. int i = round(min(double(nC0-1),((p0 - xmod)/inc_x))); int j = round(min(double(nC1-1),((p1 - ymod)/inc_y))); int k = round(min(double(nC2-1),((p2 - zmod)/inc_z))); cell_idx = i + j * nC0 + k * nC1 * nC0; cell_idx *=5; // every rect consists of 5 tetra hedra // Need to adjust the value from above // (reason: avoid issues with the circularity) // Now bring it [0,1] range double x = xmod/inc_x; double y = ymod/inc_y; double z = zmod/inc_z; bool tf = false; if (k%2==0){ if ((i%2==0 && j%2==1) || (i%2==1 && j%2==0)){ tf = true; } } else if((i%2==0 && j%2==0) || (i%2==1 && j%2==1)){ tf = true; } if (tf){ double tmp = x; x = y; y = 1-tmp; } // Let ti be the index of the tetrahedron. // ti = 0 is the centeral. // For ti = 1: // -x -y +z >= 0 (it passes thrugh the origin; no offset) // For ti = 2: // x+y+z - 2 >= 0 // For ti = 3: // -x+y-z >= 0 (it passes thrugh the origin; no offset) // For ti = 4: // x-y-z >= 0 (it passes thrugh the origin; no offset) if (-x -y +z >= 0){ cell_idx+=1; } else if (x+y+z - 2 >= 0){ cell_idx+=2; } else if (-x+y-z >= 0){ cell_idx+=3; } else if (x-y-z >= 0){ cell_idx+=4; } // if none of the conditions above was triggered: // It is in the central tetrahedron. So "cell_idx+=0;". } return cell_idx; }; __device__ inline bool inBoundary(double *p, double *bbs) { return ( bbs[0*2] <= p[0] && p[0] < bbs[0*2+1]) && ( bbs[1*2] <= p[1] && p[1] < bbs[1*2+1]) && ( bbs[2*2] <= p[1] && p[2] < bbs[2*2+1]); } __device__ void solveODE(double *p, double* As, const double h, const int nStepsOdeSolver, const int nC0, const int nC1, const int nC2, const double inc_x, const double inc_y, const double inc_z) { //modifies p double v[DIM]; double pMid[DIM]; int cell_idx; for(int t=0; t<nStepsOdeSolver; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); int mi = cell_idx*DIM*(DIM+1); // index of As // compute at the current location A_times_b(v,As+mi,p); // compute mid point #pragma unroll for(int i=0; i<DIM; ++i){ pMid[i] = p[i] + h*v[i]/2.; } // compute velocity at mid point A_times_b(v,As+mi,pMid); // update p p[0] += v[0]*h; p[1] += v[1]*h; p[2] += v[2]*h; } } __device__ void solveODE2(double *p, double* As, double* Bs, double* grad_per_point, // shape: (nPts,dim_range,d=len(BasMats)), int idx, int d, int nPts, const double h, const int nStepsOdeSolver, const int nC0, const int nC1, const int nC2, const double inc_x, const double inc_y, const double inc_z) { //modifies p double v[DIM]; double pMid[DIM]; double vMid[DIM]; double q[DIM]; double qMid[DIM]; double u[DIM]; double uMid[DIM]; double B_times_T[DIM]; double A_times_dTdAlpha[DIM]; int cell_idx; int nEntries = DIM*(DIM+1); // set to zero for (int j=0; j<d; j++){ #pragma unroll for(int i=0; i<DIM; ++i){ // nPts,dim_range,d grad_per_point[idx*DIM*d + i * d + j] = 0; } } for(int t=0; t<nStepsOdeSolver; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); int mi = cell_idx*nEntries; // index of As // compute at the current location A_times_b(v,As+mi,p); // compute mid point #pragma unroll for(int i=0; i<DIM; ++i){ pMid[i] = p[i] + h*v[i]/2.; } // compute velocity at mid point A_times_b(vMid,As+mi,pMid); for (int j=0; j<d; j++){ int bi = j * nEntries*N_CELLS + mi ; // index of the Bs // copy q #pragma unroll for(int i=0; i<DIM; ++i){ // nPts,dim_range,d q[i] = grad_per_point[idx*DIM*d + i * d + j]; } // Step 1: Compute u using the old location // Find current RHS (term1 + term2) // Term1 A_times_b(B_times_T,Bs+ bi , p); // Term2 A_times_b(A_times_dTdAlpha,As+mi , q); // Sum both terms #pragma unroll for(int i=0; i<DIM; ++i){ u[i] = B_times_T[i] + A_times_dTdAlpha[i] ; } // Step 2: Compute mid "point" #pragma unroll for(int i=0; i<DIM; ++i){ qMid[i] = q[i] + h*u[i]/2.; } // Step 3: compute uMid // Term1 A_times_b(B_times_T,Bs+ bi , pMid); // Term2 A_times_b(A_times_dTdAlpha,As+mi , qMid); // Sum both terms #pragma unroll for(int i=0; i<DIM; ++i){ uMid[i] = B_times_T[i] + A_times_dTdAlpha[i] ; } // update q #pragma unroll for(int i=0; i<DIM; ++i){ q[i] += uMid[i]*h; } // #pragma unroll for(int i=0; i<DIM; ++i){ // nPts,dim_range,d grad_per_point[idx*DIM*d + i * d + j] = q[i]; } } // update p #pragma unroll for(int i=0; i<DIM; ++i){ p[i] += vMid[i]*h; } } } __global__ void calc_cell_idx(double* pts, int* cell_idx, const int nPts,const int nC0, const int nC1, const int nC2, double inc_x,double inc_y,double inc_z){ //int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; // Do we still need the command below? __syncthreads(); if(idx >= nPts) return; double p[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) p[i] = pts[idx*DIM+i]; cell_idx[idx] = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); } __global__ void calc_T(const double* pos0,double* pos ,const double* Trels, const double* As, const double dt, const int nTimeSteps, const int nStepsOdeSolver, const int nPts , const int nC0, const int nC1, const int nC2, const double inc_x,const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i){ As_[i] = As[i]; } } __syncthreads(); if(idx < nPts) { double p[DIM]; double pNew[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) { pos[idx*DIM+i]=pos0[idx*DIM+i]; // copy the initial location p[i] = pos[idx*DIM+i]; } double h = dt/double(nStepsOdeSolver); int cell_idx=0; int cell_idx_new =0; for (int t=0; t<nTimeSteps; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); const_A_times_b(pNew,Trels + cell_idx*DIM*(DIM+1),p); cell_idx_new = compute_cell_idx(pNew,nC0,nC1,nC2,inc_x,inc_y,inc_z); if (cell_idx_new == cell_idx){ // great, we didn't leave the cell #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pNew[i]; } } else{ // compute using ODE solver solveODE(p, As_, h, nStepsOdeSolver,nC0,nC1,nC2,inc_x,inc_y,inc_z); } } #pragma unroll for(int i=0; i<DIM; ++i) pos[idx*DIM+i] = p[i]; } } __global__ void calc_T_simple(const double* pos0,double* pos , const double* As, const double dt, const int nTimeSteps, const int nStepsOdeSolver, const int nPts , const int nC0, const int nC1, const int nC2, const double inc_x,const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { double p[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) { p[i]=pos0[idx*DIM+i]; // copy the initial location } double h = dt/double(nStepsOdeSolver); solveODE(p, As_, h, nStepsOdeSolver * nTimeSteps, nC0,nC1,nC2,inc_x,inc_y,inc_z); #pragma unroll for(int i=0; i<DIM; ++i) pos[idx*DIM+i] = p[i]; } } __global__ void calc_grad_alpha(const double* pos0,double* pos , const double* As, double* Bs, double* grad_per_point, // shape: (nPts,dim_range,d=len(BasMats)), const int d, const double dt, const int nTimeSteps, const int nStepsOdeSolver, const int nPts , const int nC0, const int nC1, const int nC2, const double inc_x,const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { double p[DIM]; #pragma unroll for(int i=0; i<DIM; ++i) { p[i]=pos0[idx*DIM+i]; // copy the initial location } double h = dt/double(nStepsOdeSolver); solveODE2(p, As_, Bs, grad_per_point, idx, d, nPts, h, nStepsOdeSolver * nTimeSteps, nC0,nC1,nC2,inc_x,inc_y,inc_z); #pragma unroll for(int i=0; i<DIM; ++i) pos[idx*DIM+i] = p[i]; } } __global__ void calc_trajectory(double* pos, const double* Trels, const double* As, double dt, int nTimeSteps, int nStepsOdeSolver, const int nPts,const int nC0,const int nC1,const int nC2, const double inc_x, const double inc_y, const double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); ++i) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { double p[DIM]; double pNew[DIM]; #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pos[idx*DIM+i]; // copy initial location } double h = dt/double(nStepsOdeSolver); int cell_idx=0; int cell_idx_new =0; for (int t=0; t<nTimeSteps; ++t) { cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); const_A_times_b(pNew,Trels + cell_idx*DIM*(DIM+1),p); cell_idx_new = compute_cell_idx(pNew,nC0,nC1,nC2,inc_x,inc_y,inc_z); if (cell_idx_new == cell_idx){ // great, we didn't leave the cell. So we can use pNew. #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pNew[i]; } } else{// We stepped outside the cell. So discard pNew // and compute using ODE solver instead. solveODE(p, As_, h, nStepsOdeSolver,nC0,nC1,nC2,inc_x,inc_y,inc_z); } #pragma unroll for(int i=0; i<DIM; ++i) pos[(idx+t*nPts)*DIM+i] = p[i]; } } } __global__ void calc_v(double* pos, double* vel, double* As, int nPts,int nC0,int nC1,int nC2,double inc_x, double inc_y, double inc_z) { int tid = threadIdx.x; int idx = threadIdx.x + blockIdx.x*blockDim.x; __shared__ double As_[N_CELLS*DIM*(DIM+1)]; if(tid < N_CELLS) { // copy from GPU RAM into grid-cell shared memory #pragma unroll for(int i=tid*DIM*(DIM+1); i<(tid+1)*DIM*(DIM+1); i++) As_[i] = As[i]; } __syncthreads(); if(idx < nPts) { int cell_idx=0; double p[DIM]; double v[DIM]; #pragma unroll for(int i=0; i<DIM; ++i){ p[i] = pos[idx*DIM+i]; v[i] = vel[idx*DIM+i]; } cell_idx = compute_cell_idx(p,nC0,nC1,nC2,inc_x,inc_y,inc_z); A_times_b(v,As_ + cell_idx*DIM*(DIM+1),p); #pragma unroll for(int i=0; i<DIM; ++i){ vel[idx*DIM+i] = v[i]; } } }
cfc0a298a0c238c9c4e707f28b76cb98b80871f5.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> __global__ void saxpy(int n, float *x, float *y) { int i = blockIdx.x*blockDim.x + threadIdx.x; if (i < n) y[i] = x[i] + y[i]; } void cuda_array_culc_add_float(float* x, float* y, int32_t N) { float *d_x, *d_y; hipMalloc(&d_x, N*sizeof(float)); hipMalloc(&d_y, N*sizeof(float)); hipMemcpy(d_x, x, N*sizeof(float), hipMemcpyHostToDevice); hipMemcpy(d_y, y, N*sizeof(float), hipMemcpyHostToDevice); // Perform SAXPY on 1M elements hipLaunchKernelGGL(( saxpy), dim3((N+255)/256), dim3(256), 0, 0, N, d_x, d_y); hipMemcpy(y, d_y, N*sizeof(float), hipMemcpyDeviceToHost); }
cfc0a298a0c238c9c4e707f28b76cb98b80871f5.cu
#include <stdio.h> __global__ void saxpy(int n, float *x, float *y) { int i = blockIdx.x*blockDim.x + threadIdx.x; if (i < n) y[i] = x[i] + y[i]; } void cuda_array_culc_add_float(float* x, float* y, int32_t N) { float *d_x, *d_y; cudaMalloc(&d_x, N*sizeof(float)); cudaMalloc(&d_y, N*sizeof(float)); cudaMemcpy(d_x, x, N*sizeof(float), cudaMemcpyHostToDevice); cudaMemcpy(d_y, y, N*sizeof(float), cudaMemcpyHostToDevice); // Perform SAXPY on 1M elements saxpy<<<(N+255)/256, 256>>>(N, d_x, d_y); cudaMemcpy(y, d_y, N*sizeof(float), cudaMemcpyDeviceToHost); }
7fff923866e0cc297696d4095e01e9c53da64869.hip
// !!! This is a file automatically generated by hipify!!! #include <iostream> #include <cstdlib> #include <time.h> #include <hip/hip_runtime.h> #include <rocblas.h> #include <hipsparse.h> #include <minigun/minigun.h> #include "./baseline/yzh_kernels.cuh" #include "./minigun/spmm.cuh" #include "../samples_io.h" #include "../samples_utils.h" using minigun::advance::RuntimeConfig; using namespace spmm; double RunMinigun(const utils::SampleCsr& scsr, const minigun::IntSpMat& spmat, int32_t feat_size, GData& gdata, GData& truth) { hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); // create stream RuntimeConfig rtcfg; rtcfg.ctx = {kDLGPU, 0}; int nt = utils::_FindNumThreads(gdata.D, 512); rtcfg.data_num_threads = nt; rtcfg.data_num_blocks = (gdata.D + (nt * 4) - 1) / (nt * 4); CUDA_CALL(hipStreamCreate(&rtcfg.stream)); ResetGData(&gdata, scsr.row_offsets.size() - 1); // check accuracy typedef minigun::advance::Config<minigun::advance::kDst> Config; minigun::advance::Advance<kDLGPU, int32_t, float, Config, GData, SPMMFunctor>( rtcfg, spmat, &gdata); CUDA_CALL(hipDeviceSynchronize()); CheckResult(scsr, &gdata); // warm up const int K = 10; for (int i = 0; i < K; ++i) { minigun::advance::Advance<kDLGPU, int32_t, float, Config, GData, SPMMFunctor>( rtcfg, spmat, &gdata); } hipEventRecord(start); for (int i = 0; i < K; ++i) { minigun::advance::Advance<kDLGPU, int32_t, float, Config, GData, SPMMFunctor>( rtcfg, spmat, &gdata); } hipEventRecord(stop); CUDA_CALL(hipEventSynchronize(stop)); float dur = 0; hipEventElapsedTime(&dur, start, stop); return dur / K; } double RunBaseline1(const utils::SampleCsr& scsr, const minigun::IntCsr& csr, int32_t feat_size, GData& gdata, GData& truth) { const int32_t N = csr.row_offsets.length - 1; ResetGData(&gdata, N); hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); int nt = utils::_FindNumThreads(gdata.D, 512); hipLaunchKernelGGL(( custom_kernel::vector_spmm_forward_kernel_no_eid<int32_t, float>), dim3(N), dim3(nt), 0, 0, csr.row_offsets.data, csr.column_indices.data, gdata.weight, gdata.ndata, gdata.out, (int)gdata.D, (int)N); CUDA_CALL(hipDeviceSynchronize()); CheckResult(scsr, &gdata, &truth); const int K = 10; // warm up for (int i = 0; i < K; ++i) { hipLaunchKernelGGL(( custom_kernel::vector_spmm_forward_kernel_no_eid<int32_t, float>), dim3(N), dim3(nt), 0, 0, csr.row_offsets.data, csr.column_indices.data, gdata.weight, gdata.ndata, gdata.out, (int)gdata.D, (int)N); } hipEventRecord(start); for (int i = 0; i < K; ++i) { hipLaunchKernelGGL(( custom_kernel::vector_spmm_forward_kernel_no_eid<int32_t, float>), dim3(N), dim3(nt), 0, 0, csr.row_offsets.data, csr.column_indices.data, gdata.weight, gdata.ndata, gdata.out, (int)gdata.D, (int)N); } hipEventRecord(stop); CUDA_CALL(hipEventSynchronize(stop)); float dur = 0; hipEventElapsedTime(&dur, start, stop); return dur / K; } double RunBaseline2(const utils::SampleCsr& scsr, const minigun::IntCsr& csr, int32_t feat_size, GData& gdata, GData& truth) { hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); int n = csr.row_offsets.length - 1; ResetGData(&gdata, n); int k = feat_size; int nnz = scsr.row_offsets[n]; float alpha = 1.0; float beta = 0.0; hipblasStatus_t stat; hipblasHandle_t cublas_handle{nullptr}; stat = hipblasCreate(&cublas_handle); if (stat != HIPBLAS_STATUS_SUCCESS) { printf ("CUBLAS initialization failed\n"); return EXIT_FAILURE; } hipsparseStatus_t status; hipsparseHandle_t handle=0; hipsparseMatDescr_t descr=0; /* initialize cusparse library */ status= hipsparseCreate(&handle); if (status != HIPSPARSE_STATUS_SUCCESS) { printf("CUSPARSE Library initialization failed\n"); exit(-1); } /* create and setup matrix descriptor */ status= hipsparseCreateMatDescr(&descr); if (status != HIPSPARSE_STATUS_SUCCESS) { printf("Matrix descriptor initialization failed\n"); exit(-1); } hipsparseSetMatType(descr,HIPSPARSE_MATRIX_TYPE_GENERAL); hipsparseSetMatIndexBase(descr,HIPSPARSE_INDEX_BASE_ZERO); status= hipsparseScsrmm2(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, HIPSPARSE_OPERATION_TRANSPOSE, n, k, n, nnz, &alpha, descr, gdata.weight, csr.row_offsets.data, csr.column_indices.data, gdata.ndata, k, &beta, gdata.out, n); // transpose results to check correctness CUDA_CALL(hipDeviceSynchronize()); float* t; CUDA_CALL(hipMalloc(&t, sizeof(float) * n * k)); stat = hipblasSgeam(cublas_handle, HIPBLAS_OP_T, HIPBLAS_OP_N, k, n, &alpha, gdata.out, n, &beta, NULL, k, t, k); if (stat != HIPBLAS_STATUS_SUCCESS) { printf ("CUBLAS transpose failed\n"); return EXIT_FAILURE; } GData gdata2; gdata2.out = t; CheckResult(scsr, &gdata2, &truth); CUDA_CALL(hipFree(t)); CUDA_CALL(hipDeviceSynchronize()); const int K = 10; // warm up for (int i = 0; i < K; ++i) { status= hipsparseScsrmm2(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, HIPSPARSE_OPERATION_TRANSPOSE, n, k, n, nnz, &alpha, descr, gdata.weight, csr.row_offsets.data, csr.column_indices.data, gdata.ndata, k, &beta, gdata.out, n); } hipEventRecord(start); for (int i = 0; i < K; ++i) { status= hipsparseScsrmm2(handle, HIPSPARSE_OPERATION_NON_TRANSPOSE, HIPSPARSE_OPERATION_TRANSPOSE, n, k, n, nnz, &alpha, descr, gdata.weight, csr.row_offsets.data, csr.column_indices.data, gdata.ndata, k, &beta, gdata.out, n); } hipEventRecord(stop); hipEventSynchronize(stop); float dur = 0; hipEventElapsedTime(&dur, start, stop); if (status != HIPSPARSE_STATUS_SUCCESS) { printf("Matrix-vector multiplication failed\n"); exit(-1); } /* destroy matrix descriptor */ status = hipsparseDestroyMatDescr(descr); descr = 0; if (status != HIPSPARSE_STATUS_SUCCESS) { printf("Matrix descriptor destruction failed\n"); exit(-1); } /* destroy handle */ status = hipsparseDestroy(handle); handle = 0; if (status != HIPSPARSE_STATUS_SUCCESS) { printf("CUSPARSE Library release of resources failed\n"); exit(-1); } hipsparseDestroyMatDescr(descr); hipsparseDestroy(handle); hipblasDestroy(cublas_handle); return dur / K; } int main(int argc, char** argv) { // test transpose srand(42); /* // Small testing graph const int32_t a[] = {0, 2, 5, 5, 7}; const int32_t b[] = {1, 2, 0, 2, 3, 0, 1}; auto scsr = utils::SampleCsr{std::vector<int32_t>(std::begin(a), std::end(a)), std::vector<int32_t>(std::begin(b), std::end(b))}; const int feat_size = 2; */ if (argc < 3) { std::cout << "USAGE: ./bench_spmm <file_name> <feat_size>" << std::endl; return 1; } const char* filename = argv[1]; const int feat_size = std::atoi(argv[2]); //std::cout << "filename=" << filename << " feat_size=" << feat_size utils::SampleCsr scsr; utils::LoadGraphFromFile(filename, &scsr); const int32_t N = scsr.row_offsets.size() - 1; const int32_t M = scsr.column_indices.size(); //std::cout << "#Nodes: " << N << " #Edges: " << M << std::endl; // csr minigun::IntCoo coo = utils::ToMinigunCoo(scsr, kDLGPU); minigun::IntCsr csr = utils::ToMinigunCsr(scsr, kDLGPU); auto csr_mapping = utils::arange(0, M, kDLGPU); auto pack = utils::ToMinigunReverseCsr(scsr, csr_mapping, kDLGPU); minigun::IntCsr csr_t = pack.first; minigun::IntArray csr_t_mapping = pack.second; minigun::IntSpMat spmat = {&csr, &coo, &csr_t}; // gdata GData gdata, truth; gdata.D = feat_size; InitGData(scsr, csr_t_mapping, &gdata, &truth); CUDA_CALL(hipDeviceSynchronize()); //double dur1 = 0; double dur1 = RunBaseline1(scsr, csr_t, feat_size, gdata, truth); //double dur2 = 0; double dur2 = RunBaseline2(scsr, csr_t, feat_size, gdata, truth); //double dur3 = 0; double dur3 = RunMinigun(scsr, spmat, feat_size, gdata, truth); std::cout << N << "," << M << "," << feat_size << "," << dur1 << "," << dur2 << "," << dur3 << "\n"; FreeGData(&gdata, &truth); hipDeviceReset(); return 0; }
7fff923866e0cc297696d4095e01e9c53da64869.cu
#include <iostream> #include <cstdlib> #include <time.h> #include <cuda_runtime.h> #include <cublas_v2.h> #include <cusparse.h> #include <minigun/minigun.h> #include "./baseline/yzh_kernels.cuh" #include "./minigun/spmm.cuh" #include "../samples_io.h" #include "../samples_utils.h" using minigun::advance::RuntimeConfig; using namespace spmm; double RunMinigun(const utils::SampleCsr& scsr, const minigun::IntSpMat& spmat, int32_t feat_size, GData& gdata, GData& truth) { cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); // create stream RuntimeConfig rtcfg; rtcfg.ctx = {kDLGPU, 0}; int nt = utils::_FindNumThreads(gdata.D, 512); rtcfg.data_num_threads = nt; rtcfg.data_num_blocks = (gdata.D + (nt * 4) - 1) / (nt * 4); CUDA_CALL(cudaStreamCreate(&rtcfg.stream)); ResetGData(&gdata, scsr.row_offsets.size() - 1); // check accuracy typedef minigun::advance::Config<minigun::advance::kDst> Config; minigun::advance::Advance<kDLGPU, int32_t, float, Config, GData, SPMMFunctor>( rtcfg, spmat, &gdata); CUDA_CALL(cudaDeviceSynchronize()); CheckResult(scsr, &gdata); // warm up const int K = 10; for (int i = 0; i < K; ++i) { minigun::advance::Advance<kDLGPU, int32_t, float, Config, GData, SPMMFunctor>( rtcfg, spmat, &gdata); } cudaEventRecord(start); for (int i = 0; i < K; ++i) { minigun::advance::Advance<kDLGPU, int32_t, float, Config, GData, SPMMFunctor>( rtcfg, spmat, &gdata); } cudaEventRecord(stop); CUDA_CALL(cudaEventSynchronize(stop)); float dur = 0; cudaEventElapsedTime(&dur, start, stop); return dur / K; } double RunBaseline1(const utils::SampleCsr& scsr, const minigun::IntCsr& csr, int32_t feat_size, GData& gdata, GData& truth) { const int32_t N = csr.row_offsets.length - 1; ResetGData(&gdata, N); cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); int nt = utils::_FindNumThreads(gdata.D, 512); custom_kernel::vector_spmm_forward_kernel_no_eid<int32_t, float><<<N, nt>>>( csr.row_offsets.data, csr.column_indices.data, gdata.weight, gdata.ndata, gdata.out, (int)gdata.D, (int)N); CUDA_CALL(cudaDeviceSynchronize()); CheckResult(scsr, &gdata, &truth); const int K = 10; // warm up for (int i = 0; i < K; ++i) { custom_kernel::vector_spmm_forward_kernel_no_eid<int32_t, float><<<N, nt>>>( csr.row_offsets.data, csr.column_indices.data, gdata.weight, gdata.ndata, gdata.out, (int)gdata.D, (int)N); } cudaEventRecord(start); for (int i = 0; i < K; ++i) { custom_kernel::vector_spmm_forward_kernel_no_eid<int32_t, float><<<N, nt>>>( csr.row_offsets.data, csr.column_indices.data, gdata.weight, gdata.ndata, gdata.out, (int)gdata.D, (int)N); } cudaEventRecord(stop); CUDA_CALL(cudaEventSynchronize(stop)); float dur = 0; cudaEventElapsedTime(&dur, start, stop); return dur / K; } double RunBaseline2(const utils::SampleCsr& scsr, const minigun::IntCsr& csr, int32_t feat_size, GData& gdata, GData& truth) { cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); int n = csr.row_offsets.length - 1; ResetGData(&gdata, n); int k = feat_size; int nnz = scsr.row_offsets[n]; float alpha = 1.0; float beta = 0.0; cublasStatus_t stat; cublasHandle_t cublas_handle{nullptr}; stat = cublasCreate(&cublas_handle); if (stat != CUBLAS_STATUS_SUCCESS) { printf ("CUBLAS initialization failed\n"); return EXIT_FAILURE; } cusparseStatus_t status; cusparseHandle_t handle=0; cusparseMatDescr_t descr=0; /* initialize cusparse library */ status= cusparseCreate(&handle); if (status != CUSPARSE_STATUS_SUCCESS) { printf("CUSPARSE Library initialization failed\n"); exit(-1); } /* create and setup matrix descriptor */ status= cusparseCreateMatDescr(&descr); if (status != CUSPARSE_STATUS_SUCCESS) { printf("Matrix descriptor initialization failed\n"); exit(-1); } cusparseSetMatType(descr,CUSPARSE_MATRIX_TYPE_GENERAL); cusparseSetMatIndexBase(descr,CUSPARSE_INDEX_BASE_ZERO); status= cusparseScsrmm2(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, CUSPARSE_OPERATION_TRANSPOSE, n, k, n, nnz, &alpha, descr, gdata.weight, csr.row_offsets.data, csr.column_indices.data, gdata.ndata, k, &beta, gdata.out, n); // transpose results to check correctness CUDA_CALL(cudaDeviceSynchronize()); float* t; CUDA_CALL(cudaMalloc(&t, sizeof(float) * n * k)); stat = cublasSgeam(cublas_handle, CUBLAS_OP_T, CUBLAS_OP_N, k, n, &alpha, gdata.out, n, &beta, NULL, k, t, k); if (stat != CUBLAS_STATUS_SUCCESS) { printf ("CUBLAS transpose failed\n"); return EXIT_FAILURE; } GData gdata2; gdata2.out = t; CheckResult(scsr, &gdata2, &truth); CUDA_CALL(cudaFree(t)); CUDA_CALL(cudaDeviceSynchronize()); const int K = 10; // warm up for (int i = 0; i < K; ++i) { status= cusparseScsrmm2(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, CUSPARSE_OPERATION_TRANSPOSE, n, k, n, nnz, &alpha, descr, gdata.weight, csr.row_offsets.data, csr.column_indices.data, gdata.ndata, k, &beta, gdata.out, n); } cudaEventRecord(start); for (int i = 0; i < K; ++i) { status= cusparseScsrmm2(handle, CUSPARSE_OPERATION_NON_TRANSPOSE, CUSPARSE_OPERATION_TRANSPOSE, n, k, n, nnz, &alpha, descr, gdata.weight, csr.row_offsets.data, csr.column_indices.data, gdata.ndata, k, &beta, gdata.out, n); } cudaEventRecord(stop); cudaEventSynchronize(stop); float dur = 0; cudaEventElapsedTime(&dur, start, stop); if (status != CUSPARSE_STATUS_SUCCESS) { printf("Matrix-vector multiplication failed\n"); exit(-1); } /* destroy matrix descriptor */ status = cusparseDestroyMatDescr(descr); descr = 0; if (status != CUSPARSE_STATUS_SUCCESS) { printf("Matrix descriptor destruction failed\n"); exit(-1); } /* destroy handle */ status = cusparseDestroy(handle); handle = 0; if (status != CUSPARSE_STATUS_SUCCESS) { printf("CUSPARSE Library release of resources failed\n"); exit(-1); } cusparseDestroyMatDescr(descr); cusparseDestroy(handle); cublasDestroy(cublas_handle); return dur / K; } int main(int argc, char** argv) { // test transpose srand(42); /* // Small testing graph const int32_t a[] = {0, 2, 5, 5, 7}; const int32_t b[] = {1, 2, 0, 2, 3, 0, 1}; auto scsr = utils::SampleCsr{std::vector<int32_t>(std::begin(a), std::end(a)), std::vector<int32_t>(std::begin(b), std::end(b))}; const int feat_size = 2; */ if (argc < 3) { std::cout << "USAGE: ./bench_spmm <file_name> <feat_size>" << std::endl; return 1; } const char* filename = argv[1]; const int feat_size = std::atoi(argv[2]); //std::cout << "filename=" << filename << " feat_size=" << feat_size utils::SampleCsr scsr; utils::LoadGraphFromFile(filename, &scsr); const int32_t N = scsr.row_offsets.size() - 1; const int32_t M = scsr.column_indices.size(); //std::cout << "#Nodes: " << N << " #Edges: " << M << std::endl; // csr minigun::IntCoo coo = utils::ToMinigunCoo(scsr, kDLGPU); minigun::IntCsr csr = utils::ToMinigunCsr(scsr, kDLGPU); auto csr_mapping = utils::arange(0, M, kDLGPU); auto pack = utils::ToMinigunReverseCsr(scsr, csr_mapping, kDLGPU); minigun::IntCsr csr_t = pack.first; minigun::IntArray csr_t_mapping = pack.second; minigun::IntSpMat spmat = {&csr, &coo, &csr_t}; // gdata GData gdata, truth; gdata.D = feat_size; InitGData(scsr, csr_t_mapping, &gdata, &truth); CUDA_CALL(cudaDeviceSynchronize()); //double dur1 = 0; double dur1 = RunBaseline1(scsr, csr_t, feat_size, gdata, truth); //double dur2 = 0; double dur2 = RunBaseline2(scsr, csr_t, feat_size, gdata, truth); //double dur3 = 0; double dur3 = RunMinigun(scsr, spmat, feat_size, gdata, truth); std::cout << N << "," << M << "," << feat_size << "," << dur1 << "," << dur2 << "," << dur3 << "\n"; FreeGData(&gdata, &truth); cudaDeviceReset(); return 0; }
b446a0e5d87c68d984fdd5459aeb1c856455df22.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> /* * Refactor firstParallel so that it can run on the GPU. */ __global__ void firstParallel() { printf("This should be running in parallel.\n"); } int main() { /* * Refactor this call to firstParallel to execute in parallel * on the GPU. */ hipLaunchKernelGGL(( firstParallel), dim3(5),dim3(5), 0, 0, ); /* * Some code is needed below so that the CPU will wait * for the GPU kernels to complete before proceeding. */ hipDeviceSynchronize(); }
b446a0e5d87c68d984fdd5459aeb1c856455df22.cu
#include <stdio.h> /* * Refactor firstParallel so that it can run on the GPU. */ __global__ void firstParallel() { printf("This should be running in parallel.\n"); } int main() { /* * Refactor this call to firstParallel to execute in parallel * on the GPU. */ firstParallel<<<5,5>>>(); /* * Some code is needed below so that the CPU will wait * for the GPU kernels to complete before proceeding. */ cudaDeviceSynchronize(); }
0dbda6f5a23fc656abdd005ab13fbfdb5d080b2b.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* Copyright 2020 Stanford * * 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 "model.h" #include "cuda_helper.h" Tensor FFModel::unary(OperatorType op, const Tensor& x, const char *name) { ElementUnary *ele = new ElementUnary(*this, op, x, name); layers.push_back(ele); return ele->outputs[0]; } Tensor FFModel::exp(const Tensor& x, const char *name) { return this->unary(OP_EXP, x, name); } Tensor FFModel::relu(const Tensor& x, const char *name) { return this->unary(OP_RELU, x, name); } Tensor FFModel::sigmoid(const Tensor& x, const char *name) { return this->unary(OP_SIGMOID, x, name); } Tensor FFModel::tanh(const Tensor& x, const char *name) { return this->unary(OP_TANH, x, name); } Tensor FFModel::elu(const Tensor& x, const char *name) { return this->unary(OP_ELU, x, name); } ElementUnary::ElementUnary(FFModel& model, OperatorType _op_type, const Tensor& x, const char* name) : Op(model, _op_type, name, x) { outputs[0].numDim = inputs[0].numDim; for (int i = 0; i < outputs[0].numDim; i++) outputs[0].adim[i] = inputs[0].adim[i]; } bool ElementUnary::use_cudnn(OperatorType type) { if (type == OP_RELU) return true; if (type == OP_SIGMOID) return true; if (type == OP_TANH) return true; if (type == OP_ELU) return true; return false; } void ElementUnary::create_weights(FFModel& model) { // Do nothing } void ElementUnary::create_output_and_partition(FFModel& model) { int dim = inputs[0].numDim; switch (dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ task_is = model.get_or_create_task_is(DIM, name); \ create_output_and_partition_with_dim<DIM>(model); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: { // Unsupported dim for ElementWiseUnary operator assert(false); } } } template<int NDIM> void ElementUnary::create_output_and_partition_with_dim(FFModel& model) { // Retrive the task indexspace for the op task_is = IndexSpaceT<NDIM>(model.get_or_create_task_is(NDIM, name)); Context ctx = model.config.lg_ctx; Runtime* runtime = model.config.lg_hlr; Rect<NDIM> part_rect = runtime->get_index_space_domain(ctx, task_is); int dims[NDIM]; for (int i = 0; i < NDIM; i++) dims[i] = inputs[0].adim[NDIM-1-i]; outputs[0] = model.create_tensor<NDIM>(dims, DT_FLOAT, this); outputs[0].owner_op = this; outputs[0].owner_idx = 0; Rect<NDIM> input_rect; input_rect = runtime->get_index_partition_color_space( ctx, inputs[0].part.get_index_partition()); if (input_rect == part_rect) { input_lps[0] = inputs[0].part; input_grad_lps[0] = inputs[0].part_grad; } else { model.create_disjoint_partition<NDIM>( inputs[0], IndexSpaceT<NDIM>(task_is), input_lps[0], input_grad_lps[0]); } } OpMeta* ElementUnary::init_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { assert(regions.size() == 2); assert(task->regions.size() == 2); ElementUnary* eu = (ElementUnary*) task->args; FFHandler handle = *((FFHandler*) task->local_args); ElementUnaryMeta* m = new ElementUnaryMeta(handle); m->op_type = eu->op_type; m->profiling = eu->profiling; if (use_cudnn(m->op_type)) { cudnnActivationMode_t mode; switch (m->op_type) { case OP_SIGMOID: mode = CUDNN_ACTIVATION_SIGMOID; break; case OP_RELU: mode = CUDNN_ACTIVATION_RELU; break; case OP_TANH: mode = CUDNN_ACTIVATION_TANH; break; case OP_ELU: mode = CUDNN_ACTIVATION_ELU; break; default: assert(false); } checkCUDNN(cudnnSetActivationDescriptor(m->actiDesc, mode, CUDNN_PROPAGATE_NAN, 0.0)); Domain input_domain = runtime->get_index_space_domain( ctx, task->regions[0].region.get_index_space()); Domain output_domain = runtime->get_index_space_domain( ctx, task->regions[1].region.get_index_space()); checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->inputTensor, input_domain)); checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->outputTensor, output_domain)); } return m; } void ElementUnary::init(const FFModel& ff) { ArgumentMap argmap; Context ctx = ff.config.lg_ctx; Runtime* runtime = ff.config.lg_hlr; Domain domain = runtime->get_index_space_domain(ctx, task_is); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ ParallelConfig pc; \ std::string pcname = name; \ ff.config.find_parallel_config(DIM, pcname, pc); \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ FFHandler handle = ff.handlers[pc.device_ids[idx++]]; \ argmap.set_point(*it, TaskArgument(&handle, sizeof(FFHandler))); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexLauncher init_launcher(ELEMENTUNARY_INIT_TASK_ID, task_is, TaskArgument(this, sizeof(ElementUnary)), argmap, Predicate::TRUE_PRED, false/*must*/, 0/*mapper_id*/, FFConfig::get_hash_id(std::string(name))); init_launcher.add_region_requirement( RegionRequirement(input_lps[0], 0/*projection id*/, READ_ONLY, EXCLUSIVE, inputs[0].region)); init_launcher.add_field(0, FID_DATA); init_launcher.add_region_requirement( RegionRequirement(outputs[0].part, 0/*projection id*/, WRITE_ONLY, EXCLUSIVE, outputs[0].region)); init_launcher.add_field(1, FID_DATA); FutureMap fm = runtime->execute_index_space(ctx, init_launcher); fm.wait_all_results(); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ meta[idx++] = fm.get_result<OpMeta*>(*it); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } } __global__ void elewise_unary_forward_kernel(coord_t volume, const float alpha, const float beta, OperatorType type, const float* in, float* out) { CUDA_KERNEL_LOOP(i, volume) { switch (type) { case OP_EXP: { out[i] = alpha * exp(in[i]) + beta * out[i]; break; } default: assert(false); } } } /*static*/ void ElementUnary::forward_kernel(const ElementUnaryMeta* m, const float* input_ptr, float* output_ptr, size_t num_elements) { float alpha = 1.0f, beta = 0.0f; if (use_cudnn(m->op_type)) { checkCUDNN(cudnnActivationForward(m->handle.dnn, m->actiDesc, &alpha, m->inputTensor, input_ptr, &beta, m->outputTensor, output_ptr)); } else { hipLaunchKernelGGL(( elewise_unary_forward_kernel), dim3(GET_BLOCKS(num_elements)), dim3(CUDA_NUM_THREADS), 0, 0, num_elements, alpha, beta, m->op_type, input_ptr, output_ptr); } } /* regions[0](I): input regions[1](O): output */ __host__ void ElementUnary::forward_task(const Task* task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime* runtime) { assert(regions.size() == 2); assert(task->regions.size() == 2); //const ElementUnary* ele = (const ElementUnary*) task->args; const ElementUnaryMeta* m = *((ElementUnaryMeta**) task->local_args); Domain input_domain = runtime->get_index_space_domain( ctx, task->regions[0].region.get_index_space()); Domain output_domain = runtime->get_index_space_domain( ctx, task->regions[1].region.get_index_space()); assert(output_domain == input_domain); const float* input_ptr = helperGetTensorPointerRO<float>( regions[0], task->regions[0], FID_DATA, ctx, runtime); float* output_ptr = helperGetTensorPointerWO<float>( regions[1], task->regions[1], FID_DATA, ctx, runtime); #ifndef DISABLE_LEGION_CUDA_HIJACK hipStream_t stream; checkCUDA(hipStreamCreate(&stream)); checkCUDNN(cudnnSetStream(m->handle.dnn, stream)); #endif forward_kernel(m, input_ptr, output_ptr, output_domain.get_volume()); } void ElementUnary::forward(const FFModel& ff) { ArgumentMap argmap; Context ctx = ff.config.lg_ctx; Runtime* runtime = ff.config.lg_hlr; Domain domain = runtime->get_index_space_domain(ctx, task_is); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ OpMeta* mp = meta[idx++]; \ argmap.set_point(*it, TaskArgument(&mp, sizeof(OpMeta*))); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexLauncher launcher(ELEMENTUNARY_FWD_TASK_ID, task_is, TaskArgument(NULL, 0), argmap, Predicate::TRUE_PRED, false/*must*/, 0/*mapper_id*/, FFConfig::get_hash_id(std::string(name))); launcher.add_region_requirement( RegionRequirement(input_lps[0], 0/*projection id*/, READ_ONLY, EXCLUSIVE, inputs[0].region)); launcher.add_field(0, FID_DATA); launcher.add_region_requirement( RegionRequirement(outputs[0].part, 0/*projection id*/, WRITE_ONLY, EXCLUSIVE, outputs[0].region)); launcher.add_field(1, FID_DATA); runtime->execute_index_space(ctx, launcher); } __global__ void elewise_unary_backward_kernel(coord_t volume, const float alpha, const float beta, OperatorType type, const float* output_grad, const float* input, float* input_grad) { CUDA_KERNEL_LOOP(i, volume) { switch (type) { case OP_EXP: { //TODO: change to use output instead of recomputing input_grad[i] = alpha * output_grad[i] * exp(input[i]) + beta * input_grad[i]; break; } default: assert(false); } } } /*static*/ void ElementUnary::backward_kernel(const ElementUnaryMeta* m, const float* input_ptr, float* input_grad_ptr, const float* output_ptr, const float* output_grad_ptr, size_t num_elements) { float alpha = 1.0f; if (use_cudnn(m->op_type)) { checkCUDNN(cudnnActivationBackward(m->handle.dnn, m->actiDesc, &alpha, m->outputTensor, output_ptr, m->outputTensor, output_grad_ptr, m->inputTensor, input_ptr, &alpha, m->inputTensor, input_grad_ptr)); } else { hipLaunchKernelGGL(( elewise_unary_backward_kernel), dim3(GET_BLOCKS(num_elements)), dim3(CUDA_NUM_THREADS), 0, 0, num_elements, alpha, alpha, m->op_type, output_grad_ptr, input_ptr, input_grad_ptr); } } /* regions[0](I): input regions[1](I/O): input_grad regions[2](I): output regions[3](I): output_grad */ __host__ void ElementUnary::backward_task(const Task* task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime* runtime) { assert(regions.size() == 4); assert(task->regions.size() == 4); //const ElementUnary* ele = (const ElementUnary*) task->args; const ElementUnaryMeta* m = *((ElementUnaryMeta**) task->local_args); Domain input_domain = runtime->get_index_space_domain( ctx, task->regions[0].region.get_index_space()); Domain input_grad_domain = runtime->get_index_space_domain( ctx, task->regions[1].region.get_index_space()); Domain output_domain = runtime->get_index_space_domain( ctx, task->regions[2].region.get_index_space()); Domain output_grad_domain = runtime->get_index_space_domain( ctx, task->regions[3].region.get_index_space()); assert(output_grad_domain == input_domain); assert(output_grad_domain == output_domain); assert(output_grad_domain == input_grad_domain); const float* input_ptr = helperGetTensorPointerRO<float>( regions[0], task->regions[0], FID_DATA, ctx, runtime); float* input_grad_ptr = helperGetTensorPointerRW<float>( regions[1], task->regions[1], FID_DATA, ctx, runtime); const float* output_ptr = helperGetTensorPointerRO<float>( regions[2], task->regions[2], FID_DATA, ctx, runtime); const float* output_grad_ptr = helperGetTensorPointerRO<float>( regions[3], task->regions[3], FID_DATA, ctx, runtime); #ifndef DISABLE_LEGION_CUDA_HIJACK hipStream_t stream; checkCUDA(hipStreamCreate(&stream)); checkCUDNN(cudnnSetStream(m->handle.dnn, stream)); #endif backward_kernel(m, input_ptr, input_grad_ptr, output_ptr, output_grad_ptr, input_domain.get_volume()); } void ElementUnary::backward(const FFModel& ff) { ArgumentMap argmap; Context ctx = ff.config.lg_ctx; Runtime* runtime = ff.config.lg_hlr; Domain domain = runtime->get_index_space_domain(ctx, task_is); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ OpMeta* mp = meta[idx++]; \ argmap.set_point(*it, TaskArgument(&mp, sizeof(OpMeta*))); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexLauncher launcher(ELEMENTUNARY_BWD_TASK_ID, task_is, TaskArgument(NULL, 0), argmap, Predicate::TRUE_PRED, false/*must*/, 0/*mapper_id*/, FFConfig::get_hash_id(std::string(name))); // regions[0](I): input launcher.add_region_requirement( RegionRequirement(input_lps[0], 0/*projection id*/, READ_ONLY, EXCLUSIVE, inputs[0].region)); launcher.add_field(0, FID_DATA); // regions[1](I/O): input_grad launcher.add_region_requirement( RegionRequirement(input_grad_lps[0], 0/*projection id*/, READ_WRITE, EXCLUSIVE, inputs[0].region_grad)); launcher.add_field(1, FID_DATA); // regions[2](I): output_grad launcher.add_region_requirement( RegionRequirement(outputs[0].part, 0/*projection id*/, READ_ONLY, EXCLUSIVE, outputs[0].region)); launcher.add_field(2, FID_DATA); // regions[3](I): output_grad launcher.add_region_requirement( RegionRequirement(outputs[0].part_grad, 0/*projection id*/, READ_ONLY, EXCLUSIVE, outputs[0].region_grad)); launcher.add_field(3, FID_DATA); runtime->execute_index_space(ctx, launcher); } ElementUnaryMeta::ElementUnaryMeta(FFHandler handler) : OpMeta(handler) { checkCUDNN(cudnnCreateTensorDescriptor(&inputTensor)); checkCUDNN(cudnnCreateTensorDescriptor(&outputTensor)); checkCUDNN(cudnnCreateActivationDescriptor(&actiDesc)); } bool ElementUnary::measure_operator_cost(Simulator* sim, const ParallelConfig& pc, CostMetrics& cost_metrics) { Tensor sub_output, sub_input; if (!outputs[0].get_output_sub_tensor(pc, sub_output, op_type)) return false; if (!inputs[0].get_input_sub_tensor(pc, sub_input, op_type)) return false; ElementUnaryMeta* m = sim->ele_unary_meta; m->op_type = op_type; if (use_cudnn(m->op_type)) { cudnnActivationMode_t mode; switch (op_type) { case OP_SIGMOID: mode = CUDNN_ACTIVATION_SIGMOID; break; case OP_RELU: mode = CUDNN_ACTIVATION_RELU; break; case OP_TANH: mode = CUDNN_ACTIVATION_TANH; break; case OP_ELU: mode = CUDNN_ACTIVATION_ELU; break; default: assert(false); } checkCUDNN(cudnnSetActivationDescriptor(m->actiDesc, mode, CUDNN_PROPAGATE_NAN, 0.0)); Domain input_domain, output_domain; input_domain.dim = sub_input.numDim; for (int i = 0; i < sub_input.numDim; i++) { input_domain.rect_data[i] = 0; input_domain.rect_data[i+input_domain.dim] = sub_input.adim[i]-1; } output_domain.dim = sub_output.numDim; for (int i = 0; i < sub_output.numDim; i++) { output_domain.rect_data[i] = 0; output_domain.rect_data[i+input_domain.dim] = sub_output.adim[i]-1; } checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->inputTensor, input_domain)); checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->outputTensor, output_domain)); } sim->free_all(); float* input_ptr = (float*)sim->allocate(sub_input.get_volume(), DT_FLOAT); assert(input_ptr != NULL); float* output_ptr = (float*)sim->allocate(sub_output.get_volume(), DT_FLOAT); assert(output_ptr != NULL); std::function<void()> forward, backward; forward = [&] { forward_kernel(m, input_ptr, output_ptr, sub_output.get_volume()); }; if (sim->computationMode == COMP_MODE_TRAINING) { float* input_grad_ptr = (float*)sim->allocate(sub_input.get_volume(), DT_FLOAT); assert(input_grad_ptr != NULL); float* output_grad_ptr = (float*)sim->allocate(sub_output.get_volume(), DT_FLOAT); assert(output_grad_ptr != NULL); backward = [&] { backward_kernel(m, input_ptr, input_grad_ptr, output_ptr, output_grad_ptr, sub_output.get_volume()); }; } inner_measure_operator_cost(sim, forward, backward, cost_metrics); if (sim->computationMode == COMP_MODE_TRAINING) { printf("[Measure Elewise Unary] name(%s) num_elements(%zu) forward_time(%.4lf) backward_time(%.4lf)\n", name, sub_output.get_volume(), cost_metrics.forward_time, cost_metrics.backward_time); } else { printf("[Measure Elewise Unary] name(%s) num_elements(%zu) forward_time(%.4lf)\n", name, sub_output.get_volume(), cost_metrics.forward_time); } return true; }
0dbda6f5a23fc656abdd005ab13fbfdb5d080b2b.cu
/* Copyright 2020 Stanford * * 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 "model.h" #include "cuda_helper.h" Tensor FFModel::unary(OperatorType op, const Tensor& x, const char *name) { ElementUnary *ele = new ElementUnary(*this, op, x, name); layers.push_back(ele); return ele->outputs[0]; } Tensor FFModel::exp(const Tensor& x, const char *name) { return this->unary(OP_EXP, x, name); } Tensor FFModel::relu(const Tensor& x, const char *name) { return this->unary(OP_RELU, x, name); } Tensor FFModel::sigmoid(const Tensor& x, const char *name) { return this->unary(OP_SIGMOID, x, name); } Tensor FFModel::tanh(const Tensor& x, const char *name) { return this->unary(OP_TANH, x, name); } Tensor FFModel::elu(const Tensor& x, const char *name) { return this->unary(OP_ELU, x, name); } ElementUnary::ElementUnary(FFModel& model, OperatorType _op_type, const Tensor& x, const char* name) : Op(model, _op_type, name, x) { outputs[0].numDim = inputs[0].numDim; for (int i = 0; i < outputs[0].numDim; i++) outputs[0].adim[i] = inputs[0].adim[i]; } bool ElementUnary::use_cudnn(OperatorType type) { if (type == OP_RELU) return true; if (type == OP_SIGMOID) return true; if (type == OP_TANH) return true; if (type == OP_ELU) return true; return false; } void ElementUnary::create_weights(FFModel& model) { // Do nothing } void ElementUnary::create_output_and_partition(FFModel& model) { int dim = inputs[0].numDim; switch (dim) { #define DIMFUNC(DIM) \ case DIM: \ { \ task_is = model.get_or_create_task_is(DIM, name); \ create_output_and_partition_with_dim<DIM>(model); \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: { // Unsupported dim for ElementWiseUnary operator assert(false); } } } template<int NDIM> void ElementUnary::create_output_and_partition_with_dim(FFModel& model) { // Retrive the task indexspace for the op task_is = IndexSpaceT<NDIM>(model.get_or_create_task_is(NDIM, name)); Context ctx = model.config.lg_ctx; Runtime* runtime = model.config.lg_hlr; Rect<NDIM> part_rect = runtime->get_index_space_domain(ctx, task_is); int dims[NDIM]; for (int i = 0; i < NDIM; i++) dims[i] = inputs[0].adim[NDIM-1-i]; outputs[0] = model.create_tensor<NDIM>(dims, DT_FLOAT, this); outputs[0].owner_op = this; outputs[0].owner_idx = 0; Rect<NDIM> input_rect; input_rect = runtime->get_index_partition_color_space( ctx, inputs[0].part.get_index_partition()); if (input_rect == part_rect) { input_lps[0] = inputs[0].part; input_grad_lps[0] = inputs[0].part_grad; } else { model.create_disjoint_partition<NDIM>( inputs[0], IndexSpaceT<NDIM>(task_is), input_lps[0], input_grad_lps[0]); } } OpMeta* ElementUnary::init_task(const Task *task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime *runtime) { assert(regions.size() == 2); assert(task->regions.size() == 2); ElementUnary* eu = (ElementUnary*) task->args; FFHandler handle = *((FFHandler*) task->local_args); ElementUnaryMeta* m = new ElementUnaryMeta(handle); m->op_type = eu->op_type; m->profiling = eu->profiling; if (use_cudnn(m->op_type)) { cudnnActivationMode_t mode; switch (m->op_type) { case OP_SIGMOID: mode = CUDNN_ACTIVATION_SIGMOID; break; case OP_RELU: mode = CUDNN_ACTIVATION_RELU; break; case OP_TANH: mode = CUDNN_ACTIVATION_TANH; break; case OP_ELU: mode = CUDNN_ACTIVATION_ELU; break; default: assert(false); } checkCUDNN(cudnnSetActivationDescriptor(m->actiDesc, mode, CUDNN_PROPAGATE_NAN, 0.0)); Domain input_domain = runtime->get_index_space_domain( ctx, task->regions[0].region.get_index_space()); Domain output_domain = runtime->get_index_space_domain( ctx, task->regions[1].region.get_index_space()); checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->inputTensor, input_domain)); checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->outputTensor, output_domain)); } return m; } void ElementUnary::init(const FFModel& ff) { ArgumentMap argmap; Context ctx = ff.config.lg_ctx; Runtime* runtime = ff.config.lg_hlr; Domain domain = runtime->get_index_space_domain(ctx, task_is); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ ParallelConfig pc; \ std::string pcname = name; \ ff.config.find_parallel_config(DIM, pcname, pc); \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ FFHandler handle = ff.handlers[pc.device_ids[idx++]]; \ argmap.set_point(*it, TaskArgument(&handle, sizeof(FFHandler))); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexLauncher init_launcher(ELEMENTUNARY_INIT_TASK_ID, task_is, TaskArgument(this, sizeof(ElementUnary)), argmap, Predicate::TRUE_PRED, false/*must*/, 0/*mapper_id*/, FFConfig::get_hash_id(std::string(name))); init_launcher.add_region_requirement( RegionRequirement(input_lps[0], 0/*projection id*/, READ_ONLY, EXCLUSIVE, inputs[0].region)); init_launcher.add_field(0, FID_DATA); init_launcher.add_region_requirement( RegionRequirement(outputs[0].part, 0/*projection id*/, WRITE_ONLY, EXCLUSIVE, outputs[0].region)); init_launcher.add_field(1, FID_DATA); FutureMap fm = runtime->execute_index_space(ctx, init_launcher); fm.wait_all_results(); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ meta[idx++] = fm.get_result<OpMeta*>(*it); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } } __global__ void elewise_unary_forward_kernel(coord_t volume, const float alpha, const float beta, OperatorType type, const float* in, float* out) { CUDA_KERNEL_LOOP(i, volume) { switch (type) { case OP_EXP: { out[i] = alpha * exp(in[i]) + beta * out[i]; break; } default: assert(false); } } } /*static*/ void ElementUnary::forward_kernel(const ElementUnaryMeta* m, const float* input_ptr, float* output_ptr, size_t num_elements) { float alpha = 1.0f, beta = 0.0f; if (use_cudnn(m->op_type)) { checkCUDNN(cudnnActivationForward(m->handle.dnn, m->actiDesc, &alpha, m->inputTensor, input_ptr, &beta, m->outputTensor, output_ptr)); } else { elewise_unary_forward_kernel<<<GET_BLOCKS(num_elements), CUDA_NUM_THREADS>>>( num_elements, alpha, beta, m->op_type, input_ptr, output_ptr); } } /* regions[0](I): input regions[1](O): output */ __host__ void ElementUnary::forward_task(const Task* task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime* runtime) { assert(regions.size() == 2); assert(task->regions.size() == 2); //const ElementUnary* ele = (const ElementUnary*) task->args; const ElementUnaryMeta* m = *((ElementUnaryMeta**) task->local_args); Domain input_domain = runtime->get_index_space_domain( ctx, task->regions[0].region.get_index_space()); Domain output_domain = runtime->get_index_space_domain( ctx, task->regions[1].region.get_index_space()); assert(output_domain == input_domain); const float* input_ptr = helperGetTensorPointerRO<float>( regions[0], task->regions[0], FID_DATA, ctx, runtime); float* output_ptr = helperGetTensorPointerWO<float>( regions[1], task->regions[1], FID_DATA, ctx, runtime); #ifndef DISABLE_LEGION_CUDA_HIJACK cudaStream_t stream; checkCUDA(cudaStreamCreate(&stream)); checkCUDNN(cudnnSetStream(m->handle.dnn, stream)); #endif forward_kernel(m, input_ptr, output_ptr, output_domain.get_volume()); } void ElementUnary::forward(const FFModel& ff) { ArgumentMap argmap; Context ctx = ff.config.lg_ctx; Runtime* runtime = ff.config.lg_hlr; Domain domain = runtime->get_index_space_domain(ctx, task_is); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ OpMeta* mp = meta[idx++]; \ argmap.set_point(*it, TaskArgument(&mp, sizeof(OpMeta*))); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexLauncher launcher(ELEMENTUNARY_FWD_TASK_ID, task_is, TaskArgument(NULL, 0), argmap, Predicate::TRUE_PRED, false/*must*/, 0/*mapper_id*/, FFConfig::get_hash_id(std::string(name))); launcher.add_region_requirement( RegionRequirement(input_lps[0], 0/*projection id*/, READ_ONLY, EXCLUSIVE, inputs[0].region)); launcher.add_field(0, FID_DATA); launcher.add_region_requirement( RegionRequirement(outputs[0].part, 0/*projection id*/, WRITE_ONLY, EXCLUSIVE, outputs[0].region)); launcher.add_field(1, FID_DATA); runtime->execute_index_space(ctx, launcher); } __global__ void elewise_unary_backward_kernel(coord_t volume, const float alpha, const float beta, OperatorType type, const float* output_grad, const float* input, float* input_grad) { CUDA_KERNEL_LOOP(i, volume) { switch (type) { case OP_EXP: { //TODO: change to use output instead of recomputing input_grad[i] = alpha * output_grad[i] * exp(input[i]) + beta * input_grad[i]; break; } default: assert(false); } } } /*static*/ void ElementUnary::backward_kernel(const ElementUnaryMeta* m, const float* input_ptr, float* input_grad_ptr, const float* output_ptr, const float* output_grad_ptr, size_t num_elements) { float alpha = 1.0f; if (use_cudnn(m->op_type)) { checkCUDNN(cudnnActivationBackward(m->handle.dnn, m->actiDesc, &alpha, m->outputTensor, output_ptr, m->outputTensor, output_grad_ptr, m->inputTensor, input_ptr, &alpha, m->inputTensor, input_grad_ptr)); } else { elewise_unary_backward_kernel<<<GET_BLOCKS(num_elements), CUDA_NUM_THREADS>>>( num_elements, alpha, alpha, m->op_type, output_grad_ptr, input_ptr, input_grad_ptr); } } /* regions[0](I): input regions[1](I/O): input_grad regions[2](I): output regions[3](I): output_grad */ __host__ void ElementUnary::backward_task(const Task* task, const std::vector<PhysicalRegion> &regions, Context ctx, Runtime* runtime) { assert(regions.size() == 4); assert(task->regions.size() == 4); //const ElementUnary* ele = (const ElementUnary*) task->args; const ElementUnaryMeta* m = *((ElementUnaryMeta**) task->local_args); Domain input_domain = runtime->get_index_space_domain( ctx, task->regions[0].region.get_index_space()); Domain input_grad_domain = runtime->get_index_space_domain( ctx, task->regions[1].region.get_index_space()); Domain output_domain = runtime->get_index_space_domain( ctx, task->regions[2].region.get_index_space()); Domain output_grad_domain = runtime->get_index_space_domain( ctx, task->regions[3].region.get_index_space()); assert(output_grad_domain == input_domain); assert(output_grad_domain == output_domain); assert(output_grad_domain == input_grad_domain); const float* input_ptr = helperGetTensorPointerRO<float>( regions[0], task->regions[0], FID_DATA, ctx, runtime); float* input_grad_ptr = helperGetTensorPointerRW<float>( regions[1], task->regions[1], FID_DATA, ctx, runtime); const float* output_ptr = helperGetTensorPointerRO<float>( regions[2], task->regions[2], FID_DATA, ctx, runtime); const float* output_grad_ptr = helperGetTensorPointerRO<float>( regions[3], task->regions[3], FID_DATA, ctx, runtime); #ifndef DISABLE_LEGION_CUDA_HIJACK cudaStream_t stream; checkCUDA(cudaStreamCreate(&stream)); checkCUDNN(cudnnSetStream(m->handle.dnn, stream)); #endif backward_kernel(m, input_ptr, input_grad_ptr, output_ptr, output_grad_ptr, input_domain.get_volume()); } void ElementUnary::backward(const FFModel& ff) { ArgumentMap argmap; Context ctx = ff.config.lg_ctx; Runtime* runtime = ff.config.lg_hlr; Domain domain = runtime->get_index_space_domain(ctx, task_is); switch (domain.get_dim()) { #define DIMFUNC(DIM) \ case DIM: \ { \ Rect<DIM> rect = domain; \ int idx = 0; \ for (PointInRectIterator<DIM> it(rect); it(); it++) { \ OpMeta* mp = meta[idx++]; \ argmap.set_point(*it, TaskArgument(&mp, sizeof(OpMeta*))); \ } \ break; \ } LEGION_FOREACH_N(DIMFUNC) #undef DIMFUNC default: assert(false); } IndexLauncher launcher(ELEMENTUNARY_BWD_TASK_ID, task_is, TaskArgument(NULL, 0), argmap, Predicate::TRUE_PRED, false/*must*/, 0/*mapper_id*/, FFConfig::get_hash_id(std::string(name))); // regions[0](I): input launcher.add_region_requirement( RegionRequirement(input_lps[0], 0/*projection id*/, READ_ONLY, EXCLUSIVE, inputs[0].region)); launcher.add_field(0, FID_DATA); // regions[1](I/O): input_grad launcher.add_region_requirement( RegionRequirement(input_grad_lps[0], 0/*projection id*/, READ_WRITE, EXCLUSIVE, inputs[0].region_grad)); launcher.add_field(1, FID_DATA); // regions[2](I): output_grad launcher.add_region_requirement( RegionRequirement(outputs[0].part, 0/*projection id*/, READ_ONLY, EXCLUSIVE, outputs[0].region)); launcher.add_field(2, FID_DATA); // regions[3](I): output_grad launcher.add_region_requirement( RegionRequirement(outputs[0].part_grad, 0/*projection id*/, READ_ONLY, EXCLUSIVE, outputs[0].region_grad)); launcher.add_field(3, FID_DATA); runtime->execute_index_space(ctx, launcher); } ElementUnaryMeta::ElementUnaryMeta(FFHandler handler) : OpMeta(handler) { checkCUDNN(cudnnCreateTensorDescriptor(&inputTensor)); checkCUDNN(cudnnCreateTensorDescriptor(&outputTensor)); checkCUDNN(cudnnCreateActivationDescriptor(&actiDesc)); } bool ElementUnary::measure_operator_cost(Simulator* sim, const ParallelConfig& pc, CostMetrics& cost_metrics) { Tensor sub_output, sub_input; if (!outputs[0].get_output_sub_tensor(pc, sub_output, op_type)) return false; if (!inputs[0].get_input_sub_tensor(pc, sub_input, op_type)) return false; ElementUnaryMeta* m = sim->ele_unary_meta; m->op_type = op_type; if (use_cudnn(m->op_type)) { cudnnActivationMode_t mode; switch (op_type) { case OP_SIGMOID: mode = CUDNN_ACTIVATION_SIGMOID; break; case OP_RELU: mode = CUDNN_ACTIVATION_RELU; break; case OP_TANH: mode = CUDNN_ACTIVATION_TANH; break; case OP_ELU: mode = CUDNN_ACTIVATION_ELU; break; default: assert(false); } checkCUDNN(cudnnSetActivationDescriptor(m->actiDesc, mode, CUDNN_PROPAGATE_NAN, 0.0)); Domain input_domain, output_domain; input_domain.dim = sub_input.numDim; for (int i = 0; i < sub_input.numDim; i++) { input_domain.rect_data[i] = 0; input_domain.rect_data[i+input_domain.dim] = sub_input.adim[i]-1; } output_domain.dim = sub_output.numDim; for (int i = 0; i < sub_output.numDim; i++) { output_domain.rect_data[i] = 0; output_domain.rect_data[i+input_domain.dim] = sub_output.adim[i]-1; } checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->inputTensor, input_domain)); checkCUDNN(cudnnSetTensorDescriptorFromDomain(m->outputTensor, output_domain)); } sim->free_all(); float* input_ptr = (float*)sim->allocate(sub_input.get_volume(), DT_FLOAT); assert(input_ptr != NULL); float* output_ptr = (float*)sim->allocate(sub_output.get_volume(), DT_FLOAT); assert(output_ptr != NULL); std::function<void()> forward, backward; forward = [&] { forward_kernel(m, input_ptr, output_ptr, sub_output.get_volume()); }; if (sim->computationMode == COMP_MODE_TRAINING) { float* input_grad_ptr = (float*)sim->allocate(sub_input.get_volume(), DT_FLOAT); assert(input_grad_ptr != NULL); float* output_grad_ptr = (float*)sim->allocate(sub_output.get_volume(), DT_FLOAT); assert(output_grad_ptr != NULL); backward = [&] { backward_kernel(m, input_ptr, input_grad_ptr, output_ptr, output_grad_ptr, sub_output.get_volume()); }; } inner_measure_operator_cost(sim, forward, backward, cost_metrics); if (sim->computationMode == COMP_MODE_TRAINING) { printf("[Measure Elewise Unary] name(%s) num_elements(%zu) forward_time(%.4lf) backward_time(%.4lf)\n", name, sub_output.get_volume(), cost_metrics.forward_time, cost_metrics.backward_time); } else { printf("[Measure Elewise Unary] name(%s) num_elements(%zu) forward_time(%.4lf)\n", name, sub_output.get_volume(), cost_metrics.forward_time); } return true; }
92d5b0c59fd7a3f06438419ebdfec4c4af8b9126.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // // auto-generated by op2.m on 12-Jun-2012 19:14:41 // // user function __device__ #include "updateP.h" // CUDA kernel function __global__ void op_cuda_updateP( double *arg0, double *arg1, const double *arg2, int offset_s, int set_size ) { // process set elements for (int n=threadIdx.x+blockIdx.x*blockDim.x; n<set_size; n+=blockDim.x*gridDim.x) { // user-supplied kernel call updateP( arg0+n, arg1+n, arg2 ); } } // host stub function void op_par_loop_updateP(char const *name, op_set set, op_arg arg0, op_arg arg1, op_arg arg2 ){ double *arg2h = (double *)arg2.data; int nargs = 3; op_arg args[3]; args[0] = arg0; args[1] = arg1; args[2] = arg2; if (OP_diags>2) { printf(" kernel routine w/o indirection: updateP\n"); } op_mpi_halo_exchanges(set, nargs, args); // initialise timers double cpu_t1, cpu_t2, wall_t1, wall_t2; op_timers_core(&cpu_t1, &wall_t1); if (set->size >0) { // transfer constants to GPU int consts_bytes = 0; consts_bytes += ROUND_UP(1*sizeof(double)); reallocConstArrays(consts_bytes); consts_bytes = 0; arg2.data = OP_consts_h + consts_bytes; arg2.data_d = OP_consts_d + consts_bytes; for (int d=0; d<1; d++) ((double *)arg2.data)[d] = arg2h[d]; consts_bytes += ROUND_UP(1*sizeof(double)); mvConstArraysToDevice(consts_bytes); // set CUDA execution parameters #ifdef OP_BLOCK_SIZE_7 int nthread = OP_BLOCK_SIZE_7; #else // int nthread = OP_block_size; int nthread = 128; #endif int nblocks = 200; // work out shared memory requirements per element int nshared = 0; // execute plan int offset_s = nshared*OP_WARPSIZE; nshared = nshared*nthread; hipLaunchKernelGGL(( op_cuda_updateP), dim3(nblocks),dim3(nthread),nshared, 0, (double *) arg0.data_d, (double *) arg1.data_d, (double *) arg2.data_d, offset_s, set->size ); cutilSafeCall(hipDeviceSynchronize()); cutilCheckMsg("op_cuda_updateP execution failed\n"); } op_mpi_set_dirtybit(nargs, args); // update kernel record op_timers_core(&cpu_t2, &wall_t2); op_timing_realloc(7); OP_kernels[7].name = name; OP_kernels[7].count += 1; OP_kernels[7].time += wall_t2 - wall_t1; OP_kernels[7].transfer += (float)set->size * arg0.size; OP_kernels[7].transfer += (float)set->size * arg1.size * 2.0f; }
92d5b0c59fd7a3f06438419ebdfec4c4af8b9126.cu
// // auto-generated by op2.m on 12-Jun-2012 19:14:41 // // user function __device__ #include "updateP.h" // CUDA kernel function __global__ void op_cuda_updateP( double *arg0, double *arg1, const double *arg2, int offset_s, int set_size ) { // process set elements for (int n=threadIdx.x+blockIdx.x*blockDim.x; n<set_size; n+=blockDim.x*gridDim.x) { // user-supplied kernel call updateP( arg0+n, arg1+n, arg2 ); } } // host stub function void op_par_loop_updateP(char const *name, op_set set, op_arg arg0, op_arg arg1, op_arg arg2 ){ double *arg2h = (double *)arg2.data; int nargs = 3; op_arg args[3]; args[0] = arg0; args[1] = arg1; args[2] = arg2; if (OP_diags>2) { printf(" kernel routine w/o indirection: updateP\n"); } op_mpi_halo_exchanges(set, nargs, args); // initialise timers double cpu_t1, cpu_t2, wall_t1, wall_t2; op_timers_core(&cpu_t1, &wall_t1); if (set->size >0) { // transfer constants to GPU int consts_bytes = 0; consts_bytes += ROUND_UP(1*sizeof(double)); reallocConstArrays(consts_bytes); consts_bytes = 0; arg2.data = OP_consts_h + consts_bytes; arg2.data_d = OP_consts_d + consts_bytes; for (int d=0; d<1; d++) ((double *)arg2.data)[d] = arg2h[d]; consts_bytes += ROUND_UP(1*sizeof(double)); mvConstArraysToDevice(consts_bytes); // set CUDA execution parameters #ifdef OP_BLOCK_SIZE_7 int nthread = OP_BLOCK_SIZE_7; #else // int nthread = OP_block_size; int nthread = 128; #endif int nblocks = 200; // work out shared memory requirements per element int nshared = 0; // execute plan int offset_s = nshared*OP_WARPSIZE; nshared = nshared*nthread; op_cuda_updateP<<<nblocks,nthread,nshared>>>( (double *) arg0.data_d, (double *) arg1.data_d, (double *) arg2.data_d, offset_s, set->size ); cutilSafeCall(cudaThreadSynchronize()); cutilCheckMsg("op_cuda_updateP execution failed\n"); } op_mpi_set_dirtybit(nargs, args); // update kernel record op_timers_core(&cpu_t2, &wall_t2); op_timing_realloc(7); OP_kernels[7].name = name; OP_kernels[7].count += 1; OP_kernels[7].time += wall_t2 - wall_t1; OP_kernels[7].transfer += (float)set->size * arg0.size; OP_kernels[7].transfer += (float)set->size * arg1.size * 2.0f; }
acde7e5651a28060876652dcfef0b947d660cc14.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /** * Given some kernel with positional arguments (n -> columns, m -> rows), below * is how to calculate the row/col being worked on and the index into a * linearized matrix. See also http://en.wikipedia.org/wiki/Row-major_order */ __global__ void SomeKernel(float * d_in, float * d_out, int cols, int rows) { int colIdx = blockIdx.x*blockDim.x + threadIdx.x; int rowIdx = blockIdx.y*blockDim.y + threadIdx.y; // ensure we are in a valid row/col, needed because we have generated more // threads than needed. if ((rowIdx < rows) && (colIdx < cols)) { // linearize the index to access d_in/d_out. This is needed because an NxM // (colsXrows) matrix is linearized into a continguous address space. This // simple calculation gives you the index into a linearized 2 dimensional // array. Row*Width+Col is linear index. int idx = rowIdx*cols + colIdx; } }
acde7e5651a28060876652dcfef0b947d660cc14.cu
/** * Given some kernel with positional arguments (n -> columns, m -> rows), below * is how to calculate the row/col being worked on and the index into a * linearized matrix. See also http://en.wikipedia.org/wiki/Row-major_order */ __global__ void SomeKernel(float * d_in, float * d_out, int cols, int rows) { int colIdx = blockIdx.x*blockDim.x + threadIdx.x; int rowIdx = blockIdx.y*blockDim.y + threadIdx.y; // ensure we are in a valid row/col, needed because we have generated more // threads than needed. if ((rowIdx < rows) && (colIdx < cols)) { // linearize the index to access d_in/d_out. This is needed because an NxM // (colsXrows) matrix is linearized into a continguous address space. This // simple calculation gives you the index into a linearized 2 dimensional // array. Row*Width+Col is linear index. int idx = rowIdx*cols + colIdx; } }
1d4f3951904c098e813e0f3ce7c98f9d9634667e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <algorithm> #include <cfloat> #include <vector> #include "thrust/device_vector.h" #include "caffe/layers/softmax_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> __global__ void kernel_channel_max(const int num, const int channels, const int spatial_dim, const Dtype* data, Dtype* out) { CUDA_KERNEL_LOOP(index, num * spatial_dim) { int n = index / spatial_dim; int s = index % spatial_dim; Dtype maxval = -FLT_MAX; for (int c = 0; c < channels; ++c) { maxval = max(data[(n * channels + c) * spatial_dim + s], maxval); } out[index] = maxval; } } template <typename Dtype> __global__ void kernel_channel_subtract(const int count, const int num, const int channels, const int spatial_dim, const Dtype* channel_max, Dtype* data) { CUDA_KERNEL_LOOP(index, count) { int n = index / channels / spatial_dim; int s = index % spatial_dim; data[index] -= channel_max[n * spatial_dim + s]; } } template <typename Dtype> __global__ void kernel_exp(const int count, const Dtype* data, Dtype* out) { CUDA_KERNEL_LOOP(index, count) { out[index] = exp(data[index]); } } template <typename Dtype> __global__ void kernel_channel_sum(const int num, const int channels, const int spatial_dim, const Dtype* data, Dtype* channel_sum) { CUDA_KERNEL_LOOP(index, num * spatial_dim) { int n = index / spatial_dim; int s = index % spatial_dim; Dtype sum = 0; for (int c = 0; c < channels; ++c) { sum += data[(n * channels + c) * spatial_dim + s]; } channel_sum[index] = sum; } } template <typename Dtype> __global__ void kernel_channel_div(const int count, const int num, const int channels, const int spatial_dim, const Dtype* channel_sum, Dtype* data) { CUDA_KERNEL_LOOP(index, count) { int n = index / channels / spatial_dim; int s = index % spatial_dim; data[index] /= channel_sum[n * spatial_dim + s]; } } template <typename Dtype> __global__ void kernel_channel_dot(const int num, const int channels, const int spatial_dim, const Dtype* data_1, const Dtype* data_2, Dtype* channel_dot) { CUDA_KERNEL_LOOP(index, num * spatial_dim) { int n = index / spatial_dim; int s = index % spatial_dim; Dtype dot = 0; for (int c = 0; c < channels; ++c) { dot += (data_1[(n * channels + c) * spatial_dim + s] * data_2[(n * channels + c) * spatial_dim + s]); } channel_dot[index] = dot; } } template <typename Dtype> void SoftmaxLayer<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(); Dtype* scale_data = scale_.mutable_gpu_data(); int count = bottom[0]->count(); int channels = top[0]->shape(softmax_axis_); caffe_copy(count, bottom_data, top_data, 3); // We need to subtract the max to avoid numerical issues, compute the exp, // and then normalize. // compute max // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( kernel_channel_max<Dtype>), dim3(CAFFE_GET_BLOCKS(outer_num_ * inner_num_)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, outer_num_, channels, inner_num_, top_data, scale_data); // subtract // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( kernel_channel_subtract<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, count, outer_num_, channels, inner_num_, scale_data, top_data); // exponentiate // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( kernel_exp<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, count, top_data, top_data); // sum after exp // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( kernel_channel_sum<Dtype>), dim3(CAFFE_GET_BLOCKS(outer_num_ * inner_num_)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, outer_num_, channels, inner_num_, top_data, scale_data); // divide // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( kernel_channel_div<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, count, outer_num_, channels, inner_num_, scale_data, top_data); } template <typename Dtype> void SoftmaxLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* top_diff = top[0]->gpu_diff(); const Dtype* top_data = top[0]->gpu_data(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); Dtype* scale_data = scale_.mutable_gpu_data(); int count = top[0]->count(); int channels = top[0]->shape(softmax_axis_); caffe_copy(count, top_diff, bottom_diff, 3); // Compute inner1d(top_diff, top_data) and subtract them from the bottom diff. // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( kernel_channel_dot<Dtype>), dim3(CAFFE_GET_BLOCKS(outer_num_ * inner_num_)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, outer_num_, channels, inner_num_, top_diff, top_data, scale_data); // NOLINT_NEXT_LINE(whitespace/operators) hipLaunchKernelGGL(( kernel_channel_subtract<Dtype>), dim3(CAFFE_GET_BLOCKS(count)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, count, outer_num_, channels, inner_num_, scale_data, bottom_diff); // elementwise multiplication caffe_gpu_mul<Dtype>(top[0]->count(), bottom_diff, top_data, bottom_diff); } INSTANTIATE_LAYER_GPU_FUNCS(SoftmaxLayer); } // namespace caffe
1d4f3951904c098e813e0f3ce7c98f9d9634667e.cu
#include <algorithm> #include <cfloat> #include <vector> #include "thrust/device_vector.h" #include "caffe/layers/softmax_layer.hpp" #include "caffe/util/math_functions.hpp" namespace caffe { template <typename Dtype> __global__ void kernel_channel_max(const int num, const int channels, const int spatial_dim, const Dtype* data, Dtype* out) { CUDA_KERNEL_LOOP(index, num * spatial_dim) { int n = index / spatial_dim; int s = index % spatial_dim; Dtype maxval = -FLT_MAX; for (int c = 0; c < channels; ++c) { maxval = max(data[(n * channels + c) * spatial_dim + s], maxval); } out[index] = maxval; } } template <typename Dtype> __global__ void kernel_channel_subtract(const int count, const int num, const int channels, const int spatial_dim, const Dtype* channel_max, Dtype* data) { CUDA_KERNEL_LOOP(index, count) { int n = index / channels / spatial_dim; int s = index % spatial_dim; data[index] -= channel_max[n * spatial_dim + s]; } } template <typename Dtype> __global__ void kernel_exp(const int count, const Dtype* data, Dtype* out) { CUDA_KERNEL_LOOP(index, count) { out[index] = exp(data[index]); } } template <typename Dtype> __global__ void kernel_channel_sum(const int num, const int channels, const int spatial_dim, const Dtype* data, Dtype* channel_sum) { CUDA_KERNEL_LOOP(index, num * spatial_dim) { int n = index / spatial_dim; int s = index % spatial_dim; Dtype sum = 0; for (int c = 0; c < channels; ++c) { sum += data[(n * channels + c) * spatial_dim + s]; } channel_sum[index] = sum; } } template <typename Dtype> __global__ void kernel_channel_div(const int count, const int num, const int channels, const int spatial_dim, const Dtype* channel_sum, Dtype* data) { CUDA_KERNEL_LOOP(index, count) { int n = index / channels / spatial_dim; int s = index % spatial_dim; data[index] /= channel_sum[n * spatial_dim + s]; } } template <typename Dtype> __global__ void kernel_channel_dot(const int num, const int channels, const int spatial_dim, const Dtype* data_1, const Dtype* data_2, Dtype* channel_dot) { CUDA_KERNEL_LOOP(index, num * spatial_dim) { int n = index / spatial_dim; int s = index % spatial_dim; Dtype dot = 0; for (int c = 0; c < channels; ++c) { dot += (data_1[(n * channels + c) * spatial_dim + s] * data_2[(n * channels + c) * spatial_dim + s]); } channel_dot[index] = dot; } } template <typename Dtype> void SoftmaxLayer<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(); Dtype* scale_data = scale_.mutable_gpu_data(); int count = bottom[0]->count(); int channels = top[0]->shape(softmax_axis_); caffe_copy(count, bottom_data, top_data, 3); // We need to subtract the max to avoid numerical issues, compute the exp, // and then normalize. // compute max // NOLINT_NEXT_LINE(whitespace/operators) kernel_channel_max<Dtype><<<CAFFE_GET_BLOCKS(outer_num_ * inner_num_), CAFFE_CUDA_NUM_THREADS>>>(outer_num_, channels, inner_num_, top_data, scale_data); // subtract // NOLINT_NEXT_LINE(whitespace/operators) kernel_channel_subtract<Dtype><<<CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS>>>(count, outer_num_, channels, inner_num_, scale_data, top_data); // exponentiate // NOLINT_NEXT_LINE(whitespace/operators) kernel_exp<Dtype><<<CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS>>>( count, top_data, top_data); // sum after exp // NOLINT_NEXT_LINE(whitespace/operators) kernel_channel_sum<Dtype><<<CAFFE_GET_BLOCKS(outer_num_ * inner_num_), CAFFE_CUDA_NUM_THREADS>>>(outer_num_, channels, inner_num_, top_data, scale_data); // divide // NOLINT_NEXT_LINE(whitespace/operators) kernel_channel_div<Dtype><<<CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS>>>(count, outer_num_, channels, inner_num_, scale_data, top_data); } template <typename Dtype> void SoftmaxLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { const Dtype* top_diff = top[0]->gpu_diff(); const Dtype* top_data = top[0]->gpu_data(); Dtype* bottom_diff = bottom[0]->mutable_gpu_diff(); Dtype* scale_data = scale_.mutable_gpu_data(); int count = top[0]->count(); int channels = top[0]->shape(softmax_axis_); caffe_copy(count, top_diff, bottom_diff, 3); // Compute inner1d(top_diff, top_data) and subtract them from the bottom diff. // NOLINT_NEXT_LINE(whitespace/operators) kernel_channel_dot<Dtype><<<CAFFE_GET_BLOCKS(outer_num_ * inner_num_), CAFFE_CUDA_NUM_THREADS>>>(outer_num_, channels, inner_num_, top_diff, top_data, scale_data); // NOLINT_NEXT_LINE(whitespace/operators) kernel_channel_subtract<Dtype><<<CAFFE_GET_BLOCKS(count), CAFFE_CUDA_NUM_THREADS>>>(count, outer_num_, channels, inner_num_, scale_data, bottom_diff); // elementwise multiplication caffe_gpu_mul<Dtype>(top[0]->count(), bottom_diff, top_data, bottom_diff); } INSTANTIATE_LAYER_GPU_FUNCS(SoftmaxLayer); } // namespace caffe
76f2baa0c04314f8711429bafc091c67db32478a.hip
// !!! This is a file automatically generated by hipify!!! /*** Copyright (c) 2015, 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 "xmp.h" #include <stdio.h> #include <stdlib.h> #include <fstream> #include <hip/hip_runtime_api.h> #include<stdint.h> #include<iostream> #include <cinttypes> #define XMP_CHECK_ERROR(fun) \ { \ xmpError_t error=fun; \ if(error!=xmpErrorSuccess){ \ if(error==xmpErrorCuda) \ printf("CUDA Error %s, %s:%d\n",hipGetErrorString(hipGetLastError()),__FILE__,__LINE__); \ else \ printf("XMP Error %s, %s:%d\n",xmpGetErrorString(error),__FILE__,__LINE__); \ exit(EXIT_FAILURE); \ } \ } using namespace std; std::ofstream f; std::string getText(string filename) { std::string output=""; std::ifstream file("laststring.txt"); std::string factor=""; while (std::getline(file, factor)) { output+=factor+"\n"; } //std::cout<<output; return output; } uint32_t* makeLimbs(std::string input) { uint64_t high = 0, low = 0, tmp; for(int i=0;i<input.length();i++) { char c=input[i]; high *= 10; tmp = low * 10; if(tmp / 10 != low) { high += ((low >> 32) * 10 + ((low & 0xf) * 10 >> 32)) >> 32; } low = tmp; tmp = low + c - '0'; high += tmp < low; low = tmp; } uint32_t *number=(uint32_t *)malloc(4*sizeof(uint32_t)); number[0]=low%4294967296; number[1]=low/4294967296; number[2]=high%4294967296; number[3]=high/4294967296; return number; } void load_ordered_array(uint32_t *numb1,int no_words,int no_integers,std::string arrayname,int iteration_no) { //f<<""\n"+arrayname+"=["; uint32_t value=no_integers*iteration_no; printf("iteration no:%d",iteration_no); for(int i=0;i<no_integers;i++) { numb1[4*i]=value+i; numb1[4*i+1]=0; numb1[4*i+2]=0; numb1[4*i+3]=0; /* printf("\n"); printf("%" PRIu32 ":\t",numb1[4*i]); printf("%" PRIu32 ":\t",numb1[4*i+1]); printf("%" PRIu32 ":\t",numb1[4*i+2]); printf("%" PRIu32 ":\t\n",numb1[4*i+3]); */ //f<<"" "<<numb1[4*i]<<",0,0,0,"; } //f<<""]\n"; } void load_gen_array(uint32_t *numb1,int no_words,int no_integers,std::string arrayname) { //f<<""\n"+arrayname+"=["; int no_iterations=no_integers*no_words; for(int i=0;i<no_iterations ;i++) { numb1[i]=rand()%4294967296; //f<<"" "<<numb1[i]<<","; } //f<<""]\n"; } void load_odd_array(uint32_t *numb1,int no_words,int no_integers,std::string arrayname) { //f<<""\n"+arrayname+"=["; int no_iterations=no_integers*no_words; for(int i=0;i<no_iterations ;i++) { numb1[i]=rand()%4294967296; //f<<"" "<<numb1[i]<<","; if(i%no_words==0&&(numb1[i]%2==0)){ numb1[i]=numb1[i]+1; } } //f<<""]\n"; } void write_array_in_file(uint32_t *numb1,int no_words,int no_integers,std::string arrayname) { int no_iterations=no_words*no_integers; //f<<""\n"+arrayname+"=["; for(int i=0;i<no_iterations;i++){ //f<<"" "<<numb1[i]<<","; } //f<<""]\n"; } __global__ void searchKernel(uint32_t *a, uint32_t *search_element,int *d_index,int *iteration_no){ int index; int tid = blockIdx.x * blockDim.x + threadIdx.x; int low=677*tid; int high=677*(tid+1)-1; uint32_t h0,h1,h2,h3; h0=search_element[0]; h1=search_element[1]; h2=search_element[2]; h3=search_element[3]; /* if(tid==329){ printf("\niteration_no:%d\n",iteration_no[0]); printf("\n %d \t" ,low+iteration_no[0]*2079744); printf("\n %d \t\n" ,high+iteration_no[0]*2079744); printf("%" PRIu32 ":\t",h0); printf("%" PRIu32 ":\t",h1); printf("%" PRIu32 ":\t",h2); printf("%" PRIu32 ":\t\n",h3); printf("%d" ,668777>low) ; printf("%d",668777<high); */ for(int i=low;i<=high;i=i+1){ /* printf("\n%d %d \t" ,i,iteration_no[0]*2079744+i); printf("%" PRIu32 ":\t",a[4*i]); printf("%" PRIu32 ":\t",a[4*i+1]); printf("%" PRIu32 ":\t",a[4*i+2]); printf("%" PRIu32 ":\t\n",a[4*i+3]); */ if(h0==a[4*i]){ if(h1==a[4*i+1]){ if(h2=a[4*i+2]){ if(h3==a[4*i+3]){ printf("\nindex found at %d\n",i); d_index[0]=iteration_no[0]*2079744+i; break; } } } } } // } } // Helper function for using CUDA to add vectors in parallel. hipError_t searchWithCuda(uint32_t *a,int no_elements,uint32_t *element,int *returned_index,int iteration_no) { uint32_t *dev_a;; uint32_t *dev_element; int *dev_index; int h_index=-999; int *dev_iteration_no; hipError_t cudaStatus; // 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; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = hipMalloc((void**)&dev_a, no_elements *4* sizeof(uint32_t)); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMalloc failed!"); goto Error; } cudaStatus = hipMalloc((void**)&dev_index,sizeof(int)); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMalloc failed!"); goto Error; } cudaStatus = hipMalloc((void**)&dev_iteration_no,sizeof(int)); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMalloc failed!"); goto Error; } cudaStatus = hipMalloc((void**)&dev_element,4*sizeof(uint32_t)); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMalloc failed!"); goto Error; } // Copy input vectors from host memory to GPU buffers. cudaStatus = hipMemcpy(dev_a, a, no_elements * 4*sizeof(uint32_t), hipMemcpyHostToDevice); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); goto Error; } cudaStatus = hipMemcpy(dev_element,element,4*sizeof(uint32_t),hipMemcpyHostToDevice); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); goto Error; } cudaStatus = hipMemcpy(dev_index,&h_index,sizeof(int),hipMemcpyHostToDevice); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); goto Error; } cudaStatus = hipMemcpy(dev_iteration_no,&iteration_no,sizeof(int),hipMemcpyHostToDevice); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); goto Error; } // Launch a kernel on the GPU with one thread for each element. hipLaunchKernelGGL(( searchKernel), dim3(3), dim3(1024), 0, 0, dev_a, dev_element,dev_index,dev_iteration_no); // 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); goto Error; } // Copy output vector from GPU buffer to host memory. cudaStatus = hipMemcpy(&h_index, dev_index,sizeof(int), hipMemcpyDeviceToHost); if (cudaStatus != hipSuccess) { fprintf(stderr, "hipMemcpy failed!"); goto Error; } if(h_index!=-999){ printf("\nindex is:%d\n",h_index); printf("%" PRIu32 ":\t",a[h_index%2079744]); printf("%" PRIu32 ":\t",a[h_index%2079744+1]); printf("%" PRIu32 ":\t",a[h_index%2079744+2]); printf("%" PRIu32 ":\t\n",a[h_index%2079744+3]); returned_index[0]=h_index; } else{ printf("\nindex is not found\n"); } Error: hipFree(dev_a); hipFree(dev_element); hipFree(dev_index); return cudaStatus; } void display_number(uint32_t *number,int no_words) { printf("\n"); for(int i=0;i<4;i++){ printf("%" PRIu32 ":\t",number[i]); } printf("\n"); } void set_for_test(uint32_t *resb){ int test_index=2079713; resb[test_index]=123456; resb[test_index+1]=789123; resb[test_index+2]=456789; resb[test_index+3]=234567; } uint32_t *get_search_element(){ uint32_t *search_element=(uint32_t *)malloc(4*sizeof(uint32_t)); search_element[0]=123456; search_element[1]=789123; search_element[2]=456789; search_element[3]=234567; return search_element; } int main() { f.open ("testoutput.py"); uint32_t i,w; int bits=128; int no_integers=2079744; uint32_t *numb1,*numb2,*numb3,*resb; //these are integer variable at the CPU uint32_t *search_element; size_t bytes=bits/8; uint32_t no_limbs=bytes/sizeof(uint32_t); uint32_t limbs2=2*(bytes/sizeof(uint32_t)); time_t my_time = time(NULL); std::string search_string="239157056073798794349891607716068883257"; search_element=makeLimbs(search_string); // creating integers at the host std::string input1="202572898398210545140461686546660877937"; std::string input3="305528117913166920104874918136902167483"; numb1=makeLimbs((std::string)input1); numb2=(uint32_t*)malloc(no_integers*bytes); numb3=makeLimbs((std::string)input3); resb= (uint32_t*)malloc(no_integers*bytes); xmpIntegers_t num1, num2,num3, res; //these are integer variable at the GPU xmpHandle_t handle; hipSetDevice(0); //allocate handle XMP_CHECK_ERROR(xmpHandleCreate(&handle)); //allocate integers XMP_CHECK_ERROR(xmpIntegersCreate(handle,&num1,bits,1)); XMP_CHECK_ERROR(xmpIntegersCreate(handle,&num2,bits,no_integers)); XMP_CHECK_ERROR(xmpIntegersCreate(handle,&num3,bits,1)); XMP_CHECK_ERROR(xmpIntegersCreate(handle,&res,bits,no_integers)); int no_iterations=no_limbs; //load_odd_array(numb1,4,1,"a");//4 words means 128 bit number //load_odd_array(numb3,4,1,"c");//4 words means 128 bit number display_number(numb1,4); display_number(numb3,4); int iteration_no=0; while(iteration_no<=600){ load_ordered_array(numb2,4,no_integers,"b",iteration_no); XMP_CHECK_ERROR(xmpIntegersImport(handle,num1,4,-1, sizeof(uint32_t),0,0,numb1,1));//export to gpu XMP_CHECK_ERROR(xmpIntegersImport(handle,num2,4,-1, sizeof(uint32_t),0,0,numb2,no_integers));//export to gpu XMP_CHECK_ERROR(xmpIntegersImport(handle,num3,4,-1, sizeof(uint32_t),0,0,numb3,1));//export to gpu XMP_CHECK_ERROR(xmpIntegersPowm(handle,res,num1,num2,num3,no_integers));//calling power function XMP_CHECK_ERROR(xmpIntegersExport(handle,resb,&no_limbs,-1,sizeof(uint32_t),0,0,res,no_integers));//export to host int index=-99;; hipError_t cudaStatus = searchWithCuda(resb,no_integers,search_element,&index,iteration_no); // searchWithCuda( uint32_t element,int *returned_index) if (cudaStatus != hipSuccess) { fprintf(stderr, "addWithCuda failed!"); return 1; } if(index!=-99){ printf("\nindex is:%d\n",index); printf("%" PRIu32 ":\t",resb[index%2079744]); printf("%" PRIu32 ":\t",resb[index%2079744+1]); printf("%" PRIu32 ":\t",resb[index%2079744+2]); printf("%" PRIu32 ":\t\n",resb[index%2079744+3]); break; } iteration_no=iteration_no+1; } /* no_iterations=no_limbs*no_integers; //f<<""\nresult=["; for(i=0;i<no_iterations;i++){ //f<<"" "<<resb[i]<<","; } std::cout<<"]\n"; //f<<""]\n"; */ //write_array_in_file(resb,4,no_integers,"result"); std::string need_append=getText("laststring.txt"); //std::cout<<need_append; //f<<"need_append; //free integers XMP_CHECK_ERROR(xmpIntegersDestroy(handle,num1)); XMP_CHECK_ERROR(xmpIntegersDestroy(handle,num3)); XMP_CHECK_ERROR(xmpIntegersDestroy(handle,res)); XMP_CHECK_ERROR(xmpIntegersDestroy(handle,num2)); //free handle XMP_CHECK_ERROR(xmpHandleDestroy(handle)); free(numb1); free(resb); free(numb2); free(numb3); time_t my_time1 = time(NULL); printf("%s", ctime(&my_time)); printf("%s", ctime(&my_time1)); printf("\n\n\nsample01 executed sucessfully\n"); return 0; }
76f2baa0c04314f8711429bafc091c67db32478a.cu
/*** Copyright (c) 2015, 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 "xmp.h" #include <stdio.h> #include <stdlib.h> #include <fstream> #include <cuda_runtime_api.h> #include<stdint.h> #include<iostream> #include <cinttypes> #define XMP_CHECK_ERROR(fun) \ { \ xmpError_t error=fun; \ if(error!=xmpErrorSuccess){ \ if(error==xmpErrorCuda) \ printf("CUDA Error %s, %s:%d\n",cudaGetErrorString(cudaGetLastError()),__FILE__,__LINE__); \ else \ printf("XMP Error %s, %s:%d\n",xmpGetErrorString(error),__FILE__,__LINE__); \ exit(EXIT_FAILURE); \ } \ } using namespace std; std::ofstream f; std::string getText(string filename) { std::string output=""; std::ifstream file("laststring.txt"); std::string factor=""; while (std::getline(file, factor)) { output+=factor+"\n"; } //std::cout<<output; return output; } uint32_t* makeLimbs(std::string input) { uint64_t high = 0, low = 0, tmp; for(int i=0;i<input.length();i++) { char c=input[i]; high *= 10; tmp = low * 10; if(tmp / 10 != low) { high += ((low >> 32) * 10 + ((low & 0xf) * 10 >> 32)) >> 32; } low = tmp; tmp = low + c - '0'; high += tmp < low; low = tmp; } uint32_t *number=(uint32_t *)malloc(4*sizeof(uint32_t)); number[0]=low%4294967296; number[1]=low/4294967296; number[2]=high%4294967296; number[3]=high/4294967296; return number; } void load_ordered_array(uint32_t *numb1,int no_words,int no_integers,std::string arrayname,int iteration_no) { //f<<""\n"+arrayname+"=["; uint32_t value=no_integers*iteration_no; printf("iteration no:%d",iteration_no); for(int i=0;i<no_integers;i++) { numb1[4*i]=value+i; numb1[4*i+1]=0; numb1[4*i+2]=0; numb1[4*i+3]=0; /* printf("\n"); printf("%" PRIu32 ":\t",numb1[4*i]); printf("%" PRIu32 ":\t",numb1[4*i+1]); printf("%" PRIu32 ":\t",numb1[4*i+2]); printf("%" PRIu32 ":\t\n",numb1[4*i+3]); */ //f<<"" "<<numb1[4*i]<<",0,0,0,"; } //f<<""]\n"; } void load_gen_array(uint32_t *numb1,int no_words,int no_integers,std::string arrayname) { //f<<""\n"+arrayname+"=["; int no_iterations=no_integers*no_words; for(int i=0;i<no_iterations ;i++) { numb1[i]=rand()%4294967296; //f<<"" "<<numb1[i]<<","; } //f<<""]\n"; } void load_odd_array(uint32_t *numb1,int no_words,int no_integers,std::string arrayname) { //f<<""\n"+arrayname+"=["; int no_iterations=no_integers*no_words; for(int i=0;i<no_iterations ;i++) { numb1[i]=rand()%4294967296; //f<<"" "<<numb1[i]<<","; if(i%no_words==0&&(numb1[i]%2==0)){ numb1[i]=numb1[i]+1; } } //f<<""]\n"; } void write_array_in_file(uint32_t *numb1,int no_words,int no_integers,std::string arrayname) { int no_iterations=no_words*no_integers; //f<<""\n"+arrayname+"=["; for(int i=0;i<no_iterations;i++){ //f<<"" "<<numb1[i]<<","; } //f<<""]\n"; } __global__ void searchKernel(uint32_t *a, uint32_t *search_element,int *d_index,int *iteration_no){ int index; int tid = blockIdx.x * blockDim.x + threadIdx.x; int low=677*tid; int high=677*(tid+1)-1; uint32_t h0,h1,h2,h3; h0=search_element[0]; h1=search_element[1]; h2=search_element[2]; h3=search_element[3]; /* if(tid==329){ printf("\niteration_no:%d\n",iteration_no[0]); printf("\n %d \t" ,low+iteration_no[0]*2079744); printf("\n %d \t\n" ,high+iteration_no[0]*2079744); printf("%" PRIu32 ":\t",h0); printf("%" PRIu32 ":\t",h1); printf("%" PRIu32 ":\t",h2); printf("%" PRIu32 ":\t\n",h3); printf("%d" ,668777>low) ; printf("%d",668777<high); */ for(int i=low;i<=high;i=i+1){ /* printf("\n%d %d \t" ,i,iteration_no[0]*2079744+i); printf("%" PRIu32 ":\t",a[4*i]); printf("%" PRIu32 ":\t",a[4*i+1]); printf("%" PRIu32 ":\t",a[4*i+2]); printf("%" PRIu32 ":\t\n",a[4*i+3]); */ if(h0==a[4*i]){ if(h1==a[4*i+1]){ if(h2=a[4*i+2]){ if(h3==a[4*i+3]){ printf("\nindex found at %d\n",i); d_index[0]=iteration_no[0]*2079744+i; break; } } } } } // } } // Helper function for using CUDA to add vectors in parallel. cudaError_t searchWithCuda(uint32_t *a,int no_elements,uint32_t *element,int *returned_index,int iteration_no) { uint32_t *dev_a;; uint32_t *dev_element; int *dev_index; int h_index=-999; int *dev_iteration_no; cudaError_t cudaStatus; // Choose which GPU to run on, change this on a multi-GPU system. cudaStatus = cudaSetDevice(0); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaSetDevice failed! Do you have a CUDA-capable GPU installed?"); goto Error; } // Allocate GPU buffers for three vectors (two input, one output) . cudaStatus = cudaMalloc((void**)&dev_a, no_elements *4* sizeof(uint32_t)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); goto Error; } cudaStatus = cudaMalloc((void**)&dev_index,sizeof(int)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); goto Error; } cudaStatus = cudaMalloc((void**)&dev_iteration_no,sizeof(int)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); goto Error; } cudaStatus = cudaMalloc((void**)&dev_element,4*sizeof(uint32_t)); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMalloc failed!"); goto Error; } // Copy input vectors from host memory to GPU buffers. cudaStatus = cudaMemcpy(dev_a, a, no_elements * 4*sizeof(uint32_t), cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); goto Error; } cudaStatus = cudaMemcpy(dev_element,element,4*sizeof(uint32_t),cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); goto Error; } cudaStatus = cudaMemcpy(dev_index,&h_index,sizeof(int),cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); goto Error; } cudaStatus = cudaMemcpy(dev_iteration_no,&iteration_no,sizeof(int),cudaMemcpyHostToDevice); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); goto Error; } // Launch a kernel on the GPU with one thread for each element. searchKernel<<<3, 1024>>>(dev_a, dev_element,dev_index,dev_iteration_no); // cudaThreadSynchronize waits for the kernel to finish, and returns // any errors encountered during the launch. cudaStatus = cudaThreadSynchronize(); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaThreadSynchronize returned error code %d after launching addKernel!\n", cudaStatus); goto Error; } // Copy output vector from GPU buffer to host memory. cudaStatus = cudaMemcpy(&h_index, dev_index,sizeof(int), cudaMemcpyDeviceToHost); if (cudaStatus != cudaSuccess) { fprintf(stderr, "cudaMemcpy failed!"); goto Error; } if(h_index!=-999){ printf("\nindex is:%d\n",h_index); printf("%" PRIu32 ":\t",a[h_index%2079744]); printf("%" PRIu32 ":\t",a[h_index%2079744+1]); printf("%" PRIu32 ":\t",a[h_index%2079744+2]); printf("%" PRIu32 ":\t\n",a[h_index%2079744+3]); returned_index[0]=h_index; } else{ printf("\nindex is not found\n"); } Error: cudaFree(dev_a); cudaFree(dev_element); cudaFree(dev_index); return cudaStatus; } void display_number(uint32_t *number,int no_words) { printf("\n"); for(int i=0;i<4;i++){ printf("%" PRIu32 ":\t",number[i]); } printf("\n"); } void set_for_test(uint32_t *resb){ int test_index=2079713; resb[test_index]=123456; resb[test_index+1]=789123; resb[test_index+2]=456789; resb[test_index+3]=234567; } uint32_t *get_search_element(){ uint32_t *search_element=(uint32_t *)malloc(4*sizeof(uint32_t)); search_element[0]=123456; search_element[1]=789123; search_element[2]=456789; search_element[3]=234567; return search_element; } int main() { f.open ("testoutput.py"); uint32_t i,w; int bits=128; int no_integers=2079744; uint32_t *numb1,*numb2,*numb3,*resb; //these are integer variable at the CPU uint32_t *search_element; size_t bytes=bits/8; uint32_t no_limbs=bytes/sizeof(uint32_t); uint32_t limbs2=2*(bytes/sizeof(uint32_t)); time_t my_time = time(NULL); std::string search_string="239157056073798794349891607716068883257"; search_element=makeLimbs(search_string); // creating integers at the host std::string input1="202572898398210545140461686546660877937"; std::string input3="305528117913166920104874918136902167483"; numb1=makeLimbs((std::string)input1); numb2=(uint32_t*)malloc(no_integers*bytes); numb3=makeLimbs((std::string)input3); resb= (uint32_t*)malloc(no_integers*bytes); xmpIntegers_t num1, num2,num3, res; //these are integer variable at the GPU xmpHandle_t handle; cudaSetDevice(0); //allocate handle XMP_CHECK_ERROR(xmpHandleCreate(&handle)); //allocate integers XMP_CHECK_ERROR(xmpIntegersCreate(handle,&num1,bits,1)); XMP_CHECK_ERROR(xmpIntegersCreate(handle,&num2,bits,no_integers)); XMP_CHECK_ERROR(xmpIntegersCreate(handle,&num3,bits,1)); XMP_CHECK_ERROR(xmpIntegersCreate(handle,&res,bits,no_integers)); int no_iterations=no_limbs; //load_odd_array(numb1,4,1,"a");//4 words means 128 bit number //load_odd_array(numb3,4,1,"c");//4 words means 128 bit number display_number(numb1,4); display_number(numb3,4); int iteration_no=0; while(iteration_no<=600){ load_ordered_array(numb2,4,no_integers,"b",iteration_no); XMP_CHECK_ERROR(xmpIntegersImport(handle,num1,4,-1, sizeof(uint32_t),0,0,numb1,1));//export to gpu XMP_CHECK_ERROR(xmpIntegersImport(handle,num2,4,-1, sizeof(uint32_t),0,0,numb2,no_integers));//export to gpu XMP_CHECK_ERROR(xmpIntegersImport(handle,num3,4,-1, sizeof(uint32_t),0,0,numb3,1));//export to gpu XMP_CHECK_ERROR(xmpIntegersPowm(handle,res,num1,num2,num3,no_integers));//calling power function XMP_CHECK_ERROR(xmpIntegersExport(handle,resb,&no_limbs,-1,sizeof(uint32_t),0,0,res,no_integers));//export to host int index=-99;; cudaError_t cudaStatus = searchWithCuda(resb,no_integers,search_element,&index,iteration_no); // searchWithCuda( uint32_t element,int *returned_index) if (cudaStatus != cudaSuccess) { fprintf(stderr, "addWithCuda failed!"); return 1; } if(index!=-99){ printf("\nindex is:%d\n",index); printf("%" PRIu32 ":\t",resb[index%2079744]); printf("%" PRIu32 ":\t",resb[index%2079744+1]); printf("%" PRIu32 ":\t",resb[index%2079744+2]); printf("%" PRIu32 ":\t\n",resb[index%2079744+3]); break; } iteration_no=iteration_no+1; } /* no_iterations=no_limbs*no_integers; //f<<""\nresult=["; for(i=0;i<no_iterations;i++){ //f<<"" "<<resb[i]<<","; } std::cout<<"]\n"; //f<<""]\n"; */ //write_array_in_file(resb,4,no_integers,"result"); std::string need_append=getText("laststring.txt"); //std::cout<<need_append; //f<<"need_append; //free integers XMP_CHECK_ERROR(xmpIntegersDestroy(handle,num1)); XMP_CHECK_ERROR(xmpIntegersDestroy(handle,num3)); XMP_CHECK_ERROR(xmpIntegersDestroy(handle,res)); XMP_CHECK_ERROR(xmpIntegersDestroy(handle,num2)); //free handle XMP_CHECK_ERROR(xmpHandleDestroy(handle)); free(numb1); free(resb); free(numb2); free(numb3); time_t my_time1 = time(NULL); printf("%s", ctime(&my_time)); printf("%s", ctime(&my_time1)); printf("\n\n\nsample01 executed sucessfully\n"); return 0; }
e85b899a7807d6ac92da933d7989a51a0b0de4e5.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright (c) 2020 NVIDIA Corporation. * Copyright (c) 2018-2020 Chris Choy (chrischoy@ai.stanford.edu). * * 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. * * Please cite "4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural * Networks", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part * of the code. */ #ifndef GPU_POOLING_AVG #define GPU_POOLING_AVG #include <hipsparse.h> #include <limits> #include <thrust/device_vector.h> #include <thrust/execution_policy.h> #include <thrust/fill.h> #include <thrust/host_vector.h> #include <thrust/functional.h> #include <thrust/iterator/discard_iterator.h> #include <thrust/reduce.h> #include <thrust/sort.h> #include "allocators.cuh" #include "pooling_avg_kernel.cuh" #include "utils.hpp" namespace minkowski { template <typename Dtype> __global__ void fill(const int n, Dtype *in_feat, Dtype val) { CUDA_KERNEL_LOOP(index, n) { in_feat[index] = val; } } template <typename Dtype> __global__ void col2row_major(const int n, const int nrows, const int ncols, const Dtype *colA, Dtype *rowA) { int i, j; CUDA_KERNEL_LOOP(index, n) { i = index % nrows; j = index / nrows; rowA[i * ncols + j] = colA[index]; } } template <typename Dtype> __global__ void col2row_major_with_div(const int n, const int nrows, const int ncols, const Dtype *num_nonzero, const Dtype *colA, Dtype *rowA) { int i, j; CUDA_KERNEL_LOOP(index, n) { i = index % nrows; j = index / nrows; if (num_nonzero[i] >= 1) { rowA[i * ncols + j] = colA[index] / num_nonzero[i]; } else { rowA[i * ncols + j] = colA[index]; } } } template <typename Itype, typename Dtype> __global__ void unique_row2num_nonzero(const int n, Dtype *__restrict__ d_num_nonzero, const Itype *__restrict__ unique_row_ptr, const Dtype *__restrict__ reduced_val_ptr) { CUDA_KERNEL_LOOP(index, n) { d_num_nonzero[unique_row_ptr[index]] = reduced_val_ptr[index]; } } template <typename Dtype, typename Itype> __global__ void set_gradient(const int n, const Dtype *d_grad_out, Dtype *d_grad_in, const Itype *out_index, int nchannel) { CUDA_KERNEL_LOOP(index, n) { atomicAdd(&d_grad_in[out_index[index]], d_grad_out[index]); } } template <typename Dtype, typename Itype> __global__ void set_gradient_nonzero(const int n, const Dtype *d_grad_out, Dtype *d_grad_in, int nchannel, const Itype *in_map, const Itype *out_map) { CUDA_KERNEL_LOOP(index, n) { int nrow = index / nchannel; int ch = index % nchannel; atomicAdd(&d_grad_in[in_map[nrow] * nchannel + ch], d_grad_out[out_map[nrow] * nchannel + ch]); } } template <typename Dtype, typename Itype> __global__ void set_gradient_nonzero_avg(const int n, const Dtype *d_grad_out, Dtype *d_grad_in, int nchannel, const Dtype *d_num_nonzero, const Itype *in_map, const Itype *out_map) { CUDA_KERNEL_LOOP(index, n) { int nrow = index / nchannel; int ch = index % nchannel; int curr_num_nonzero = d_num_nonzero[out_map[nrow]]; if (curr_num_nonzero >= 1) atomicAdd(&d_grad_in[in_map[nrow] * nchannel + ch], d_grad_out[out_map[nrow] * nchannel + ch] / curr_num_nonzero); } } template <typename Dtype, typename Itype, typename ByteAllocator> void NonzeroAvgPoolingForwardKernelGPU( Dtype const *d_in_feat, // default_types::size_type const in_nrows, // Dtype *d_out_feat, // default_types::size_type const out_nrows, // Dtype *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<Itype, ByteAllocator> const &kernel_map, // bool const use_avg, // ByteAllocator &allocator, // hipsparseHandle_t cushandle, hipStream_t stream) { const Dtype alpha = 1; const Dtype beta = 0; static_assert(sizeof(Itype) == sizeof(int), "cusparse requires int type index"); Dtype *d_ones, *d_coo_val, *d_tmp_out_feat; constexpr bool is_int32 = sizeof(Itype) == sizeof(int32_t); constexpr bool is_int64 = sizeof(Itype) == sizeof(int64_t); constexpr bool is_float32 = std::is_same<Dtype, float>::value; hipDataType cuda_data_type = is_float32 ? HIP_R_32F : HIP_R_64F; hipsparseSpMMAlg_t mm_alg; #if defined(CUDART_VERSION) && (CUDART_VERSION < 10010) ASSERT(false, "spmm sparse-dense requires CUDA 10.1 or greater"); #elif defined(CUDART_VERSION) && (CUDART_VERSION >= 10010) && \ (CUDART_VERSION < 11000) mm_alg = HIPSPARSE_COOMM_ALG1; static_assert(is_int32, "int64 hipsparseSpMM requires CUDA 11.1 or greater"); #elif defined(CUDART_VERSION) && (CUDART_VERSION >= 11000) mm_alg = HIPSPARSE_SPMM_COO_ALG1; static_assert(is_int32 || is_int64, "Invalid index type"); #endif /* sparse mm prep */ size_t const sparse_nnzs = kernel_map.in_maps.end() - kernel_map.in_maps.begin(); static_assert(is_int32, "sort_coo supports int32"); sort_coo_gpu<ByteAllocator>(cushandle, out_nrows, in_nrows, sparse_nnzs, (int *)kernel_map.out_maps.begin(), (int *)kernel_map.in_maps.begin(), allocator); // feature output d_tmp_out_feat = (Dtype *)allocator.allocate(nchannel * out_nrows * sizeof(Dtype)); d_coo_val = (Dtype *)allocator.allocate(sparse_nnzs * sizeof(Dtype)); hipLaunchKernelGGL(( fill<Dtype>), dim3(GET_BLOCKS(sparse_nnzs, CUDA_NUM_THREADS)), dim3(CUDA_NUM_THREADS), 0, stream, sparse_nnzs, d_coo_val, (Dtype)1.); if (use_avg) { d_ones = (Dtype *)allocator.allocate(sparse_nnzs * sizeof(Dtype)); hipLaunchKernelGGL(( fill<Dtype>), dim3(GET_BLOCKS(sparse_nnzs, CUDA_NUM_THREADS)), dim3(CUDA_NUM_THREADS), 0, stream, sparse_nnzs, d_ones, (Dtype)1.); } #ifdef DEBUG std::cout << "sparse_nnzs: " << sparse_nnzs << "\n"; Itype *p_scr = (Itype *)std::malloc((sparse_nnzs)*2 * sizeof(Itype)); CUDA_CHECK(hipMemcpy(p_scr, kernel_map.out_maps.begin(), sparse_nnzs * sizeof(Itype), hipMemcpyDeviceToHost)); CUDA_CHECK(hipMemcpy(p_scr + sparse_nnzs, kernel_map.in_maps.begin(), sparse_nnzs * sizeof(Itype), hipMemcpyDeviceToHost)); Itype step = std::max<Itype>(sparse_nnzs / 100, 1); Itype i = 0; for (; i < sparse_nnzs;) { std::cout << i; std::cout << " out_map: " << p_scr[i] << ", in_map: " << p_scr[i + sparse_nnzs] << "\n"; i += step; } i -= step; for (; i < sparse_nnzs; ++i) { std::cout << i; std::cout << " out_map: " << p_scr[i] << ", in_map: " << p_scr[i + sparse_nnzs] << "\n"; } std::free(p_scr); std::cout << "done printing\n"; #endif Itype *sorted_row_ptr = (Itype *)allocator.allocate(2 * (sparse_nnzs + 1) * sizeof(Itype)); Itype *sorted_col_ptr = sorted_row_ptr + sparse_nnzs + 1; CUDA_CHECK(hipMemcpy(sorted_row_ptr, kernel_map.out_maps.begin(), sparse_nnzs * sizeof(Itype), hipMemcpyDeviceToDevice)); CUDA_CHECK(hipMemcpy(sorted_col_ptr, kernel_map.in_maps.begin(), sparse_nnzs * sizeof(Itype), hipMemcpyDeviceToDevice)); thrust::sort_by_key(thrust::device, // sorted_row_ptr, // key begin sorted_row_ptr + sparse_nnzs, // key end sorted_col_ptr); // +---------+ +---+ // | spm | | i | // +---------+ | n | // in_nrows | | // | F | // | | // +---+ // nchannel size_t dim_i = out_nrows, dim_j = in_nrows, dim_k = nchannel; hipsparseSpMatDescr_t sparse_descr; hipsparseDnMatDescr_t dense_descr; hipsparseDnMatDescr_t result_descr; CUSPARSE_CHECK( hipsparseCreateCoo(&sparse_descr, // dim_i, dim_j, sparse_nnzs, // sorted_row_ptr, // rows sorted_col_ptr, // cols d_coo_val, // coo vals is_int32 ? HIPSPARSE_INDEX_32I : HIPSPARSE_INDEX_64I, HIPSPARSE_INDEX_BASE_ZERO, cuda_data_type)); CUSPARSE_CHECK(hipsparseCreateDnMat(&dense_descr, // dim_k, dim_j, dim_k, // (void *)d_in_feat, // cuda_data_type, HIPSPARSE_ORDER_COL)); CUSPARSE_CHECK(hipsparseCreateDnMat(&result_descr, // dim_i, dim_k, dim_i, // (void *)d_tmp_out_feat, // cuda_data_type, HIPSPARSE_ORDER_COL)); size_t buffer_size = 0; CUSPARSE_CHECK(hipsparseSpMM_bufferSize( cushandle, HIPSPARSE_OPERATION_NON_TRANSPOSE, HIPSPARSE_OPERATION_TRANSPOSE, (void *)&alpha, sparse_descr, dense_descr, (void *)&beta, result_descr, cuda_data_type, mm_alg, &buffer_size)); // buffer size 0 for HIPSPARSE_SPMM_COO_ALG1, CUSPARSE_SPMM_COO_ALG3, // CUSPARSE_SPMM_COO_ALG4, and HIPSPARSE_CSRMM_ALG1 // WARNING: coo sorting must have been handled in the kernel map // decomposition. CUSPARSE_CHECK(hipsparseSpMM(cushandle, // HIPSPARSE_OPERATION_NON_TRANSPOSE, // HIPSPARSE_OPERATION_TRANSPOSE, // (void *)&alpha, // sparse_descr, dense_descr, // (void *)&beta, result_descr, // cuda_data_type, mm_alg, &buffer_size)); #ifdef DEBUG CUDA_CHECK(hipStreamSynchronize(0)); #endif LOG_DEBUG("SPMM"); if (use_avg) { Itype *unique_row_ptr = (Itype *)allocator.allocate(sparse_nnzs * sizeof(Itype)); Dtype *reduced_val_ptr = (Dtype *)allocator.allocate(sparse_nnzs * sizeof(Dtype)); // reduce by key auto end = thrust::reduce_by_key(thrust::device, // policy sorted_row_ptr, // key begin sorted_row_ptr + sparse_nnzs, // key end d_ones, // value begin unique_row_ptr, // key out begin reduced_val_ptr // value out begin ); int num_unique_keys = end.first - unique_row_ptr; LOG_DEBUG("Num unique keys:", num_unique_keys); #ifdef DEBUG Itype *p_unique_row = (Itype *)std::malloc(num_unique_keys * sizeof(Itype)); CUDA_CHECK(hipMemcpy(p_unique_row, unique_row_ptr, num_unique_keys * sizeof(Itype), hipMemcpyDeviceToHost)); std::cout << "[" << PtrToString(p_unique_row, num_unique_keys) << "]\n"; std::free(p_unique_row); Dtype *p_reduced_val = (Dtype *)std::malloc(num_unique_keys * sizeof(Dtype)); CUDA_CHECK(hipMemcpy(p_reduced_val, reduced_val_ptr, num_unique_keys * sizeof(Dtype), hipMemcpyDeviceToHost)); std::cout << "[" << PtrToString(p_reduced_val, num_unique_keys) << "]\n"; std::free(p_reduced_val); #endif // Copy the results to the correct output hipLaunchKernelGGL(( unique_row2num_nonzero<Itype, Dtype>) , dim3(GET_BLOCKS(num_unique_keys, CUDA_NUM_THREADS)), dim3(CUDA_NUM_THREADS), 0, stream, num_unique_keys, d_num_nonzero, unique_row_ptr, reduced_val_ptr); hipLaunchKernelGGL(( col2row_major_with_div<Dtype>) , dim3(GET_BLOCKS(out_nrows * nchannel, CUDA_NUM_THREADS)), dim3(CUDA_NUM_THREADS), 0, stream, out_nrows * nchannel, out_nrows, nchannel, d_num_nonzero, d_tmp_out_feat, d_out_feat); #ifdef DEBUG CUDA_CHECK(hipStreamSynchronize(0)); #endif LOG_DEBUG("col2row"); // Delete tmp spaces allocator.deallocate((char *)unique_row_ptr, sparse_nnzs * sizeof(Itype)); allocator.deallocate((char *)reduced_val_ptr, sparse_nnzs * sizeof(Dtype)); } else { hipLaunchKernelGGL(( col2row_major<Dtype>), dim3(GET_BLOCKS(out_nrows * nchannel, CUDA_NUM_THREADS)), dim3(CUDA_NUM_THREADS), 0, stream, out_nrows * nchannel, out_nrows, nchannel, d_tmp_out_feat, d_out_feat); } CUSPARSE_CHECK(hipsparseDestroySpMat(sparse_descr)); CUSPARSE_CHECK(hipsparseDestroyDnMat(dense_descr)); CUSPARSE_CHECK(hipsparseDestroyDnMat(result_descr)); allocator.deallocate((char *)d_coo_val, sparse_nnzs * sizeof(Dtype)); allocator.deallocate((char *)d_tmp_out_feat, nchannel * out_nrows * sizeof(Dtype)); if (use_avg) allocator.deallocate((char *)d_ones, in_nrows * sizeof(Dtype)); CUDA_CHECK(hipStreamSynchronize(0)); } // default_allocator template void NonzeroAvgPoolingForwardKernelGPU<float, uint32_t, detail::default_allocator<char>>( float const *d_in_feat, // default_types::size_type const in_nrows, // float *d_out_feat, // default_types::size_type const out_nrows, // float *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, // bool const use_avg, detail::default_allocator<char> &allocator, // hipsparseHandle_t cushandle, hipStream_t stream); template void NonzeroAvgPoolingForwardKernelGPU<double, uint32_t, detail::default_allocator<char>>( double const *d_in_feat, // default_types::size_type const in_nrows, // double *d_out_feat, // default_types::size_type const out_nrows, // double *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, // bool const use_avg, detail::default_allocator<char> &allocator, // hipsparseHandle_t cushandle, hipStream_t stream); // c10_allocator template void NonzeroAvgPoolingForwardKernelGPU<float, uint32_t, detail::c10_allocator<char>>( float const *d_in_feat, // default_types::size_type const in_nrows, // float *d_out_feat, // default_types::size_type const out_nrows, // float *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, // bool const use_avg, detail::c10_allocator<char> &allocator, // hipsparseHandle_t cushandle, hipStream_t stream); template void NonzeroAvgPoolingForwardKernelGPU<double, uint32_t, detail::c10_allocator<char>>( double const *d_in_feat, // default_types::size_type const in_nrows, // double *d_out_feat, // default_types::size_type const out_nrows, // double *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, // bool const use_avg, detail::c10_allocator<char> &allocator, // hipsparseHandle_t cushandle, hipStream_t stream); // Backward template <typename Dtype, typename Itype, typename ByteAllocator> void NonzeroAvgPoolingBackwardKernelGPU( Dtype *d_grad_in_feat, // default_types::size_type const in_nrows, // Dtype const *d_grad_out_feat, // default_types::size_type const out_nrows, // Dtype const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<Itype, ByteAllocator> const &kernel_map, bool const use_avg, hipStream_t stream) { // d_grad_in_feat must be all set to 0 size_t sparse_nnzs = kernel_map.in_maps.end() - kernel_map.in_maps.begin(); if (use_avg) { hipLaunchKernelGGL(( set_gradient_nonzero_avg<Dtype>) , dim3(GET_BLOCKS(sparse_nnzs * nchannel, CUDA_NUM_THREADS)), dim3(CUDA_NUM_THREADS), 0, stream, sparse_nnzs * nchannel, d_grad_out_feat, d_grad_in_feat, nchannel, d_num_nonzero, kernel_map.in_maps.cdata(), kernel_map.out_maps.cdata()); } else { hipLaunchKernelGGL(( set_gradient_nonzero<Dtype>) , dim3(GET_BLOCKS(sparse_nnzs * nchannel, CUDA_NUM_THREADS)), dim3(CUDA_NUM_THREADS), 0, stream, sparse_nnzs * nchannel, d_grad_out_feat, d_grad_in_feat, nchannel, kernel_map.in_maps.cdata(), kernel_map.out_maps.cdata()); } CUDA_CHECK(hipDeviceSynchronize()); } // default_allocator template void NonzeroAvgPoolingBackwardKernelGPU<float, uint32_t, detail::default_allocator<char>>( float *d_grad_in_feat, // default_types::size_type const in_nrows, // float const *d_grad_out_feat, // default_types::size_type const out_nrows, // float const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, bool const use_avg, hipStream_t stream); template void NonzeroAvgPoolingBackwardKernelGPU<double, uint32_t, detail::default_allocator<char>>( double *d_grad_in_feat, // default_types::size_type const in_nrows, // double const *d_grad_out_feat, // default_types::size_type const out_nrows, // double const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, bool const use_avg, hipStream_t stream); // c10_allocator template void NonzeroAvgPoolingBackwardKernelGPU<float, uint32_t, detail::c10_allocator<char>>( float *d_grad_in_feat, // default_types::size_type const in_nrows, // float const *d_grad_out_feat, // default_types::size_type const out_nrows, // float const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, bool const use_avg, hipStream_t stream); template void NonzeroAvgPoolingBackwardKernelGPU<double, uint32_t, detail::c10_allocator<char>>( double *d_grad_in_feat, // default_types::size_type const in_nrows, // double const *d_grad_out_feat, // default_types::size_type const out_nrows, // double const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, bool const use_avg, hipStream_t stream); } // end namespace minkowski #endif // end GPU_POOLING_AVG
e85b899a7807d6ac92da933d7989a51a0b0de4e5.cu
/* * Copyright (c) 2020 NVIDIA Corporation. * Copyright (c) 2018-2020 Chris Choy (chrischoy@ai.stanford.edu). * * 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. * * Please cite "4D Spatio-Temporal ConvNets: Minkowski Convolutional Neural * Networks", CVPR'19 (https://arxiv.org/abs/1904.08755) if you use any part * of the code. */ #ifndef GPU_POOLING_AVG #define GPU_POOLING_AVG #include <cusparse.h> #include <limits> #include <thrust/device_vector.h> #include <thrust/execution_policy.h> #include <thrust/fill.h> #include <thrust/host_vector.h> #include <thrust/functional.h> #include <thrust/iterator/discard_iterator.h> #include <thrust/reduce.h> #include <thrust/sort.h> #include "allocators.cuh" #include "pooling_avg_kernel.cuh" #include "utils.hpp" namespace minkowski { template <typename Dtype> __global__ void fill(const int n, Dtype *in_feat, Dtype val) { CUDA_KERNEL_LOOP(index, n) { in_feat[index] = val; } } template <typename Dtype> __global__ void col2row_major(const int n, const int nrows, const int ncols, const Dtype *colA, Dtype *rowA) { int i, j; CUDA_KERNEL_LOOP(index, n) { i = index % nrows; j = index / nrows; rowA[i * ncols + j] = colA[index]; } } template <typename Dtype> __global__ void col2row_major_with_div(const int n, const int nrows, const int ncols, const Dtype *num_nonzero, const Dtype *colA, Dtype *rowA) { int i, j; CUDA_KERNEL_LOOP(index, n) { i = index % nrows; j = index / nrows; if (num_nonzero[i] >= 1) { rowA[i * ncols + j] = colA[index] / num_nonzero[i]; } else { rowA[i * ncols + j] = colA[index]; } } } template <typename Itype, typename Dtype> __global__ void unique_row2num_nonzero(const int n, Dtype *__restrict__ d_num_nonzero, const Itype *__restrict__ unique_row_ptr, const Dtype *__restrict__ reduced_val_ptr) { CUDA_KERNEL_LOOP(index, n) { d_num_nonzero[unique_row_ptr[index]] = reduced_val_ptr[index]; } } template <typename Dtype, typename Itype> __global__ void set_gradient(const int n, const Dtype *d_grad_out, Dtype *d_grad_in, const Itype *out_index, int nchannel) { CUDA_KERNEL_LOOP(index, n) { atomicAdd(&d_grad_in[out_index[index]], d_grad_out[index]); } } template <typename Dtype, typename Itype> __global__ void set_gradient_nonzero(const int n, const Dtype *d_grad_out, Dtype *d_grad_in, int nchannel, const Itype *in_map, const Itype *out_map) { CUDA_KERNEL_LOOP(index, n) { int nrow = index / nchannel; int ch = index % nchannel; atomicAdd(&d_grad_in[in_map[nrow] * nchannel + ch], d_grad_out[out_map[nrow] * nchannel + ch]); } } template <typename Dtype, typename Itype> __global__ void set_gradient_nonzero_avg(const int n, const Dtype *d_grad_out, Dtype *d_grad_in, int nchannel, const Dtype *d_num_nonzero, const Itype *in_map, const Itype *out_map) { CUDA_KERNEL_LOOP(index, n) { int nrow = index / nchannel; int ch = index % nchannel; int curr_num_nonzero = d_num_nonzero[out_map[nrow]]; if (curr_num_nonzero >= 1) atomicAdd(&d_grad_in[in_map[nrow] * nchannel + ch], d_grad_out[out_map[nrow] * nchannel + ch] / curr_num_nonzero); } } template <typename Dtype, typename Itype, typename ByteAllocator> void NonzeroAvgPoolingForwardKernelGPU( Dtype const *d_in_feat, // default_types::size_type const in_nrows, // Dtype *d_out_feat, // default_types::size_type const out_nrows, // Dtype *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<Itype, ByteAllocator> const &kernel_map, // bool const use_avg, // ByteAllocator &allocator, // cusparseHandle_t cushandle, cudaStream_t stream) { const Dtype alpha = 1; const Dtype beta = 0; static_assert(sizeof(Itype) == sizeof(int), "cusparse requires int type index"); Dtype *d_ones, *d_coo_val, *d_tmp_out_feat; constexpr bool is_int32 = sizeof(Itype) == sizeof(int32_t); constexpr bool is_int64 = sizeof(Itype) == sizeof(int64_t); constexpr bool is_float32 = std::is_same<Dtype, float>::value; cudaDataType cuda_data_type = is_float32 ? CUDA_R_32F : CUDA_R_64F; cusparseSpMMAlg_t mm_alg; #if defined(CUDART_VERSION) && (CUDART_VERSION < 10010) ASSERT(false, "spmm sparse-dense requires CUDA 10.1 or greater"); #elif defined(CUDART_VERSION) && (CUDART_VERSION >= 10010) && \ (CUDART_VERSION < 11000) mm_alg = CUSPARSE_COOMM_ALG1; static_assert(is_int32, "int64 cusparseSpMM requires CUDA 11.1 or greater"); #elif defined(CUDART_VERSION) && (CUDART_VERSION >= 11000) mm_alg = CUSPARSE_SPMM_COO_ALG1; static_assert(is_int32 || is_int64, "Invalid index type"); #endif /* sparse mm prep */ size_t const sparse_nnzs = kernel_map.in_maps.end() - kernel_map.in_maps.begin(); static_assert(is_int32, "sort_coo supports int32"); sort_coo_gpu<ByteAllocator>(cushandle, out_nrows, in_nrows, sparse_nnzs, (int *)kernel_map.out_maps.begin(), (int *)kernel_map.in_maps.begin(), allocator); // feature output d_tmp_out_feat = (Dtype *)allocator.allocate(nchannel * out_nrows * sizeof(Dtype)); d_coo_val = (Dtype *)allocator.allocate(sparse_nnzs * sizeof(Dtype)); fill<Dtype><<<GET_BLOCKS(sparse_nnzs, CUDA_NUM_THREADS), CUDA_NUM_THREADS, 0, stream>>>(sparse_nnzs, d_coo_val, (Dtype)1.); if (use_avg) { d_ones = (Dtype *)allocator.allocate(sparse_nnzs * sizeof(Dtype)); fill<Dtype><<<GET_BLOCKS(sparse_nnzs, CUDA_NUM_THREADS), CUDA_NUM_THREADS, 0, stream>>>(sparse_nnzs, d_ones, (Dtype)1.); } #ifdef DEBUG std::cout << "sparse_nnzs: " << sparse_nnzs << "\n"; Itype *p_scr = (Itype *)std::malloc((sparse_nnzs)*2 * sizeof(Itype)); CUDA_CHECK(cudaMemcpy(p_scr, kernel_map.out_maps.begin(), sparse_nnzs * sizeof(Itype), cudaMemcpyDeviceToHost)); CUDA_CHECK(cudaMemcpy(p_scr + sparse_nnzs, kernel_map.in_maps.begin(), sparse_nnzs * sizeof(Itype), cudaMemcpyDeviceToHost)); Itype step = std::max<Itype>(sparse_nnzs / 100, 1); Itype i = 0; for (; i < sparse_nnzs;) { std::cout << i; std::cout << " out_map: " << p_scr[i] << ", in_map: " << p_scr[i + sparse_nnzs] << "\n"; i += step; } i -= step; for (; i < sparse_nnzs; ++i) { std::cout << i; std::cout << " out_map: " << p_scr[i] << ", in_map: " << p_scr[i + sparse_nnzs] << "\n"; } std::free(p_scr); std::cout << "done printing\n"; #endif Itype *sorted_row_ptr = (Itype *)allocator.allocate(2 * (sparse_nnzs + 1) * sizeof(Itype)); Itype *sorted_col_ptr = sorted_row_ptr + sparse_nnzs + 1; CUDA_CHECK(cudaMemcpy(sorted_row_ptr, kernel_map.out_maps.begin(), sparse_nnzs * sizeof(Itype), cudaMemcpyDeviceToDevice)); CUDA_CHECK(cudaMemcpy(sorted_col_ptr, kernel_map.in_maps.begin(), sparse_nnzs * sizeof(Itype), cudaMemcpyDeviceToDevice)); thrust::sort_by_key(thrust::device, // sorted_row_ptr, // key begin sorted_row_ptr + sparse_nnzs, // key end sorted_col_ptr); // +---------+ +---+ // | spm | | i | // +---------+ | n | // in_nrows | | // | F | // | | // +---+ // nchannel size_t dim_i = out_nrows, dim_j = in_nrows, dim_k = nchannel; cusparseSpMatDescr_t sparse_descr; cusparseDnMatDescr_t dense_descr; cusparseDnMatDescr_t result_descr; CUSPARSE_CHECK( cusparseCreateCoo(&sparse_descr, // dim_i, dim_j, sparse_nnzs, // sorted_row_ptr, // rows sorted_col_ptr, // cols d_coo_val, // coo vals is_int32 ? CUSPARSE_INDEX_32I : CUSPARSE_INDEX_64I, CUSPARSE_INDEX_BASE_ZERO, cuda_data_type)); CUSPARSE_CHECK(cusparseCreateDnMat(&dense_descr, // dim_k, dim_j, dim_k, // (void *)d_in_feat, // cuda_data_type, CUSPARSE_ORDER_COL)); CUSPARSE_CHECK(cusparseCreateDnMat(&result_descr, // dim_i, dim_k, dim_i, // (void *)d_tmp_out_feat, // cuda_data_type, CUSPARSE_ORDER_COL)); size_t buffer_size = 0; CUSPARSE_CHECK(cusparseSpMM_bufferSize( cushandle, CUSPARSE_OPERATION_NON_TRANSPOSE, CUSPARSE_OPERATION_TRANSPOSE, (void *)&alpha, sparse_descr, dense_descr, (void *)&beta, result_descr, cuda_data_type, mm_alg, &buffer_size)); // buffer size 0 for CUSPARSE_SPMM_COO_ALG1, CUSPARSE_SPMM_COO_ALG3, // CUSPARSE_SPMM_COO_ALG4, and CUSPARSE_SPMM_CSR_ALG1 // WARNING: coo sorting must have been handled in the kernel map // decomposition. CUSPARSE_CHECK(cusparseSpMM(cushandle, // CUSPARSE_OPERATION_NON_TRANSPOSE, // CUSPARSE_OPERATION_TRANSPOSE, // (void *)&alpha, // sparse_descr, dense_descr, // (void *)&beta, result_descr, // cuda_data_type, mm_alg, &buffer_size)); #ifdef DEBUG CUDA_CHECK(cudaStreamSynchronize(0)); #endif LOG_DEBUG("SPMM"); if (use_avg) { Itype *unique_row_ptr = (Itype *)allocator.allocate(sparse_nnzs * sizeof(Itype)); Dtype *reduced_val_ptr = (Dtype *)allocator.allocate(sparse_nnzs * sizeof(Dtype)); // reduce by key auto end = thrust::reduce_by_key(thrust::device, // policy sorted_row_ptr, // key begin sorted_row_ptr + sparse_nnzs, // key end d_ones, // value begin unique_row_ptr, // key out begin reduced_val_ptr // value out begin ); int num_unique_keys = end.first - unique_row_ptr; LOG_DEBUG("Num unique keys:", num_unique_keys); #ifdef DEBUG Itype *p_unique_row = (Itype *)std::malloc(num_unique_keys * sizeof(Itype)); CUDA_CHECK(cudaMemcpy(p_unique_row, unique_row_ptr, num_unique_keys * sizeof(Itype), cudaMemcpyDeviceToHost)); std::cout << "[" << PtrToString(p_unique_row, num_unique_keys) << "]\n"; std::free(p_unique_row); Dtype *p_reduced_val = (Dtype *)std::malloc(num_unique_keys * sizeof(Dtype)); CUDA_CHECK(cudaMemcpy(p_reduced_val, reduced_val_ptr, num_unique_keys * sizeof(Dtype), cudaMemcpyDeviceToHost)); std::cout << "[" << PtrToString(p_reduced_val, num_unique_keys) << "]\n"; std::free(p_reduced_val); #endif // Copy the results to the correct output unique_row2num_nonzero<Itype, Dtype> <<<GET_BLOCKS(num_unique_keys, CUDA_NUM_THREADS), CUDA_NUM_THREADS, 0, stream>>>(num_unique_keys, d_num_nonzero, unique_row_ptr, reduced_val_ptr); col2row_major_with_div<Dtype> <<<GET_BLOCKS(out_nrows * nchannel, CUDA_NUM_THREADS), CUDA_NUM_THREADS, 0, stream>>>(out_nrows * nchannel, out_nrows, nchannel, d_num_nonzero, d_tmp_out_feat, d_out_feat); #ifdef DEBUG CUDA_CHECK(cudaStreamSynchronize(0)); #endif LOG_DEBUG("col2row"); // Delete tmp spaces allocator.deallocate((char *)unique_row_ptr, sparse_nnzs * sizeof(Itype)); allocator.deallocate((char *)reduced_val_ptr, sparse_nnzs * sizeof(Dtype)); } else { col2row_major<Dtype><<<GET_BLOCKS(out_nrows * nchannel, CUDA_NUM_THREADS), CUDA_NUM_THREADS, 0, stream>>>( out_nrows * nchannel, out_nrows, nchannel, d_tmp_out_feat, d_out_feat); } CUSPARSE_CHECK(cusparseDestroySpMat(sparse_descr)); CUSPARSE_CHECK(cusparseDestroyDnMat(dense_descr)); CUSPARSE_CHECK(cusparseDestroyDnMat(result_descr)); allocator.deallocate((char *)d_coo_val, sparse_nnzs * sizeof(Dtype)); allocator.deallocate((char *)d_tmp_out_feat, nchannel * out_nrows * sizeof(Dtype)); if (use_avg) allocator.deallocate((char *)d_ones, in_nrows * sizeof(Dtype)); CUDA_CHECK(cudaStreamSynchronize(0)); } // default_allocator template void NonzeroAvgPoolingForwardKernelGPU<float, uint32_t, detail::default_allocator<char>>( float const *d_in_feat, // default_types::size_type const in_nrows, // float *d_out_feat, // default_types::size_type const out_nrows, // float *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, // bool const use_avg, detail::default_allocator<char> &allocator, // cusparseHandle_t cushandle, cudaStream_t stream); template void NonzeroAvgPoolingForwardKernelGPU<double, uint32_t, detail::default_allocator<char>>( double const *d_in_feat, // default_types::size_type const in_nrows, // double *d_out_feat, // default_types::size_type const out_nrows, // double *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, // bool const use_avg, detail::default_allocator<char> &allocator, // cusparseHandle_t cushandle, cudaStream_t stream); // c10_allocator template void NonzeroAvgPoolingForwardKernelGPU<float, uint32_t, detail::c10_allocator<char>>( float const *d_in_feat, // default_types::size_type const in_nrows, // float *d_out_feat, // default_types::size_type const out_nrows, // float *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, // bool const use_avg, detail::c10_allocator<char> &allocator, // cusparseHandle_t cushandle, cudaStream_t stream); template void NonzeroAvgPoolingForwardKernelGPU<double, uint32_t, detail::c10_allocator<char>>( double const *d_in_feat, // default_types::size_type const in_nrows, // double *d_out_feat, // default_types::size_type const out_nrows, // double *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, // bool const use_avg, detail::c10_allocator<char> &allocator, // cusparseHandle_t cushandle, cudaStream_t stream); // Backward template <typename Dtype, typename Itype, typename ByteAllocator> void NonzeroAvgPoolingBackwardKernelGPU( Dtype *d_grad_in_feat, // default_types::size_type const in_nrows, // Dtype const *d_grad_out_feat, // default_types::size_type const out_nrows, // Dtype const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<Itype, ByteAllocator> const &kernel_map, bool const use_avg, cudaStream_t stream) { // d_grad_in_feat must be all set to 0 size_t sparse_nnzs = kernel_map.in_maps.end() - kernel_map.in_maps.begin(); if (use_avg) { set_gradient_nonzero_avg<Dtype> <<<GET_BLOCKS(sparse_nnzs * nchannel, CUDA_NUM_THREADS), CUDA_NUM_THREADS, 0, stream>>>( sparse_nnzs * nchannel, d_grad_out_feat, d_grad_in_feat, nchannel, d_num_nonzero, kernel_map.in_maps.cdata(), kernel_map.out_maps.cdata()); } else { set_gradient_nonzero<Dtype> <<<GET_BLOCKS(sparse_nnzs * nchannel, CUDA_NUM_THREADS), CUDA_NUM_THREADS, 0, stream>>>( sparse_nnzs * nchannel, d_grad_out_feat, d_grad_in_feat, nchannel, kernel_map.in_maps.cdata(), kernel_map.out_maps.cdata()); } CUDA_CHECK(cudaDeviceSynchronize()); } // default_allocator template void NonzeroAvgPoolingBackwardKernelGPU<float, uint32_t, detail::default_allocator<char>>( float *d_grad_in_feat, // default_types::size_type const in_nrows, // float const *d_grad_out_feat, // default_types::size_type const out_nrows, // float const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, bool const use_avg, cudaStream_t stream); template void NonzeroAvgPoolingBackwardKernelGPU<double, uint32_t, detail::default_allocator<char>>( double *d_grad_in_feat, // default_types::size_type const in_nrows, // double const *d_grad_out_feat, // default_types::size_type const out_nrows, // double const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::default_allocator<char>> const &kernel_map, bool const use_avg, cudaStream_t stream); // c10_allocator template void NonzeroAvgPoolingBackwardKernelGPU<float, uint32_t, detail::c10_allocator<char>>( float *d_grad_in_feat, // default_types::size_type const in_nrows, // float const *d_grad_out_feat, // default_types::size_type const out_nrows, // float const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, bool const use_avg, cudaStream_t stream); template void NonzeroAvgPoolingBackwardKernelGPU<double, uint32_t, detail::c10_allocator<char>>( double *d_grad_in_feat, // default_types::size_type const in_nrows, // double const *d_grad_out_feat, // default_types::size_type const out_nrows, // double const *d_num_nonzero, // default_types::size_type const nchannel, // gpu_kernel_map<uint32_t, detail::c10_allocator<char>> const &kernel_map, bool const use_avg, cudaStream_t stream); } // end namespace minkowski #endif // end GPU_POOLING_AVG
23e6c05d0d1e87fdf899dfd9911588b51394e0b5.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 "wlcss_cuda_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]; int32_t *d_mss = NULL; hipMalloc(&d_mss, XSIZE*YSIZE); int32_t *d_mss_offsets = NULL; hipMalloc(&d_mss_offsets, XSIZE*YSIZE); int32_t *d_ts = NULL; hipMalloc(&d_ts, XSIZE*YSIZE); int32_t *d_ss = NULL; hipMalloc(&d_ss, XSIZE*YSIZE); int32_t *d_tlen = NULL; hipMalloc(&d_tlen, XSIZE*YSIZE); int32_t *d_toffsets = NULL; hipMalloc(&d_toffsets, XSIZE*YSIZE); int32_t *d_slen = NULL; hipMalloc(&d_slen, XSIZE*YSIZE); int32_t *d_soffsets = NULL; hipMalloc(&d_soffsets, XSIZE*YSIZE); int32_t *d_params = NULL; hipMalloc(&d_params, XSIZE*YSIZE); int32_t *d_3d_cost_matrix = NULL; hipMalloc(&d_3d_cost_matrix, 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(( wlcss_cuda_kernel), dim3(gridBlock),dim3(threadBlock), 0, 0, d_mss,d_mss_offsets,d_ts,d_ss,d_tlen,d_toffsets,d_slen,d_soffsets,d_params,d_3d_cost_matrix); hipDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) {hipLaunchKernelGGL(( wlcss_cuda_kernel), dim3(gridBlock),dim3(threadBlock), 0, 0, d_mss,d_mss_offsets,d_ts,d_ss,d_tlen,d_toffsets,d_slen,d_soffsets,d_params,d_3d_cost_matrix); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) {hipLaunchKernelGGL(( wlcss_cuda_kernel), dim3(gridBlock),dim3(threadBlock), 0, 0, d_mss,d_mss_offsets,d_ts,d_ss,d_tlen,d_toffsets,d_slen,d_soffsets,d_params,d_3d_cost_matrix); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
23e6c05d0d1e87fdf899dfd9911588b51394e0b5.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 "wlcss_cuda_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]; int32_t *d_mss = NULL; cudaMalloc(&d_mss, XSIZE*YSIZE); int32_t *d_mss_offsets = NULL; cudaMalloc(&d_mss_offsets, XSIZE*YSIZE); int32_t *d_ts = NULL; cudaMalloc(&d_ts, XSIZE*YSIZE); int32_t *d_ss = NULL; cudaMalloc(&d_ss, XSIZE*YSIZE); int32_t *d_tlen = NULL; cudaMalloc(&d_tlen, XSIZE*YSIZE); int32_t *d_toffsets = NULL; cudaMalloc(&d_toffsets, XSIZE*YSIZE); int32_t *d_slen = NULL; cudaMalloc(&d_slen, XSIZE*YSIZE); int32_t *d_soffsets = NULL; cudaMalloc(&d_soffsets, XSIZE*YSIZE); int32_t *d_params = NULL; cudaMalloc(&d_params, XSIZE*YSIZE); int32_t *d_3d_cost_matrix = NULL; cudaMalloc(&d_3d_cost_matrix, 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); wlcss_cuda_kernel<<<gridBlock,threadBlock>>>(d_mss,d_mss_offsets,d_ts,d_ss,d_tlen,d_toffsets,d_slen,d_soffsets,d_params,d_3d_cost_matrix); cudaDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) { wlcss_cuda_kernel<<<gridBlock,threadBlock>>>(d_mss,d_mss_offsets,d_ts,d_ss,d_tlen,d_toffsets,d_slen,d_soffsets,d_params,d_3d_cost_matrix); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) { wlcss_cuda_kernel<<<gridBlock,threadBlock>>>(d_mss,d_mss_offsets,d_ts,d_ss,d_tlen,d_toffsets,d_slen,d_soffsets,d_params,d_3d_cost_matrix); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
06021d50a0ac64d716d010e9eb3db94e91a77345.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright 1993-2010 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. * Any use, reproduction, disclosure, or distribution of this software * and related documentation without an express license agreement from * NVIDIA Corporation is strictly prohibited. * * Please refer to the applicable NVIDIA end user license agreement (EULA) * associated with this source code for terms and conditions that govern * your use of this NVIDIA software. * */ #include "book.h" #include "func.h" #include <stdio.h> #include <time.h> #define PI 3.1415926535897932384 #define mu0 4*PI*1e-7 int main( void ) { clock_t begin, end; double time_spent; begin = clock(); FILE *myfile; myfile = fopen("results.txt", "w"); double imax, rlength, eta, tstep, ldr, thresh; int numseg; int gpusteps = 10; printf("%s", "What is your I max? "); scanf("%lf", &imax); printf("%s", "What is the length of your rod? "); scanf("%lf", &rlength); printf("%s", "What is eta? "); scanf("%lf", &eta); printf("%s", "How many segments would you like? "); scanf("%d", &numseg); ldr = rlength/(numseg+1); double bound = 0.5*ldr*ldr*mu0/eta; printf("%s%lf%s", "What time step would you like? (must be less than ", bound, " ) "); scanf("%lf", &tstep); printf("%s", "What is the threshold for your convergence? "); scanf("%lf", &thresh); //initialize double *rod_new = new double[numseg+2]; bool *conv = new bool[numseg]; double *dev_old, *dev_new, *temp; bool *dev_conv; // allocate the memory on the GPU HANDLE_ERROR( hipMalloc( (void**)&dev_old, (numseg+2) * sizeof(double) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_new, (numseg+2) * sizeof(double) ) ); HANDLE_ERROR( hipMalloc( (void**)&temp, ((2*gpusteps)-1)*numseg * sizeof(double) ) ); HANDLE_ERROR( hipMalloc( (void**)&dev_conv, numseg * sizeof(bool) ) ); // fill the array 'new' hipLaunchKernelGGL(( init), dim3(numseg+2),dim3(1), 0, 0, dev_new, imax, ldr, rlength, numseg+2); // copy data on device from 'dev_new' to 'rod_new' HANDLE_ERROR( hipMemcpy( rod_new, dev_new, (numseg+2) * sizeof(double), hipMemcpyDeviceToHost ) ); int out; // output r values for (out = 0; out<numseg+1; out++) { fprintf( myfile, "%lf ", out*ldr ); } fprintf( myfile, "%lf\n", out*ldr ); double aug = eta*tstep/(mu0*ldr*ldr); int tcount = 0; HANDLE_ERROR( hipMemcpy( rod_new + 1, dev_new + 1, numseg * sizeof(double), hipMemcpyDeviceToHost ) ); for (out=0; out<numseg+1; out++) { fprintf( myfile, "%lf ", *(rod_new+out) ); } fprintf( myfile, "%lf\n", *(rod_new+out) ); do{ /*if(tcount%2000==0){ HANDLE_ERROR( hipMemcpy( rod_new + 1, dev_new + 1, numseg * sizeof(double), hipMemcpyDeviceToHost ) ); for (out=0; out<numseg+1; out++) { fprintf( myfile, "%lf ", *(rod_new+out) ); } fprintf( myfile, "%lf\n", *(rod_new+out) ); }*/ tcount++; //copy new to old hipLaunchKernelGGL(( copyToOld), dim3(numseg+2),dim3(1), 0, 0, dev_new, dev_old, numseg+2); //update hipLaunchKernelGGL(( update), dim3(numseg),dim3(1), 0, 0, dev_new, dev_old, numseg+1, dev_conv, thresh, aug, gpusteps, temp); HANDLE_ERROR( hipMemcpy( conv, dev_conv, numseg, hipMemcpyDeviceToHost ) ); }while(!converge(conv, numseg)); HANDLE_ERROR( hipMemcpy( rod_new + 1, dev_new + 1, numseg * sizeof(double), hipMemcpyDeviceToHost ) ); for (out=0; out<numseg+1; out++) { fprintf( myfile, "%lf ", *(rod_new+out) ); } fprintf( myfile, "%lf\n", *(rod_new+out) ); // free the memory allocated on the GPU HANDLE_ERROR( hipFree( dev_old ) ); HANDLE_ERROR( hipFree( dev_new ) ); HANDLE_ERROR( hipFree( dev_conv ) ); fprintf(myfile, "STOP\n"); fclose(myfile); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("\n------------------------------------\n"); printf("Execution took: %lf sec\n", time_spent); return 0; }
06021d50a0ac64d716d010e9eb3db94e91a77345.cu
/* * Copyright 1993-2010 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. * Any use, reproduction, disclosure, or distribution of this software * and related documentation without an express license agreement from * NVIDIA Corporation is strictly prohibited. * * Please refer to the applicable NVIDIA end user license agreement (EULA) * associated with this source code for terms and conditions that govern * your use of this NVIDIA software. * */ #include "book.h" #include "func.h" #include <stdio.h> #include <time.h> #define PI 3.1415926535897932384 #define mu0 4*PI*1e-7 int main( void ) { clock_t begin, end; double time_spent; begin = clock(); FILE *myfile; myfile = fopen("results.txt", "w"); double imax, rlength, eta, tstep, ldr, thresh; int numseg; int gpusteps = 10; printf("%s", "What is your I max? "); scanf("%lf", &imax); printf("%s", "What is the length of your rod? "); scanf("%lf", &rlength); printf("%s", "What is eta? "); scanf("%lf", &eta); printf("%s", "How many segments would you like? "); scanf("%d", &numseg); ldr = rlength/(numseg+1); double bound = 0.5*ldr*ldr*mu0/eta; printf("%s%lf%s", "What time step would you like? (must be less than ", bound, " ) "); scanf("%lf", &tstep); printf("%s", "What is the threshold for your convergence? "); scanf("%lf", &thresh); //initialize double *rod_new = new double[numseg+2]; bool *conv = new bool[numseg]; double *dev_old, *dev_new, *temp; bool *dev_conv; // allocate the memory on the GPU HANDLE_ERROR( cudaMalloc( (void**)&dev_old, (numseg+2) * sizeof(double) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_new, (numseg+2) * sizeof(double) ) ); HANDLE_ERROR( cudaMalloc( (void**)&temp, ((2*gpusteps)-1)*numseg * sizeof(double) ) ); HANDLE_ERROR( cudaMalloc( (void**)&dev_conv, numseg * sizeof(bool) ) ); // fill the array 'new' init<<<numseg+2,1>>>(dev_new, imax, ldr, rlength, numseg+2); // copy data on device from 'dev_new' to 'rod_new' HANDLE_ERROR( cudaMemcpy( rod_new, dev_new, (numseg+2) * sizeof(double), cudaMemcpyDeviceToHost ) ); int out; // output r values for (out = 0; out<numseg+1; out++) { fprintf( myfile, "%lf ", out*ldr ); } fprintf( myfile, "%lf\n", out*ldr ); double aug = eta*tstep/(mu0*ldr*ldr); int tcount = 0; HANDLE_ERROR( cudaMemcpy( rod_new + 1, dev_new + 1, numseg * sizeof(double), cudaMemcpyDeviceToHost ) ); for (out=0; out<numseg+1; out++) { fprintf( myfile, "%lf ", *(rod_new+out) ); } fprintf( myfile, "%lf\n", *(rod_new+out) ); do{ /*if(tcount%2000==0){ HANDLE_ERROR( cudaMemcpy( rod_new + 1, dev_new + 1, numseg * sizeof(double), cudaMemcpyDeviceToHost ) ); for (out=0; out<numseg+1; out++) { fprintf( myfile, "%lf ", *(rod_new+out) ); } fprintf( myfile, "%lf\n", *(rod_new+out) ); }*/ tcount++; //copy new to old copyToOld<<<numseg+2,1>>>(dev_new, dev_old, numseg+2); //update update<<<numseg,1>>>(dev_new, dev_old, numseg+1, dev_conv, thresh, aug, gpusteps, temp); HANDLE_ERROR( cudaMemcpy( conv, dev_conv, numseg, cudaMemcpyDeviceToHost ) ); }while(!converge(conv, numseg)); HANDLE_ERROR( cudaMemcpy( rod_new + 1, dev_new + 1, numseg * sizeof(double), cudaMemcpyDeviceToHost ) ); for (out=0; out<numseg+1; out++) { fprintf( myfile, "%lf ", *(rod_new+out) ); } fprintf( myfile, "%lf\n", *(rod_new+out) ); // free the memory allocated on the GPU HANDLE_ERROR( cudaFree( dev_old ) ); HANDLE_ERROR( cudaFree( dev_new ) ); HANDLE_ERROR( cudaFree( dev_conv ) ); fprintf(myfile, "STOP\n"); fclose(myfile); end = clock(); time_spent = (double)(end - begin) / CLOCKS_PER_SEC; printf("\n------------------------------------\n"); printf("Execution took: %lf sec\n", time_spent); return 0; }
964f07629793ea1b16b1e8dc3730aee6fb34f61c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #ifndef THC_GENERIC_FILE #define THC_GENERIC_FILE "generic/CrossbarSpatialConvolution.cu" #else static inline void THNN_(CrossbarSpatialConvolution_shapeCheck)( THCState *state, THCTensor *input, THCTensor *weight, int kH, int kW, int dH, int dW, int padH, int padW){ THArgCheck(kW > 0 && kH > 0, 9, "kernel size should be greater than zero, but got kH: %d kW: %d", kH, kW); THArgCheck(dW > 0 && dH > 0, 11, "stride should be greater than zero, but got dH: %d dW: %d", dH, dW); THCUNN_argCheck(state, weight->nDimension == 2 || weight->nDimension == 4, 5, weight, "2D or 4D weight tensor expected, but got: %s"); int ndim = input->nDimension; int dimf = 0; int dimh = 1; int dimw = 2; if (ndim == 4) { dimf++; dimh++; dimw++; } THCUNN_argCheck(state, ndim == 3 || ndim == 4, 2, input, "3D or 4D input tensor expected but got: %s"); long nInputPlane = weight->size[1] / (kH * kW); long inputHeight = input->size[dimh]; long inputWidth = input->size[dimw]; long nOutputPlane = weight->size[0]; long outputHeight = (inputHeight + 2*padH - kH) / dH + 1; long outputWidth = (inputWidth + 2*padW - kW) / dW + 1; if (outputWidth < 1 || outputHeight < 1) THError("Given input size: (%d x %d x %d). " "Calculated output size: (%d x %d x %d). Output size is too small", nInputPlane, inputHeight, inputWidth, nOutputPlane, outputHeight, outputWidth); THCUNN_check_dim_size(state, input, ndim, dimf, nInputPlane); } void THNN_(CrossbarSpatialConvolution_updateOutput)( THCState *state, THCTensor *input, THCTensor *output, THCTensor *weight, THCTensor *columns, int accumN, int kW, int kH, int dW, int dH, int padW, int padH) { THCUNN_assertSameGPU(state, 4, input, output, weight, columns); THArgCheck(THCTensor_(isContiguous)(state, weight), 4, "weight tensor has to be contiguous"); // convert 4D weight into 2D weight int freeWeight = 0; if (weight->nDimension == 4) { long s1 = weight->size[0]; long s2 = weight->size[1] * weight->size[2] * weight->size[3]; weight = THCTensor_(newWithStorage2d)(state, weight->storage, weight->storageOffset, s1, -1, s2, -1); freeWeight = 1; } THNN_(CrossbarSpatialConvolution_shapeCheck) (state, input, weight, kH, kW, dH, dW, padH, padW); // make input contiguous and 4D input = THCTensor_(newContiguous)(state, input); int batch = 1; if (input->nDimension == 3) { // Force batch batch = 0; THCTensor_(resize4d)(state, input, 1, input->size[0], input->size[1], input->size[2]); } // Params: long nInputPlane = weight->size[1]/(kH*kW); long nIn = weight->size[1]; long nOutputPlane = weight->size[0]; long inputWidth = input->size[3]; long inputHeight = input->size[2]; long outputWidth = (inputWidth + 2*padW - kW) / dW + 1; long outputHeight = (inputHeight + 2*padH - kH) / dH + 1; long nOutSpatial = outputWidth * outputHeight; long batchSize = input->size[0]; long nPsum = weight->size[1] / accumN; //Check if nPsum is valid THArgCheck(nPsum > 0 && weight->size[1] == nPsum * accumN, 101, "Number of input per convolution should be divisible by accumN, but we got number of input: %ld, accumN: %d, nPsum: %ld", weight->size[1], accumN, nPsum); // Resize output THCTensor_(resize5d)(state, output, batchSize, nOutputPlane, outputHeight, outputWidth, nPsum); // Resize temporary columns THCTensor_(resize2d)(state, columns, nInputPlane*kW*kH, outputHeight*outputWidth); // Helpers THCTensor *input_n = THCTensor_(new)(state); THCTensor *output_n = THCTensor_(new)(state); // set dimension of block and grid dim3 threads(BLOCK_SIZE, BLOCK_SIZE); dim3 grid((nOutputPlane+threads.x-1)/threads.x, (nOutSpatial+threads.y-1)/threads.y); // For each elt in batch, do: for (long elt = 0; elt < batchSize; elt ++) { // Matrix multiply per output: THCTensor_(select)(state, input_n, input, 0, elt); THCTensor_(select)(state, output_n, output, 0, elt); // Extract columns: im2col( THCState_getCurrentStream(state), THCTensor_(data)(state, input_n), nInputPlane, inputHeight, inputWidth, kH, kW, padH, padW, dH, dW, 1, 1, THCTensor_(data)(state, columns) ); // Execute the kernel hipLaunchKernelGGL(( cunn_CrossbarSpatialConvolution_updateOutput_frame_kernel<real, accreal>), dim3(grid), dim3(threads), 0, 0, THCTensor_(data)(state, output_n), THCTensor_(data)(state, columns), THCTensor_(data)(state, weight), accumN, nIn, nOutSpatial, nOutputPlane, nPsum); } // free memorys THCTensor_(free)(state, input_n); THCTensor_(free)(state, output_n); if (freeWeight) THCTensor_(free)(state, weight); // Resize output if (batch == 0) { THCTensor_(resize4d)(state, output, nOutputPlane, outputHeight, outputWidth, nPsum); THCTensor_(resize3d)(state, input, nInputPlane, inputHeight, inputWidth); } THCTensor_(free)(state, input); } #endif
964f07629793ea1b16b1e8dc3730aee6fb34f61c.cu
#ifndef THC_GENERIC_FILE #define THC_GENERIC_FILE "generic/CrossbarSpatialConvolution.cu" #else static inline void THNN_(CrossbarSpatialConvolution_shapeCheck)( THCState *state, THCTensor *input, THCTensor *weight, int kH, int kW, int dH, int dW, int padH, int padW){ THArgCheck(kW > 0 && kH > 0, 9, "kernel size should be greater than zero, but got kH: %d kW: %d", kH, kW); THArgCheck(dW > 0 && dH > 0, 11, "stride should be greater than zero, but got dH: %d dW: %d", dH, dW); THCUNN_argCheck(state, weight->nDimension == 2 || weight->nDimension == 4, 5, weight, "2D or 4D weight tensor expected, but got: %s"); int ndim = input->nDimension; int dimf = 0; int dimh = 1; int dimw = 2; if (ndim == 4) { dimf++; dimh++; dimw++; } THCUNN_argCheck(state, ndim == 3 || ndim == 4, 2, input, "3D or 4D input tensor expected but got: %s"); long nInputPlane = weight->size[1] / (kH * kW); long inputHeight = input->size[dimh]; long inputWidth = input->size[dimw]; long nOutputPlane = weight->size[0]; long outputHeight = (inputHeight + 2*padH - kH) / dH + 1; long outputWidth = (inputWidth + 2*padW - kW) / dW + 1; if (outputWidth < 1 || outputHeight < 1) THError("Given input size: (%d x %d x %d). " "Calculated output size: (%d x %d x %d). Output size is too small", nInputPlane, inputHeight, inputWidth, nOutputPlane, outputHeight, outputWidth); THCUNN_check_dim_size(state, input, ndim, dimf, nInputPlane); } void THNN_(CrossbarSpatialConvolution_updateOutput)( THCState *state, THCTensor *input, THCTensor *output, THCTensor *weight, THCTensor *columns, int accumN, int kW, int kH, int dW, int dH, int padW, int padH) { THCUNN_assertSameGPU(state, 4, input, output, weight, columns); THArgCheck(THCTensor_(isContiguous)(state, weight), 4, "weight tensor has to be contiguous"); // convert 4D weight into 2D weight int freeWeight = 0; if (weight->nDimension == 4) { long s1 = weight->size[0]; long s2 = weight->size[1] * weight->size[2] * weight->size[3]; weight = THCTensor_(newWithStorage2d)(state, weight->storage, weight->storageOffset, s1, -1, s2, -1); freeWeight = 1; } THNN_(CrossbarSpatialConvolution_shapeCheck) (state, input, weight, kH, kW, dH, dW, padH, padW); // make input contiguous and 4D input = THCTensor_(newContiguous)(state, input); int batch = 1; if (input->nDimension == 3) { // Force batch batch = 0; THCTensor_(resize4d)(state, input, 1, input->size[0], input->size[1], input->size[2]); } // Params: long nInputPlane = weight->size[1]/(kH*kW); long nIn = weight->size[1]; long nOutputPlane = weight->size[0]; long inputWidth = input->size[3]; long inputHeight = input->size[2]; long outputWidth = (inputWidth + 2*padW - kW) / dW + 1; long outputHeight = (inputHeight + 2*padH - kH) / dH + 1; long nOutSpatial = outputWidth * outputHeight; long batchSize = input->size[0]; long nPsum = weight->size[1] / accumN; //Check if nPsum is valid THArgCheck(nPsum > 0 && weight->size[1] == nPsum * accumN, 101, "Number of input per convolution should be divisible by accumN, but we got number of input: %ld, accumN: %d, nPsum: %ld", weight->size[1], accumN, nPsum); // Resize output THCTensor_(resize5d)(state, output, batchSize, nOutputPlane, outputHeight, outputWidth, nPsum); // Resize temporary columns THCTensor_(resize2d)(state, columns, nInputPlane*kW*kH, outputHeight*outputWidth); // Helpers THCTensor *input_n = THCTensor_(new)(state); THCTensor *output_n = THCTensor_(new)(state); // set dimension of block and grid dim3 threads(BLOCK_SIZE, BLOCK_SIZE); dim3 grid((nOutputPlane+threads.x-1)/threads.x, (nOutSpatial+threads.y-1)/threads.y); // For each elt in batch, do: for (long elt = 0; elt < batchSize; elt ++) { // Matrix multiply per output: THCTensor_(select)(state, input_n, input, 0, elt); THCTensor_(select)(state, output_n, output, 0, elt); // Extract columns: im2col( THCState_getCurrentStream(state), THCTensor_(data)(state, input_n), nInputPlane, inputHeight, inputWidth, kH, kW, padH, padW, dH, dW, 1, 1, THCTensor_(data)(state, columns) ); // Execute the kernel cunn_CrossbarSpatialConvolution_updateOutput_frame_kernel<real, accreal><<<grid, threads>>>( THCTensor_(data)(state, output_n), THCTensor_(data)(state, columns), THCTensor_(data)(state, weight), accumN, nIn, nOutSpatial, nOutputPlane, nPsum); } // free memorys THCTensor_(free)(state, input_n); THCTensor_(free)(state, output_n); if (freeWeight) THCTensor_(free)(state, weight); // Resize output if (batch == 0) { THCTensor_(resize4d)(state, output, nOutputPlane, outputHeight, outputWidth, nPsum); THCTensor_(resize3d)(state, input, nInputPlane, inputHeight, inputWidth); } THCTensor_(free)(state, input); } #endif
54321c81f7fc638479cb28da8d6ef33e5f385054.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "headers.h" const int SIZE = 2; void printDevProp(hipDeviceProp_t* prop){ printf(".................................................\n\n"); printf("Device Name :- %s\n",prop->name); printf("Wrap size :- %d\n",prop->warpSize); printf("Multi Processor Count :- %d\n",prop->multiProcessorCount); printf("Max threads per block :- %d\n",prop->maxThreadsPerBlock); printf("Total device memory :- %zu\n",prop->totalGlobalMem); printf("Shared memory per block :- %zu\n",prop->sharedMemPerBlock); printf("Max threads dim :- (%d,%d,%d)\n",prop->maxThreadsDim[0],prop->maxThreadsDim[1],prop->maxThreadsDim[2]); printf("Max grid size :- (%d,%d,%d)\n",prop->maxGridSize[0],prop->maxGridSize[1],prop->maxGridSize[2]); printf("\n.................................................\n\n"); } double getWallTime() //stackoverflow { struct timeval time; if(gettimeofday(&time, NULL)) { return 0; } double wallTime = (double)time.tv_sec + (double)time.tv_usec * 0.000001; return wallTime; } void fillArray(float * Arr,const int n){ unsigned int num_max = n*(SIZE*SIZE);//no of elements = #matrices * #elements_per_matrix for(int i = 0;i<num_max;i++){ if(i%10000 == 0) srand(i); Arr[i] = (rand()/(float)(RAND_MAX))/(float(n)/1000); } } void printArray(float * Arr,const int n){ unsigned int num_max = n; for(int i = 0;i<num_max;i++){ if(i%(SIZE*SIZE)==0) printf("\n"); printf("%f ",Arr[i]); } printf("\n"); printf("\n%d elements\n",n); } void naiveImplementation(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls hipError_t err = hipSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); hipLaunchKernelGGL(( naiveKernel), dim3(num_blocks),dim3(threads_per_block),threads_per_block*sizeof(float), 0, d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = hipMemcpy(h_sdata,d_sdata,sdata_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = hipFree(d_A); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = hipFree(d_sdata); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = hipMemcpy(d_sdata, h_sdata,sdata_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = hipMemcpy(result,d_sdata,result_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised1(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls hipError_t err = hipSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); hipLaunchKernelGGL(( optimKernel1), dim3(num_blocks),dim3(threads_per_block),threads_per_block*sizeof(float), 0, d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = hipMemcpy(h_sdata,d_sdata,sdata_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = hipFree(d_A); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = hipFree(d_sdata); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = hipMemcpy(d_sdata, h_sdata,sdata_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = hipMemcpy(result,d_sdata,result_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised2(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls hipError_t err = hipSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); hipLaunchKernelGGL(( optimKernel2), dim3(num_blocks),dim3(threads_per_block),threads_per_block*sizeof(float), 0, d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = hipMemcpy(h_sdata,d_sdata,sdata_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = hipFree(d_A); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = hipFree(d_sdata); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = hipMemcpy(d_sdata, h_sdata,sdata_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = hipMemcpy(result,d_sdata,result_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised3(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls hipError_t err = hipSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); num_blocks = ceil(num_blocks/2.0); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); hipLaunchKernelGGL(( optimKernel3), dim3(num_blocks),dim3(threads_per_block),threads_per_block*sizeof(float), 0, d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = hipMemcpy(h_sdata,d_sdata,sdata_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = hipFree(d_A); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = hipFree(d_sdata); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = hipMemcpy(d_sdata, h_sdata,sdata_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = hipMemcpy(result,d_sdata,result_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised4(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls hipError_t err = hipSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); num_blocks = ceil(num_blocks/2.0); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); hipLaunchKernelGGL(( optimKernel4), dim3(num_blocks),dim3(threads_per_block),threads_per_block*sizeof(float), 0, d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = hipMemcpy(h_sdata,d_sdata,sdata_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = hipFree(d_A); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = hipFree(d_sdata); if (err != hipSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = hipMalloc((void**)&d_A,arr_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = hipMemcpy(d_A, h_A,arr_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = hipMalloc((void**)&d_sdata,sdata_size); if (err != hipSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = hipMemcpy(d_sdata, h_sdata,sdata_size, hipMemcpyHostToDevice); if (err != hipSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = hipMemcpy(result,d_sdata,result_size,hipMemcpyDeviceToHost); if (err != hipSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } int main(){ // Error code to check return values for CUDA calls hipError_t err = hipSuccess; double walltime; int device_count; hipDeviceProp_t* prop; err = hipGetDeviceCount(&device_count); if (err != hipSuccess) { fprintf(stderr, "Failed to get device count (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printf("\nNumber of devices :- %d\n\n",device_count); printf("Device Properties :-\n"); for(int i = 0;i<device_count;i++){ //printf("i : %d\n",i); err = hipGetDeviceProperties(prop,i); if (err != hipSuccess) { fprintf(stderr, "Failed to get device properties (error code %s)!\n", hipGetErrorString(err)); exit(EXIT_FAILURE); } printDevProp(prop); } int warp_size,procs,max_threads_per_block; warp_size = prop->warpSize; procs = prop->multiProcessorCount; max_threads_per_block = prop->maxThreadsPerBlock; //naiveImplementation(warp_size,procs,max_threads_per_block); //optimised1(warp_size,procs,max_threads_per_block); //optimised2(warp_size,procs,max_threads_per_block); optimised3(warp_size,procs,max_threads_per_block); //optimised4(warp_size,procs,max_threads_per_block); ///DOES NOT WORK ATM return 0; }
54321c81f7fc638479cb28da8d6ef33e5f385054.cu
#include "headers.h" const int SIZE = 2; void printDevProp(cudaDeviceProp* prop){ printf(".................................................\n\n"); printf("Device Name :- %s\n",prop->name); printf("Wrap size :- %d\n",prop->warpSize); printf("Multi Processor Count :- %d\n",prop->multiProcessorCount); printf("Max threads per block :- %d\n",prop->maxThreadsPerBlock); printf("Total device memory :- %zu\n",prop->totalGlobalMem); printf("Shared memory per block :- %zu\n",prop->sharedMemPerBlock); printf("Max threads dim :- (%d,%d,%d)\n",prop->maxThreadsDim[0],prop->maxThreadsDim[1],prop->maxThreadsDim[2]); printf("Max grid size :- (%d,%d,%d)\n",prop->maxGridSize[0],prop->maxGridSize[1],prop->maxGridSize[2]); printf("\n.................................................\n\n"); } double getWallTime() //stackoverflow { struct timeval time; if(gettimeofday(&time, NULL)) { return 0; } double wallTime = (double)time.tv_sec + (double)time.tv_usec * 0.000001; return wallTime; } void fillArray(float * Arr,const int n){ unsigned int num_max = n*(SIZE*SIZE);//no of elements = #matrices * #elements_per_matrix for(int i = 0;i<num_max;i++){ if(i%10000 == 0) srand(i); Arr[i] = (rand()/(float)(RAND_MAX))/(float(n)/1000); } } void printArray(float * Arr,const int n){ unsigned int num_max = n; for(int i = 0;i<num_max;i++){ if(i%(SIZE*SIZE)==0) printf("\n"); printf("%f ",Arr[i]); } printf("\n"); printf("\n%d elements\n",n); } void naiveImplementation(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls cudaError_t err = cudaSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); naiveKernel<<<num_blocks,threads_per_block,threads_per_block*sizeof(float)>>>(d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = cudaMemcpy(h_sdata,d_sdata,sdata_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = cudaFree(d_A); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = cudaFree(d_sdata); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = cudaMemcpy(d_sdata, h_sdata,sdata_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = cudaMemcpy(result,d_sdata,result_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised1(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls cudaError_t err = cudaSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); optimKernel1<<<num_blocks,threads_per_block,threads_per_block*sizeof(float)>>>(d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = cudaMemcpy(h_sdata,d_sdata,sdata_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = cudaFree(d_A); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = cudaFree(d_sdata); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = cudaMemcpy(d_sdata, h_sdata,sdata_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = cudaMemcpy(result,d_sdata,result_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised2(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls cudaError_t err = cudaSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); optimKernel2<<<num_blocks,threads_per_block,threads_per_block*sizeof(float)>>>(d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = cudaMemcpy(h_sdata,d_sdata,sdata_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = cudaFree(d_A); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = cudaFree(d_sdata); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = cudaMemcpy(d_sdata, h_sdata,sdata_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = cudaMemcpy(result,d_sdata,result_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised3(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls cudaError_t err = cudaSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); num_blocks = ceil(num_blocks/2.0); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); optimKernel3<<<num_blocks,threads_per_block,threads_per_block*sizeof(float)>>>(d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = cudaMemcpy(h_sdata,d_sdata,sdata_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = cudaFree(d_A); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = cudaFree(d_sdata); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = cudaMemcpy(d_sdata, h_sdata,sdata_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = cudaMemcpy(result,d_sdata,result_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } void optimised4(const int warp_size,const int procs,const int max_threads_per_block){ int n; int response; // Error code to check return values for CUDA calls cudaError_t err = cudaSuccess; size_t arr_size; printf("Enter no of Arrays : "); scanf("%d",&n); //Defining the matrices float* h_A; arr_size = (SIZE*SIZE)*n*sizeof(float); h_A = (float*)malloc(arr_size); fillArray(h_A,n); // Allocate the device input vector A float *d_A = NULL; err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Defining the blocksize and the grid size int threads_per_block = warp_size*(max_threads_per_block/warp_size); int num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); num_blocks = ceil(num_blocks/2.0); //Defining h_sdata; float* h_sdata; size_t sdata_size = (SIZE*SIZE)*num_blocks*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device vector sdata float *d_sdata = NULL; err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_A , arr_size/(sizeof(float))); //Main recursive kernel invocation while(1){ //Kernel Invocation printf("Launched kernel with %d blocks and %d threads per block \n",num_blocks,threads_per_block); optimKernel4<<<num_blocks,threads_per_block,threads_per_block*sizeof(float)>>>(d_A,d_sdata,n*(SIZE*SIZE)); //Updation steps //............. //Copying back output array err = cudaMemcpy(h_sdata,d_sdata,sdata_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy output array from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printArray(h_sdata,sdata_size/sizeof(float)); //TERMINATION STATEMENT if(sdata_size == SIZE*SIZE*sizeof(float)) break; //Freeing unused memory free(h_A); err = cudaFree(d_A); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Freeing unused memory err = cudaFree(d_sdata); if (err != cudaSuccess) { fprintf(stderr, "Failed to free device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //updation of n and num_blocks n = num_blocks; num_blocks = ceil(n*(SIZE*SIZE)/(float)threads_per_block); //Generating input for the next iter. arr_size = sdata_size; h_A = h_sdata; // Allocate the device input vector A err = cudaMalloc((void**)&d_A,arr_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector A (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } // Copy the host input vector A in host memory to the device printf("Copy input data from the host memory to the CUDA device\n"); err = cudaMemcpy(d_A, h_A,arr_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array A from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //printArray(h_A , arr_size/(sizeof(float))); //Generating the output vector for the next iteration free(h_sdata); sdata_size = num_blocks*(SIZE*SIZE)*sizeof(float); h_sdata = (float*)malloc(sdata_size); // Allocate the device output vector sdata err = cudaMalloc((void**)&d_sdata,sdata_size); if (err != cudaSuccess) { fprintf(stderr, "Failed to allocate device vector sdata (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } //Copying the new output vector to device printf("Coping output array from the host memory to the CUDA device\n"); err = cudaMemcpy(d_sdata, h_sdata,sdata_size, cudaMemcpyHostToDevice); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy array sdata from host to device (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } } //float *result; /*{ result = (float*)malloc(SIZE*SIZE*sizeof(float)); size_t result_size = SIZE*SIZE*sizeof(float); printf("\n\nAnswer :- \n\n"); //Copying back output array err = cudaMemcpy(result,d_sdata,result_size,cudaMemcpyDeviceToHost); if (err != cudaSuccess) { fprintf(stderr, "Failed to copy matrix from device to host (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } }*/ printf("Result :- \n"); printArray(h_sdata , SIZE*SIZE); } int main(){ // Error code to check return values for CUDA calls cudaError_t err = cudaSuccess; double walltime; int device_count; cudaDeviceProp* prop; err = cudaGetDeviceCount(&device_count); if (err != cudaSuccess) { fprintf(stderr, "Failed to get device count (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printf("\nNumber of devices :- %d\n\n",device_count); printf("Device Properties :-\n"); for(int i = 0;i<device_count;i++){ //printf("i : %d\n",i); err = cudaGetDeviceProperties(prop,i); if (err != cudaSuccess) { fprintf(stderr, "Failed to get device properties (error code %s)!\n", cudaGetErrorString(err)); exit(EXIT_FAILURE); } printDevProp(prop); } int warp_size,procs,max_threads_per_block; warp_size = prop->warpSize; procs = prop->multiProcessorCount; max_threads_per_block = prop->maxThreadsPerBlock; //naiveImplementation(warp_size,procs,max_threads_per_block); //optimised1(warp_size,procs,max_threads_per_block); //optimised2(warp_size,procs,max_threads_per_block); optimised3(warp_size,procs,max_threads_per_block); //optimised4(warp_size,procs,max_threads_per_block); ///DOES NOT WORK ATM return 0; }
9d375328c806d6b8b05ba91c65cfa2bac0be064e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* This is machine problem 2, part 2: brute force k nearest neighbors * You are given a large number of particles, and are asked * to find the k particles that are nearest to each one. * Look at the example in /tutorials/thread_local_variables.cu * for how you can use per thread arrays for sorting. * Using that example, port the cpu reference code to the gpu in a first step. * In a second step, modify your code so that the per-thread arrays are in * shared memory. You should submit this second version of your code. */ /* * SUBMISSION INSTRUCTIONS * ========================= * * You can submit the assignment from any of the cluster machines by using * our submit script. Th submit script bundles the entire current directory into * a submission. Thus, you use it by CDing to a the directory for your assignment, * and running: * * > cd *some directory* * > /usr/class/cs193g/bin/submit mp2 * * This will submit the current directory as your assignment. You can submit * as many times as you want, and we will use your last submission. */ #include <cassert> #include "mp2-util.h" // TODO enable this to print debugging information //const bool print_debug = true; const bool print_debug = false; event_pair timer; inline __device__ __host__ float3 operator -(float3 a, float3 b) { return make_float3(a.x-b.x, a.y-b.y, a.z-b.z); } __host__ __device__ float dist2(float3 a, float3 b) { float3 d = a - b; float d2 = d.x*d.x + d.y*d.y + d.z*d.z; return d2; } template <typename T> __host__ __device__ void init_list(T *base_ptr, unsigned int size, T val) { for(int i=0;i<size;i++) { base_ptr[i] = val; } } __host__ __device__ void insert_list(float *dist_list, int *id_list, int size, float dist, int id) { int k; for (k=0; k < size; k++) { if (dist < dist_list[k]) { // we should insert it in here, so push back and make it happen for (int j = size - 1; j > k ; j--) { dist_list[j] = dist_list[j-1]; id_list[j] = id_list[j-1]; } dist_list[k] = dist; id_list[k] = id; break; } } } template <int num_neighbors> void host_find_knn(float3 *particles, int *knn, int array_length) { for(int i=0;i<array_length;i++) { float3 p = particles[i]; float neigh_dist[num_neighbors]; int neigh_ids[num_neighbors]; init_list(&neigh_dist[0],num_neighbors,2.0f); init_list(&neigh_ids[0],num_neighbors,-1); for(int j=0;j<array_length;j++) { if(i != j) { float rsq = dist2(p,particles[j]); insert_list(&neigh_dist[0], &neigh_ids[0], num_neighbors, rsq, j); } } for(int j=0;j<num_neighbors;j++) { knn[num_neighbors*i + j] = neigh_ids[j]; } } } template <int num_neighbors> __global__ void device_find_knn_local_mem(float3 *particles, int *knn, int array_length) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i >= array_length) return; { float3 p = particles[i]; float neigh_dist[num_neighbors]; int neigh_ids[num_neighbors]; init_list(&neigh_dist[0],num_neighbors,2.0f); init_list(&neigh_ids[0],num_neighbors,-1); for(int j=0;j<array_length;j++) { if(i != j) { float rsq = dist2(p,particles[j]); insert_list(&neigh_dist[0], &neigh_ids[0], num_neighbors, rsq, j); } } for(int j=0;j<num_neighbors;j++) { knn[num_neighbors*i + j] = neigh_ids[j]; } } } template <int num_neighbors> __global__ void device_find_knn_shared_mem(float3 *particles, int *knn, int array_length) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i >= array_length) return; { float3 p = particles[i]; extern __shared__ float neigh_dist[]; int * neigh_ids = (int*)&neigh_dist[num_neighbors]; init_list(&neigh_dist[0],num_neighbors,2.0f); init_list(&neigh_ids[0],num_neighbors,-1); for(int j=0;j<array_length;j++) { if(i != j) { float rsq = dist2(p,particles[j]); insert_list(&neigh_dist[0], &neigh_ids[0], num_neighbors, rsq, j); } } for(int j=0;j<num_neighbors;j++) { knn[num_neighbors*i + j] = neigh_ids[j]; } } } void allocate_host_memory(int num_particles, int num_neighbors, float3 *&h_particles, int *&h_knn, int *&h_knn_checker) { // malloc host array h_particles = (float3*)malloc(num_particles * sizeof(float3)); h_knn = (int*)malloc(num_particles * num_neighbors * sizeof(int)); h_knn_checker = (int*)malloc(num_particles * num_neighbors * sizeof(int)); // if either memory allocation failed, report an error message if(h_particles == 0 || h_knn == 0 || h_knn_checker == 0) { printf("couldn't allocate host memory\n"); exit(1); } } #define CHECK(call) { \ hipError_t err = hipSuccess; \ if ( (err = (call)) != hipSuccess) { \ fprintf(stderr, "Got error %s at %s:%d\n", hipGetErrorString(err), __FILE__, __LINE__); \ exit(1); \ }\ } void allocate_device_memory(int num_particles, int num_neighbors, float3 *&d_particles, int *&d_knn) { // device memory allocations here CHECK(hipMalloc((void**)&d_particles, num_particles * sizeof(float3))); CHECK(hipMalloc((void**)&d_knn, num_particles * num_neighbors * sizeof(int))); } void deallocate_host_memory(float3 *h_particles, int *h_knn, int *h_knn_checker) { free(h_particles); free(h_knn); free(h_knn_checker); } void deallocate_device_memory(float3 *d_particles, int *d_knn) { // device memory deallocations here CHECK(hipFree(d_particles)); CHECK(hipFree(d_knn)); } bool cross_check_results(int * reference_knn, int * knn, int num_particles, int num_neighbors) { int error = 0; for(int i=0;i<num_particles;i++) { for(int j=0;j<num_neighbors;j++) { if(reference_knn[i*num_neighbors + j] != knn[i*num_neighbors + j]) { if(print_debug) printf("particle %d, neighbor %d is %d on cpu, %d on gpu\n",i,j,reference_knn[i*num_neighbors + j],knn[i*num_neighbors + j]); error = 1; } } } if(error) { printf("Output of CUDA version and normal version didn't match! \n"); } else { printf("Worked! CUDA and reference output match. \n"); } return error; } int main(void) { // create arrays of 8K elements int num_particles = 20*1024; const int num_neighbors = 5; // pointers to host arrays float3 *h_particles = 0; int *h_knn = 0; int *h_knn_checker = 0; // pointers to device arrays float3 *d_particles = 0; int *d_knn = 0; allocate_host_memory(num_particles, num_neighbors, h_particles, h_knn, h_knn_checker); allocate_device_memory(num_particles, num_neighbors, d_particles, d_knn); // generate random input // initialize srand(13); for(int i=0;i< num_particles;i++) { h_particles[i] = make_float3((float)rand()/(float)RAND_MAX,(float)rand()/(float)RAND_MAX,(float)rand()/(float)RAND_MAX); } // copy input to GPU start_timer(&timer); //copy of input from host to device here CHECK(hipMemcpy(d_particles,h_particles, num_particles * sizeof (float3), hipMemcpyHostToDevice)); CHECK(hipMemcpy(d_knn,h_knn, num_particles * num_neighbors * sizeof (int), hipMemcpyHostToDevice)); stop_timer(&timer,"copy to gpu"); dim3 THRD_SZ(512); dim3 GRID_SZ((num_particles + THRD_SZ.x-1)/THRD_SZ.x); start_timer(&timer); // kernel launch which uses local memory hipLaunchKernelGGL(( device_find_knn_local_mem<num_neighbors>), dim3(GRID_SZ), dim3(THRD_SZ), 0, 0, d_particles, d_knn, num_particles); check_cuda_error("brute force knn"); stop_timer(&timer,"brute force knn"); start_timer(&timer); // kernel launch which uses __shared__ memory int shmem_size = THRD_SZ.x * (sizeof (float) + sizeof(int)) * num_neighbors; hipLaunchKernelGGL(( device_find_knn_shared_mem<num_neighbors>), dim3(GRID_SZ), dim3(shmem_size), 0, 0, d_particles, d_knn, num_particles); check_cuda_error("shared meme knn"); stop_timer(&timer,"shared mem knn"); // download and inspect the result on the host start_timer(&timer); // copy results from device to host here hipMemcpy(h_knn,d_knn, num_particles * num_neighbors * sizeof (int), hipMemcpyDeviceToHost); check_cuda_error("copy from gpu"); stop_timer(&timer,"copy back from gpu memory"); // generate reference output start_timer(&timer); host_find_knn<num_neighbors>(h_particles, h_knn_checker, num_particles); stop_timer(&timer,"cpu brute force knn"); // check CUDA output versus reference output cross_check_results(h_knn_checker, h_knn, num_particles, num_neighbors); deallocate_host_memory(h_particles, h_knn, h_knn_checker); deallocate_device_memory(d_particles, d_knn); return 0; }
9d375328c806d6b8b05ba91c65cfa2bac0be064e.cu
/* This is machine problem 2, part 2: brute force k nearest neighbors * You are given a large number of particles, and are asked * to find the k particles that are nearest to each one. * Look at the example in /tutorials/thread_local_variables.cu * for how you can use per thread arrays for sorting. * Using that example, port the cpu reference code to the gpu in a first step. * In a second step, modify your code so that the per-thread arrays are in * shared memory. You should submit this second version of your code. */ /* * SUBMISSION INSTRUCTIONS * ========================= * * You can submit the assignment from any of the cluster machines by using * our submit script. Th submit script bundles the entire current directory into * a submission. Thus, you use it by CDing to a the directory for your assignment, * and running: * * > cd *some directory* * > /usr/class/cs193g/bin/submit mp2 * * This will submit the current directory as your assignment. You can submit * as many times as you want, and we will use your last submission. */ #include <cassert> #include "mp2-util.h" // TODO enable this to print debugging information //const bool print_debug = true; const bool print_debug = false; event_pair timer; inline __device__ __host__ float3 operator -(float3 a, float3 b) { return make_float3(a.x-b.x, a.y-b.y, a.z-b.z); } __host__ __device__ float dist2(float3 a, float3 b) { float3 d = a - b; float d2 = d.x*d.x + d.y*d.y + d.z*d.z; return d2; } template <typename T> __host__ __device__ void init_list(T *base_ptr, unsigned int size, T val) { for(int i=0;i<size;i++) { base_ptr[i] = val; } } __host__ __device__ void insert_list(float *dist_list, int *id_list, int size, float dist, int id) { int k; for (k=0; k < size; k++) { if (dist < dist_list[k]) { // we should insert it in here, so push back and make it happen for (int j = size - 1; j > k ; j--) { dist_list[j] = dist_list[j-1]; id_list[j] = id_list[j-1]; } dist_list[k] = dist; id_list[k] = id; break; } } } template <int num_neighbors> void host_find_knn(float3 *particles, int *knn, int array_length) { for(int i=0;i<array_length;i++) { float3 p = particles[i]; float neigh_dist[num_neighbors]; int neigh_ids[num_neighbors]; init_list(&neigh_dist[0],num_neighbors,2.0f); init_list(&neigh_ids[0],num_neighbors,-1); for(int j=0;j<array_length;j++) { if(i != j) { float rsq = dist2(p,particles[j]); insert_list(&neigh_dist[0], &neigh_ids[0], num_neighbors, rsq, j); } } for(int j=0;j<num_neighbors;j++) { knn[num_neighbors*i + j] = neigh_ids[j]; } } } template <int num_neighbors> __global__ void device_find_knn_local_mem(float3 *particles, int *knn, int array_length) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i >= array_length) return; { float3 p = particles[i]; float neigh_dist[num_neighbors]; int neigh_ids[num_neighbors]; init_list(&neigh_dist[0],num_neighbors,2.0f); init_list(&neigh_ids[0],num_neighbors,-1); for(int j=0;j<array_length;j++) { if(i != j) { float rsq = dist2(p,particles[j]); insert_list(&neigh_dist[0], &neigh_ids[0], num_neighbors, rsq, j); } } for(int j=0;j<num_neighbors;j++) { knn[num_neighbors*i + j] = neigh_ids[j]; } } } template <int num_neighbors> __global__ void device_find_knn_shared_mem(float3 *particles, int *knn, int array_length) { int i = blockDim.x * blockIdx.x + threadIdx.x; if (i >= array_length) return; { float3 p = particles[i]; extern __shared__ float neigh_dist[]; int * neigh_ids = (int*)&neigh_dist[num_neighbors]; init_list(&neigh_dist[0],num_neighbors,2.0f); init_list(&neigh_ids[0],num_neighbors,-1); for(int j=0;j<array_length;j++) { if(i != j) { float rsq = dist2(p,particles[j]); insert_list(&neigh_dist[0], &neigh_ids[0], num_neighbors, rsq, j); } } for(int j=0;j<num_neighbors;j++) { knn[num_neighbors*i + j] = neigh_ids[j]; } } } void allocate_host_memory(int num_particles, int num_neighbors, float3 *&h_particles, int *&h_knn, int *&h_knn_checker) { // malloc host array h_particles = (float3*)malloc(num_particles * sizeof(float3)); h_knn = (int*)malloc(num_particles * num_neighbors * sizeof(int)); h_knn_checker = (int*)malloc(num_particles * num_neighbors * sizeof(int)); // if either memory allocation failed, report an error message if(h_particles == 0 || h_knn == 0 || h_knn_checker == 0) { printf("couldn't allocate host memory\n"); exit(1); } } #define CHECK(call) { \ cudaError_t err = cudaSuccess; \ if ( (err = (call)) != cudaSuccess) { \ fprintf(stderr, "Got error %s at %s:%d\n", cudaGetErrorString(err), __FILE__, __LINE__); \ exit(1); \ }\ } void allocate_device_memory(int num_particles, int num_neighbors, float3 *&d_particles, int *&d_knn) { // device memory allocations here CHECK(cudaMalloc((void**)&d_particles, num_particles * sizeof(float3))); CHECK(cudaMalloc((void**)&d_knn, num_particles * num_neighbors * sizeof(int))); } void deallocate_host_memory(float3 *h_particles, int *h_knn, int *h_knn_checker) { free(h_particles); free(h_knn); free(h_knn_checker); } void deallocate_device_memory(float3 *d_particles, int *d_knn) { // device memory deallocations here CHECK(cudaFree(d_particles)); CHECK(cudaFree(d_knn)); } bool cross_check_results(int * reference_knn, int * knn, int num_particles, int num_neighbors) { int error = 0; for(int i=0;i<num_particles;i++) { for(int j=0;j<num_neighbors;j++) { if(reference_knn[i*num_neighbors + j] != knn[i*num_neighbors + j]) { if(print_debug) printf("particle %d, neighbor %d is %d on cpu, %d on gpu\n",i,j,reference_knn[i*num_neighbors + j],knn[i*num_neighbors + j]); error = 1; } } } if(error) { printf("Output of CUDA version and normal version didn't match! \n"); } else { printf("Worked! CUDA and reference output match. \n"); } return error; } int main(void) { // create arrays of 8K elements int num_particles = 20*1024; const int num_neighbors = 5; // pointers to host arrays float3 *h_particles = 0; int *h_knn = 0; int *h_knn_checker = 0; // pointers to device arrays float3 *d_particles = 0; int *d_knn = 0; allocate_host_memory(num_particles, num_neighbors, h_particles, h_knn, h_knn_checker); allocate_device_memory(num_particles, num_neighbors, d_particles, d_knn); // generate random input // initialize srand(13); for(int i=0;i< num_particles;i++) { h_particles[i] = make_float3((float)rand()/(float)RAND_MAX,(float)rand()/(float)RAND_MAX,(float)rand()/(float)RAND_MAX); } // copy input to GPU start_timer(&timer); //copy of input from host to device here CHECK(cudaMemcpy(d_particles,h_particles, num_particles * sizeof (float3), cudaMemcpyHostToDevice)); CHECK(cudaMemcpy(d_knn,h_knn, num_particles * num_neighbors * sizeof (int), cudaMemcpyHostToDevice)); stop_timer(&timer,"copy to gpu"); dim3 THRD_SZ(512); dim3 GRID_SZ((num_particles + THRD_SZ.x-1)/THRD_SZ.x); start_timer(&timer); // kernel launch which uses local memory device_find_knn_local_mem<num_neighbors><<<GRID_SZ, THRD_SZ>>>(d_particles, d_knn, num_particles); check_cuda_error("brute force knn"); stop_timer(&timer,"brute force knn"); start_timer(&timer); // kernel launch which uses __shared__ memory int shmem_size = THRD_SZ.x * (sizeof (float) + sizeof(int)) * num_neighbors; device_find_knn_shared_mem<num_neighbors><<<GRID_SZ, shmem_size>>>(d_particles, d_knn, num_particles); check_cuda_error("shared meme knn"); stop_timer(&timer,"shared mem knn"); // download and inspect the result on the host start_timer(&timer); // copy results from device to host here cudaMemcpy(h_knn,d_knn, num_particles * num_neighbors * sizeof (int), cudaMemcpyDeviceToHost); check_cuda_error("copy from gpu"); stop_timer(&timer,"copy back from gpu memory"); // generate reference output start_timer(&timer); host_find_knn<num_neighbors>(h_particles, h_knn_checker, num_particles); stop_timer(&timer,"cpu brute force knn"); // check CUDA output versus reference output cross_check_results(h_knn_checker, h_knn, num_particles, num_neighbors); deallocate_host_memory(h_particles, h_knn, h_knn_checker); deallocate_device_memory(d_particles, d_knn); return 0; }
41b6a03787ebbd6e2a2d44564d8a4fdae160e50d.hip
// !!! This is a file automatically generated by hipify!!! /* * SourceTerms.cu * * Created on: Oct 22, 2015 * Author: bazow */ #include <stdio.h> // for printf #include <math.h> // for math functions #include <hip/hip_runtime.h> #include <hip/hip_runtime.h> #include "../include/SourceTerms.cuh" #include "../include/FiniteDifference.cuh" #include "../include/EnergyMomentumTensor.cuh" #include "../include/DynamicalVariables.cuh" #include "../include/CudaConfiguration.cuh" #include "../include/EquationOfState.cuh" // for bulk terms #include "../include/TransportCoefficients.cuh" #include "../include/AnisotropicDistributionFunctions.cuh" //#define USE_CARTESIAN_COORDINATES /* // paramters for the analytic parameterization of the bulk viscosity \zeta/S #define A_1 -13.77 #define A_2 27.55 #define A_3 13.45 #define LAMBDA_1 0.9 #define LAMBDA_2 0.25 #define LAMBDA_3 0.9 #define LAMBDA_4 0.22 #define SIGMA_1 0.025 #define SIGMA_2 0.13 #define SIGMA_3 0.0025 #define SIGMA_4 0.022 inline PRECISION bulkViscosityToEntropyDensity(PRECISION T) { PRECISION x = T/1.01355; if(x > 1.05) return LAMBDA_1*exp(-(x-1)/SIGMA_1) + LAMBDA_2*exp(-(x-1)/SIGMA_2)+0.001; else if(x < 0.995) return LAMBDA_3*exp((x-1)/SIGMA_3)+ LAMBDA_4*exp((x-1)/SIGMA_4)+0.03; else return A_1*x*x + A_2*x - A_3; } */ __device__ void setPimunuSourceTerms(PRECISION * const __restrict__ pimunuRHS, PRECISION t, PRECISION e, PRECISION p, PRECISION ut, PRECISION ux, PRECISION uy, PRECISION un, PRECISION utp, PRECISION uxp, PRECISION uyp, PRECISION unp, PRECISION pitt, PRECISION pitx, PRECISION pity, PRECISION pitn, PRECISION pixx, PRECISION pixy, PRECISION pixn, PRECISION piyy, PRECISION piyn, PRECISION pinn, PRECISION Pi, PRECISION dxut, PRECISION dyut, PRECISION dnut, PRECISION dxux, PRECISION dyux, PRECISION dnux, PRECISION dxuy, PRECISION dyuy, PRECISION dnuy, PRECISION dxun, PRECISION dyun, PRECISION dnun, PRECISION dkvk) { /*********************************************************\ * Temperature dependent shear transport coefficients /*********************************************************/ PRECISION T = effectiveTemperature(e); PRECISION taupiInv = 0.2f * fdividef(T, d_etabar); PRECISION beta_pi = 0.2f * (e + p); /*********************************************************\ * Temperature dependent bulk transport coefficients /*********************************************************/ PRECISION cs2 = speedOfSoundSquared(e); PRECISION a = 0.333333f - cs2; PRECISION a2 = a * a; PRECISION beta_Pi = 15 * a2 * (e + p); PRECISION lambda_Pipi = 1.6f * a; PRECISION zetabar = bulkViscosityToEntropyDensity(T); PRECISION tauPiInv = 15 * a2 * fdividef(T, zetabar); PRECISION ut2 = ut * ut; PRECISION un2 = un * un; PRECISION t2 = t * t; PRECISION t3 = t * t2; // time derivatives of u PRECISION dtut = (ut - utp) / d_dt; PRECISION dtux = (ux - uxp) / d_dt; PRECISION dtuy = (uy - uyp) / d_dt; PRECISION dtun = (un - unp) / d_dt; /*********************************************************\ * covariant derivatives /*********************************************************/ PRECISION Dut = ut * dtut + ux * dxut + uy * dyut + un * dnut + t * un * un; PRECISION dut = Dut - t * un * un; PRECISION dux = ut * dtux + ux * dxux + uy * dyux + un * dnux; PRECISION Dux = -dux; PRECISION duy = ut * dtuy + ux * dxuy + uy * dyuy + un * dnuy; PRECISION Duy = -duy; PRECISION dun = ut * dtun + ux * dxun + uy * dyun + un * dnun; PRECISION Dun = -t2 * dun - 2 * t * ut * un; /*********************************************************\ * expansion rate /*********************************************************/ PRECISION theta = ut / t + dtut + dxux + dyuy + dnun; /*********************************************************\ * Velocity shear stress tensor /*********************************************************/ PRECISION theta3 = theta / 3; PRECISION stt = -t * ut * un2 + (dtut - ut * dut) + (ut2 - 1) * theta3; PRECISION stx = -(t * un2 * ux) / 2 + (dtux - dxut) / 2 - (ux * dut + ut * dux) / 2 + ut * ux * theta3; PRECISION sty = -(t * un2 * uy) / 2 + (dtuy - dyut) / 2 - (uy * dut + ut * duy) / 2 + ut * uy * theta3; PRECISION stn = -un * (2 * ut2 + t2 * un2) / (2 * t) + (dtun - dnut / t2) / 2 - (un * dut + ut * dun) / 2 + ut * un * theta3; PRECISION sxx = -(dxux + ux * dux) + (1 + ux * ux) * theta3; PRECISION sxy = -(dxuy + dyux) / 2 - (uy * dux + ux * duy) / 2 + ux * uy * theta3; PRECISION sxn = -ut * ux * un / t - (dxun + dnux / t2) / 2 - (un * dux + ux * dun) / 2 + ux * un * theta3; PRECISION syy = -(dyuy + uy * duy) + (1 + uy * uy) * theta3; PRECISION syn = -ut * uy * un / t - (dyun + dnuy / t2) / 2 - (un * duy + uy * dun) / 2 + uy * un * theta3; PRECISION snn = -ut * (1 + 2 * t2 * un2) / t3 - dnun / t2 - un * dun + (1 / t2 + un2) * theta3; /*********************************************************\ * vorticity tensor /*********************************************************/ PRECISION wtx = (dtux + dxut) / 2 + (ux * dut - ut * dux) / 2 + t * un2 * ux / 2; PRECISION wty = (dtuy + dyut) / 2 + (uy * dut - ut * duy) / 2 + t * un2 * uy / 2; PRECISION wtn = (t2 * dtun + 2 * t * un + dnut) / 2 + (t2 * un * dut - ut * Dun) + t3 * un * un2 / 2; PRECISION wxy = (dyux - dxuy) / 2 + (uy * dux - ux * duy) / 2; PRECISION wxn = (dnux - t2 * dxun) / 2 + (t2 * un * dux - ux * Dun) / 2; PRECISION wyn = (dnuy - t2 * dyun) / 2 + (t2 * un * duy - uy * Dun) / 2; // anti-symmetric vorticity components PRECISION wxt = wtx; PRECISION wyt = wty; PRECISION wnt = wtn / t2; PRECISION wyx = -wxy; PRECISION wnx = -wxn / t2; PRECISION wny = -wyn / t2; /*********************************************************\ * I1 /*********************************************************/ PRECISION I1tt = 2 * ut * (pitt * Dut + pitx * Dux + pity * Duy + pitn * Dun); PRECISION I1tx = (pitt * ux + pitx * ut) * Dut + (pitx * ux + pixx * ut) * Dux + (pity * ux + pixy * ut) * Duy + (pitn * ux + pixn * ut) * Dun; PRECISION I1ty = (pitt * uy + pity * ut) * Dut + (pitx * uy + pixy * ut) * Dux + (pity * uy + piyy * ut) * Duy + (pitn * uy + piyn * ut) * Dun; PRECISION I1tn = (pitt * un + pitn * ut) * Dut + (pitx * un + pixn * ut) * Dux + (pity * un + piyn * ut) * Duy + (pitn * un + pinn * ut) * Dun; PRECISION I1xx = 2 * ux * (pitx * Dut + pixx * Dux + pixy * Duy + pixn * Dun); PRECISION I1xy = (pitx * uy + pity * ux) * Dut + (pixx * uy + pixy * ux) * Dux + (pixy * uy + piyy * ux) * Duy + (pixn * uy + piyn * ux) * Dun; PRECISION I1xn = (pitx * un + pitn * ux) * Dut + (pixx * un + pixn * ux) * Dux + (pixy * un + piyn * ux) * Duy + (pixn * un + pinn * ux) * Dun; PRECISION I1yy = 2 * uy * (pity * Dut + pixy * Dux + piyy * Duy + piyn * Dun); PRECISION I1yn = (pity * un + pitn * uy) * Dut + (pixy * un + pixn * uy) * Dux + (piyy * un + piyn * uy) * Duy + (piyn * un + pinn * uy) * Dun; PRECISION I1nn = 2 * un * (pitn * Dut + pixn * Dux + piyn * Duy + pinn * Dun); /*********************************************************\ * I2 /*********************************************************/ PRECISION I2tt = theta * pitt; PRECISION I2tx = theta * pitx; PRECISION I2ty = theta * pity; PRECISION I2tn = theta * pitn; PRECISION I2xx = theta * pixx; PRECISION I2xy = theta * pixy; PRECISION I2xn = theta * pixn; PRECISION I2yy = theta * piyy; PRECISION I2yn = theta * piyn; PRECISION I2nn = theta * pinn; /*********************************************************\ * I3 /*********************************************************/ PRECISION I3tt = 2 * (pitx * wtx + pity * wty + pitn * wtn); PRECISION I3tx = pitt * wxt + pity * wxy + pitn * wxn + pixx * wtx + pixy * wty + pixn * wtn; PRECISION I3ty = pitt * wyt + pitx * wyx + pitn * wyn + pixy * wtx + piyy * wty + piyn * wtn; PRECISION I3tn = pitt * wnt + pitx * wnx + pity * wny + pixn * wtx + piyn * wty + pinn * wtn; PRECISION I3xx = 2 * (pitx * wxt + pixy * wxy + pixn * wxn); PRECISION I3xy = pitx * wyt + pity * wxt + pixx * wyx + piyy * wxy + pixn * wyn + piyn * wxn; PRECISION I3xn = pitx * wnt + pitn * wxt + pixx * wnx + pixy * wny + piyn * wxy + pinn * wxn; PRECISION I3yy = 2 * (pity * wyt + pixy * wyx + piyn * wyn); PRECISION I3yn = pity * wnt + pitn * wyt + pixy * wnx + pixn * wyx + piyy * wny + pinn * wyn; PRECISION I3nn = 2 * (pitn * wnt + pixn * wnx + piyn * wny); /*********************************************************\ * I4 /*********************************************************/ PRECISION ux2 = ux * ux; PRECISION uy2 = uy * uy; PRECISION ps = pitt * stt - 2 * pitx * stx - 2 * pity * sty + pixx * sxx + 2 * pixy * sxy + piyy * syy - 2 * pitn * stn * t2 + 2 * pixn * sxn * t2 + 2 * piyn * syn * t2 + pinn * snn * t2 * t2; PRECISION ps3 = ps / 3; PRECISION I4tt = (pitt * stt - pitx * stx - pity * sty - t2 * pitn * stn) - (1 - ut2) * ps3; PRECISION I4tx = (pitt * stx + pitx * stt) / 2 - (pitx * sxx + pixx * stx) / 2 - (pity * sxy + pixy * sty) / 2 - t2 * (pitn * sxn + pixn * stn) / 2 + (ut * ux) * ps3; PRECISION I4ty = (pitt * sty + pity * stt) / 2 - (pitx * sxy + pixy * stx) / 2 - (pity * syy + piyy * sty) / 2 - t2 * (pitn * syn + piyn * stn) / 2 + (ut * uy) * ps3; PRECISION I4tn = (pitt * stn + pitn * stt) / 2 - (pitx * sxn + pixn * stx) / 2 - (pity * syn + piyn * sty) / 2 - t2 * (pitn * snn + pinn * stn) / 2 + (ut * un) * ps3; PRECISION I4xx = (pitx * stx - pixx * sxx - pixy * sxy - t2 * pixn * sxn) + (1 + ux2) * ps3; PRECISION I4xy = (pitx * sty + pity * stx) / 2 - (pixx * sxy + pixy * sxx) / 2 - (pixy * syy + piyy * sxy) / 2 - t2 * (pixn * syn + piyn * sxn) / 2 + (ux * uy) * ps3; PRECISION I4xn = (pitx * stn + pitn * stx) / 2 - (pixx * sxn + pixn * sxx) / 2 - (pixy * syn + piyn * sxy) / 2 - t2 * (pixn * snn + pinn * sxn) / 2 + (ux * un) * ps3; PRECISION I4yy = (pity * sty - pixy * sxy - piyy * syy - t2 * piyn * syn) + (1 + uy2) * ps3; PRECISION I4yn = (pity * stn + pitn * sty) / 2 - (pixy * sxn + pixn * sxy) / 2 - (piyy * syn + piyn * syy) / 2 - t2 * (piyn * snn + pinn * syn) / 2 + (uy * un) * ps3; PRECISION I4nn = (pitn * stn - pixn * sxn - piyn * syn - t2 * pinn * snn) + (1 / t2 + un2) * ps3; /*********************************************************\ * I /*********************************************************/ // PRECISION ps = 0; /* // PRECISION ps = pitt*stt + 2*(pixy*sxy - pitx*stx - pity*sty + (pixn*sxn + piyn*syn - pitn*stn)*t2) + pixx*sxx + piyy*syy + pinn*snn*t2*t2; PRECISION ps = pitt*stt-2*pitx*stx-2*pity*sty+pixx*sxx+2*pixy*sxy+piyy*syy-2*pitn*stn*t2+2*pixn*sxn*t2+2*piyn*syn*t2+pinn*snn*t2*t2; PRECISION I4tt = 0; PRECISION I4tx = 0; PRECISION I4ty = 0; PRECISION I4tn = 0; PRECISION I4xx = 0; PRECISION I4xy = 0; PRECISION I4xn = 0; PRECISION I4yy = 0; PRECISION I4yn = 0; PRECISION I4nn = 0; //*/ /* PRECISION I3tt = 0; PRECISION I3tx = 0; PRECISION I3ty = 0; PRECISION I3tn = 0; PRECISION I3xx = 0; PRECISION I3xy = 0; PRECISION I3xn = 0; PRECISION I3yy = 0; PRECISION I3yn = 0; PRECISION I3nn = 0; //*/ PRECISION Itt = I1tt + delta_pipi * I2tt - I3tt + tau_pipi * I4tt - lambda_piPi * Pi * stt; PRECISION Itx = I1tx + delta_pipi * I2tx - I3tx + tau_pipi * I4tx - lambda_piPi * Pi * stx; PRECISION Ity = I1ty + delta_pipi * I2ty - I3ty + tau_pipi * I4ty - lambda_piPi * Pi * sty; PRECISION Itn = I1tn + delta_pipi * I2tn - I3tn + tau_pipi * I4tn - lambda_piPi * Pi * stn; PRECISION Ixx = I1xx + delta_pipi * I2xx - I3xx + tau_pipi * I4xx - lambda_piPi * Pi * sxx; PRECISION Ixy = I1xy + delta_pipi * I2xy - I3xy + tau_pipi * I4xy - lambda_piPi * Pi * sxy; PRECISION Ixn = I1xn + delta_pipi * I2xn - I3xn + tau_pipi * I4xn - lambda_piPi * Pi * sxn; PRECISION Iyy = I1yy + delta_pipi * I2yy - I3yy + tau_pipi * I4yy - lambda_piPi * Pi * syy; PRECISION Iyn = I1yn + delta_pipi * I2yn - I3yn + tau_pipi * I4yn - lambda_piPi * Pi * syn; PRECISION Inn = I1nn + delta_pipi * I2nn - I3nn + tau_pipi * I4nn - lambda_piPi * Pi * snn; /*********************************************************\ * shear stress tensor source terms, i.e. terms on RHS /*********************************************************/ /* Itt = I1tt; Itx = I1tx; Ity = I1ty; Itn = I1tn; Ixx = I1xx; Ixy = I1xy; Ixn = I1xn; Iyy = I1yy; Iyn = I1yn; Inn = I1nn; //*/ Itt = I1tt + delta_pipi * I2tt + tau_pipi * I4tt; Itx = I1tx + delta_pipi * I2tx + tau_pipi * I4tx; Ity = I1ty + delta_pipi * I2ty + tau_pipi * I4ty; Itn = I1tn + delta_pipi * I2tn + tau_pipi * I4tn; Ixx = I1xx + delta_pipi * I2xx + tau_pipi * I4xx; Ixy = I1xy + delta_pipi * I2xy + tau_pipi * I4xy; Ixn = I1xn + delta_pipi * I2xn + tau_pipi * I4xn; Iyy = I1yy + delta_pipi * I2yy + tau_pipi * I4yy; Iyn = I1yn + delta_pipi * I2yn + tau_pipi * I4yn; Inn = I1nn + delta_pipi * I2nn + tau_pipi * I4nn; // PRECISION dpitt = 2 * beta_pi * stt - pitt * taupiInv - Itt - 2 * un * t * pitn; PRECISION dpitx = 2 * beta_pi * stx - pitx * taupiInv - Itx - un * t * pixn; PRECISION dpity = 2 * beta_pi * sty - pity * taupiInv - Ity - un * t * piyn; PRECISION dpitn = 2 * beta_pi * stn - pitn * taupiInv - Itn - un * t * pinn - (ut * pitn + un * pitt) / t; PRECISION dpixx = 2 * beta_pi * sxx - pixx * taupiInv - Ixx; PRECISION dpixy = 2 * beta_pi * sxy - pixy * taupiInv - Ixy; PRECISION dpixn = 2 * beta_pi * sxn - pixn * taupiInv - Ixn - (ut * pixn + un * pitx) / t; PRECISION dpiyy = 2 * beta_pi * syy - piyy * taupiInv - Iyy; PRECISION dpiyn = 2 * beta_pi * syn - piyn * taupiInv - Iyn - (ut * piyn + un * pity) / t; PRECISION dpinn = 2 * beta_pi * snn - pinn * taupiInv - Inn - 2 * (ut * pinn + un * pitn) / t; /*********************************************************\ * bulk viscous pressure source terms, i.e. terms on RHS /*********************************************************/ PRECISION dPi = -beta_Pi * theta - Pi * tauPiInv - delta_PiPi * Pi * theta + lambda_Pipi * ps; /*********************************************************\ * time derivative of the dissipative quantities /*********************************************************/ pimunuRHS[0] = dpitt / ut + pitt * dkvk; pimunuRHS[1] = dpitx / ut + pitx * dkvk; pimunuRHS[2] = dpity / ut + pity * dkvk; pimunuRHS[3] = dpitn / ut + pitn * dkvk; pimunuRHS[4] = dpixx / ut + pixx * dkvk; pimunuRHS[5] = dpixy / ut + pixy * dkvk; pimunuRHS[6] = dpixn / ut + pixn * dkvk; pimunuRHS[7] = dpiyy / ut + piyy * dkvk; pimunuRHS[8] = dpiyn / ut + piyn * dkvk; pimunuRHS[9] = dpinn / ut + pinn * dkvk; #ifdef PI pimunuRHS[10] = dPi / ut + Pi * dkvk; #endif } /***************************************************************************************************************************************************/ __device__ void loadSourceTerms(const PRECISION * const __restrict__ I, const PRECISION * const __restrict__ J, const PRECISION * const __restrict__ K, const PRECISION * const __restrict__ Q, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, PRECISION utp, PRECISION uxp, PRECISION uyp, PRECISION unp, PRECISION t, const PRECISION * const __restrict__ evec, const PRECISION * const __restrict__ pvec, const CONSERVED_VARIABLES * const __restrict__ currentVars, int s) { //========================================================= // conserved variables //========================================================= PRECISION ttt = Q[0]; PRECISION ttx = Q[1]; PRECISION tty = Q[2]; PRECISION ttn = Q[3]; PRECISION pl = Q[4]; #ifdef PIMUNU PRECISION pitt = Q[5]; PRECISION pitx = Q[6]; PRECISION pity = Q[7]; PRECISION pitn = Q[8]; PRECISION pixx = Q[9]; PRECISION pixy = Q[10]; PRECISION pixn = Q[11]; PRECISION piyy = Q[12]; PRECISION piyn = Q[13]; PRECISION pinn = Q[14]; #else PRECISION pitt = 0; PRECISION pitx = 0; PRECISION pity = 0; PRECISION pitn = 0; PRECISION pixx = 0; PRECISION pixy = 0; PRECISION pixn = 0; PRECISION piyy = 0; PRECISION piyn = 0; PRECISION pinn = 0; #endif #ifdef W_TZ_MU PRECISION WtTz = Q[15]; PRECISION WxTz = Q[16]; PRECISION WyTz = Q[17]; PRECISION WnTz = Q[18]; #else PRECISION WtTz = 0; PRECISION WxTz = 0; PRECISION WyTz = 0; PRECISION WnTz = 0; #endif #ifdef PI PRECISION Pi = Q[NUMBER_CONSERVED_VARIABLES-1]; #else PRECISION Pi = 0; #endif //========================================================= // primary variables //========================================================= PRECISION *utvec = u->ut; PRECISION *uxvec = u->ux; PRECISION *uyvec = u->uy; PRECISION *unvec = u->un; PRECISION e = evec[s]; PRECISION p = pvec[s]; PRECISION ut = utvec[s]; PRECISION ux = uxvec[s]; PRECISION uy = uyvec[s]; PRECISION un = unvec[s]; //========================================================= // spatial derivatives of primary variables //========================================================= PRECISION facX = 1 / d_dx / 2; PRECISION facY = 1 / d_dy / 2; PRECISION facZ = 1 / d_dz / 2; // dx of u^{\mu} components PRECISION dxut = (*(utvec + s + 1) - *(utvec + s - 1)) * facX; PRECISION dxux = (*(uxvec + s + 1) - *(uxvec + s - 1)) * facX; PRECISION dxuy = (*(uyvec + s + 1) - *(uyvec + s - 1)) * facX; PRECISION dxun = (*(unvec + s + 1) - *(unvec + s - 1)) * facX; // dy of u^{\mu} components PRECISION dyut = (*(utvec + s + d_ncx) - *(utvec + s - d_ncx)) * facY; PRECISION dyux = (*(uxvec + s + d_ncx) - *(uxvec + s - d_ncx)) * facY; PRECISION dyuy = (*(uyvec + s + d_ncx) - *(uyvec + s - d_ncx)) * facY; PRECISION dyun = (*(unvec + s + d_ncx) - *(unvec + s - d_ncx)) * facY; // dn of u^{\mu} components int stride = d_ncx * d_ncy; PRECISION dnut = (*(utvec + s + stride) - *(utvec + s - stride)) * facZ; PRECISION dnux = (*(uxvec + s + stride) - *(uxvec + s - stride)) * facZ; PRECISION dnuy = (*(uyvec + s + stride) - *(uyvec + s - stride)) * facZ; PRECISION dnun = (*(unvec + s + stride) - *(unvec + s - stride)) * facZ; // pressure PRECISION dxp = (*(pvec + s + 1) - *(pvec + s - 1)) * facX; PRECISION dyp = (*(pvec + s + d_ncx) - *(pvec + s - d_ncx)) * facY; PRECISION dnp = (*(pvec + s + stride) - *(pvec + s - stride)) * facZ; // energy density PRECISION dxe = (*(evec + s + 1) - *(evec + s - 1)) * facX; PRECISION dye = (*(evec + s + d_ncx) - *(evec + s - d_ncx)) * facY; PRECISION dne = (*(evec + s + stride) - *(evec + s - stride)) * facZ; //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dxpitt = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpity = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixy = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 20; PRECISION dxPi = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; // Y ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dypitt = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitx = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypity = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypixy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypiyy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypiyn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dyPi = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; // Z ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dnpitt = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitx = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpity = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 15; PRECISION dnpixn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 10; PRECISION dnpiyn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpinn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnPi = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; //========================================================= // T^{\mu\nu} source terms //========================================================= PRECISION tnn = Tnn(e, p + Pi, un, pinn, t); PRECISION vx = ux / ut; PRECISION vy = uy / ut; PRECISION vn = un / ut; PRECISION dxvx = (dxux - vx * dxut) / ut; PRECISION dyvy = (dyuy - vy * dyut) / ut; PRECISION dnvn = (dnun - vn * dnut) / ut; PRECISION dkvk = dxvx + dyvy + dnvn; S[0] = -(ttt / t + t * tnn) + dkvk * (pitt - p - Pi) - vx * dxp - vy * dyp - vn * dnp; S[1] = -ttx / t - dxp + dkvk * pitx; S[2] = -tty / t - dyp + dkvk * pity; S[3] = -3 * ttn / t - dnp / powf(t, 2.0f) + dkvk * pitn; #ifdef USE_CARTESIAN_COORDINATES S[0] = dkvk*(pitt-p-Pi) - vx*dxp - vy*dyp - vn*dnp; S[1] = -dxp + dkvk*pitx; S[2] = -dyp + dkvk*pity; S[3] = -dnp + dkvk*pitn; #endif //X #ifndef PI S[0] += dxpitt*vx - dxpitx + dypitt*vy - dypity + dnpitt*vn - dnpitn; S[1] += dxpitx*vx - dxpixx + dypitx*vy - dypixy + dnpitx*vn - dnpixn; S[2] += dxpity*vx - dxpixy + dypity*vy - dypiyy + dnpity*vn - dnpiyn; S[3] += dxpitn*vx - dxpixn + dypitn*vy - dypiyn + dnpitn*vn - dnpinn; #else S[0] += dxpitt * vx - dxpitx - vx * dxPi + dypitt * vy - dypity - vy * dyPi + dnpitt * vn - dnpitn - vn * dnPi; S[1] += dxpitx * vx - dxpixx + dypitx * vy - dypixy + dnpitx * vn - dnpixn - dxPi; S[2] += dxpity * vx - dxpixy + dypity * vy - dypiyy + dnpity * vn - dnpiyn - dyPi; S[3] += dxpitn * vx - dxpixn + dypitn * vy - dypiyn + dnpitn * vn - dnpinn - dnPi / powf(t, 2.0f); #endif //========================================================= // \pi^{\mu\nu} source terms //========================================================= #ifndef IDEAL PRECISION pimunuRHS[NUMBER_DISSIPATIVE_CURRENTS]; setPimunuSourceTerms(pimunuRHS, t, e, p, ut, ux, uy, un, utp, uxp, uyp, unp, pitt, pitx, pity, pitn, pixx, pixy, pixn, piyy, piyn, pinn, Pi, dxut, dyut, dnut, dxux, dyux, dnux, dxuy, dyuy, dnuy, dxun, dyun, dnun, dkvk); for (unsigned int n = 0; n < NUMBER_DISSIPATIVE_CURRENTS; ++n) S[n + 4] = pimunuRHS[n]; #endif } /***************************************************************************************************************************************************/ __device__ void loadSourceTermsX(const PRECISION * const __restrict__ I, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, int s) { //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= PRECISION facX = 1 / d_dx / 2; int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dxpitt = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpity = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixy = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 20; PRECISION ut = u->ut[s]; PRECISION ux = u->ux[s]; //========================================================= // set dx terms in the source terms //========================================================= PRECISION vx = ux / ut; #ifndef PI S[0] = dxpitt*vx - dxpitx; S[1] = dxpitx*vx - dxpixx; #else PRECISION dxPi = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; S[0] = dxpitt * vx - dxpitx - vx * dxPi; S[1] = dxpitx * vx - dxpixx - dxPi; #endif S[2] = dxpity * vx - dxpixy; S[3] = dxpitn * vx - dxpixn; } __device__ void loadSourceTermsY(const PRECISION * const __restrict__ J, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, int s) { //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= PRECISION facY = 1 / d_dy / 2; int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dypitt = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitx = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypity = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypixy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypiyy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypiyn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION ut = u->ut[s]; PRECISION uy = u->uy[s]; //========================================================= // set dy terms in the source terms //========================================================= PRECISION vy = uy / ut; #ifndef PI S[0] = dypitt*vy - dypity; S[2] = dypity*vy - dypiyy; #else PRECISION dyPi = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; S[0] = dypitt * vy - dypity - vy * dyPi; S[2] = dypity * vy - dypiyy - dyPi; #endif S[1] = dypitx * vy - dypixy; S[3] = dypitn * vy - dypiyn; } __device__ void loadSourceTermsZ(const PRECISION * const __restrict__ K, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, int s, PRECISION t) { //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= PRECISION facZ = 1 / d_dz / 2; int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dnpitt = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitx = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpity = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 15; PRECISION dnpixn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 10; PRECISION dnpiyn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpinn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION ut = u->ut[s]; PRECISION un = u->un[s]; //========================================================= // set dn terms in the source terms //========================================================= PRECISION vn = un / ut; #ifndef PI S[0] = dnpitt*vn - dnpitn; S[3] = dnpitn*vn - dnpinn; #else PRECISION dnPi = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; S[0] = dnpitt * vn - dnpitn - vn * dnPi; S[3] = dnpitn * vn - dnpinn - dnPi / powf(t, 2); #endif S[1] = dnpitx * vn - dnpixn; S[2] = dnpity * vn - dnpiyn; } __device__ void loadSourceTerms2(const PRECISION * const __restrict__ Q, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, PRECISION utp, PRECISION uxp, PRECISION uyp, PRECISION unp, PRECISION t, const PRECISION * const __restrict__ evec, const PRECISION * const __restrict__ pvec, const CONSERVED_VARIABLES * const __restrict__ currentVars, int s) { //========================================================= // conserved variables //========================================================= PRECISION ttt = Q[0]; PRECISION ttx = Q[1]; PRECISION tty = Q[2]; PRECISION ttn = Q[3]; PRECISION pl = Q[4]; #ifdef PIMUNU PRECISION pitt = Q[5]; PRECISION pitx = Q[6]; PRECISION pity = Q[7]; PRECISION pitn = Q[8]; PRECISION pixx = Q[9]; PRECISION pixy = Q[10]; PRECISION pixn = Q[11]; PRECISION piyy = Q[12]; PRECISION piyn = Q[13]; PRECISION pinn = Q[14]; #else PRECISION pitt = 0; PRECISION pitx = 0; PRECISION pity = 0; PRECISION pitn = 0; PRECISION pixx = 0; PRECISION pixy = 0; PRECISION pixn = 0; PRECISION piyy = 0; PRECISION piyn = 0; PRECISION pinn = 0; #endif #ifdef W_TZ_MU PRECISION WtTz = Q[15]; PRECISION WxTz = Q[16]; PRECISION WyTz = Q[17]; PRECISION WnTz = Q[18]; #else PRECISION WtTz = 0; PRECISION WxTz = 0; PRECISION WyTz = 0; PRECISION WnTz = 0; #endif // \Pi #ifdef PI PRECISION Pi = Q[NUMBER_CONSERVED_VARIABLES-1]; #else PRECISION Pi = 0; #endif //========================================================= // primary variables //========================================================= PRECISION *utvec = u->ut; PRECISION *uxvec = u->ux; PRECISION *uyvec = u->uy; PRECISION *unvec = u->un; PRECISION e = evec[s]; PRECISION p = pvec[s]; PRECISION ut = utvec[s]; PRECISION ux = uxvec[s]; PRECISION uy = uyvec[s]; PRECISION un = unvec[s]; //========================================================= // spatial derivatives of primary variables //========================================================= PRECISION facX = 1 / d_dx / 2; PRECISION facY = 1 / d_dy / 2; PRECISION facZ = 1 / d_dz / 2; // dx of u^{\mu} components PRECISION dxut = (*(utvec + s + 1) - *(utvec + s - 1)) * facX; PRECISION dxux = (*(uxvec + s + 1) - *(uxvec + s - 1)) * facX; PRECISION dxuy = (*(uyvec + s + 1) - *(uyvec + s - 1)) * facX; PRECISION dxun = (*(unvec + s + 1) - *(unvec + s - 1)) * facX; // dy of u^{\mu} components PRECISION dyut = (*(utvec + s + d_ncx) - *(utvec + s - d_ncx)) * facY; PRECISION dyux = (*(uxvec + s + d_ncx) - *(uxvec + s - d_ncx)) * facY; PRECISION dyuy = (*(uyvec + s + d_ncx) - *(uyvec + s - d_ncx)) * facY; PRECISION dyun = (*(unvec + s + d_ncx) - *(unvec + s - d_ncx)) * facY; // dn of u^{\mu} components int stride = d_ncx * d_ncy; PRECISION dnut = (*(utvec + s + stride) - *(utvec + s - stride)) * facZ; PRECISION dnux = (*(uxvec + s + stride) - *(uxvec + s - stride)) * facZ; PRECISION dnuy = (*(uyvec + s + stride) - *(uyvec + s - stride)) * facZ; PRECISION dnun = (*(unvec + s + stride) - *(unvec + s - stride)) * facZ; // pressure PRECISION dxp = (*(pvec + s + 1) - *(pvec + s - 1)) * facX; PRECISION dyp = (*(pvec + s + d_ncx) - *(pvec + s - d_ncx)) * facY; PRECISION dnp = (*(pvec + s + stride) - *(pvec + s - stride)) * facZ; // energy density PRECISION dxe = (*(evec + s + 1) - *(evec + s - 1)) * facX; PRECISION dye = (*(evec + s + d_ncx) - *(evec + s - d_ncx)) * facY; PRECISION dne = (*(evec + s + stride) - *(evec + s - stride)) * facZ; //added by DEREK below //========================================================= // Deriviatives of v //========================================================= PRECISION vx = ux/ut; PRECISION vy = uy/ut; PRECISION vn = un/ut; PRECISION dxvx = (dxux - vx * dxut)/ ut; PRECISION dyvy = (dyuy - vy * dyut)/ ut; PRECISION dnvn = (dnun - vn * dnut)/ ut; PRECISION dkvk = dxvx + dyvy + dnvn; PRECISION t2 = t*t; PRECISION t3 = t*t2; PRECISION un2 = un*un; PRECISION ut2 = ut*ut; /************************************************************************************\ * Gradient terms of the fluid velocity /************************************************************************************/ // time derivatives of u PRECISION dtut = (ut - utp) / d_dt; PRECISION dtux = (ux - uxp) / d_dt; PRECISION dtuy = (uy - uyp) / d_dt; PRECISION dtun = (un - unp) / d_dt; // covariant derivatives PRECISION Dut = ut*dtut + ux*dxut + uy*dyut + un*dnut + t*un*un; PRECISION DuxUpper = ut*dtux + ux*dxux + uy*dyux + un*dnux; PRECISION Dux = -DuxUpper; PRECISION DuyUpper = ut*dtuy + ux*dxuy + uy*dyuy + un*dnuy; PRECISION Duy = -DuyUpper; PRECISION DunUpper = ut*dtun + ux*dxun + uy*dyun + un*dnun + 2*ut*un/t; PRECISION Dun = -t2*DunUpper; PRECISION dut = Dut -t*un*un; PRECISION dux = ut*dtux + ux*dxux + uy*dyux + un*dnux; PRECISION duy = ut*dtuy + ux*dxuy + uy*dyuy + un*dnuy; PRECISION dun = ut*dtun + ux*dxun + uy*dyun + un*dnun; // expansion rate PRECISION theta = ut / t + dtut + dxux + dyuy + dnun; // shear tensor PRECISION stt = -t * ut * un2 + (dtut - ut * dut) + (ut2 - 1) * theta / 3; PRECISION stx = -(t * un2 * ux) / 2 + (dtux - dxut) / 2 - (ux * dut + ut * dux) / 2 + ut * ux * theta / 3; PRECISION sty = -(t * un2 * uy) / 2 + (dtuy - dyut) / 2 - (uy * dut + ut * duy) / 2 + ut * uy * theta / 3; PRECISION stn = -un * (2 * ut2 + t2 * un2) / (2 * t) + (dtun - dnut / t2) / 2 - (un * dut + ut * dun) / 2 + ut * un * theta / 3; PRECISION sxx = -(dxux + ux * dux) + (1 + ux*ux) * theta / 3; PRECISION sxy = -(dxuy + dyux) / 2 - (uy * dux + ux * duy) / 2 + ux * uy * theta / 3; PRECISION sxn = -ut * ux * un / t - (dxun + dnux / t2) / 2 - (un * dux + ux * dun) / 2 + ux * un * theta / 3; PRECISION syy = -(dyuy + uy * duy) + (1 + uy*uy) * theta / 3; PRECISION syn = -ut * uy * un / t - (dyun + dnuy / t2) / 2 - (un * duy + uy * dun) / 2 + uy * un * theta / 3; PRECISION snn = -ut * (1 + 2 * t2 * un2) / t3 - dnun / t2 - un * dun + (1 / t2 + un2) * theta / 3; // vorticity tensor PRECISION wtx = (dtux + dxut) / 2 + (ux * dut - ut * dux) / 2 + t * un2 * ux / 2; PRECISION wty = (dtuy + dyut) / 2 + (uy * dut - ut * duy) / 2 + t * un2 * uy / 2; PRECISION wtn = (t2 * dtun + 2 * t * un + dnut) / 2 + (t2 * un * dut - ut * Dun) + t3 * un*un2 / 2; PRECISION wxy = (dyux - dxuy) / 2 + (uy * dux - ux * duy) / 2; PRECISION wxn = (dnux - t2 * dxun) / 2 + (t2 * un * dux - ux * Dun) / 2; PRECISION wyn = (dnuy - t2 * dyun) / 2 + (t2 * un * duy - uy * Dun) / 2; // anti-symmetric vorticity components PRECISION wxt = wtx; PRECISION wyt = wty; PRECISION wnt = wtn / t2; PRECISION wyx = -wxy; PRECISION wnx = -wxn / t2; PRECISION wny = -wyn / t2; /************************************************************************************\ * Split transverse and longitudinal gradients of the fluid velocity /************************************************************************************/ // transverse flow velocity PRECISION uT2 = ux*ux+uy*uy; PRECISION uT = sqrt(uT2); PRECISION uTdtuT = (ux*dtux+uy*dtuy); PRECISION uTdxuT = (ux*dxux+uy*dxuy); PRECISION uTdyuT = (ux*dyux+uy*dyuy); PRECISION uTdnuT = (ux*dnux+uy*dnuy); PRECISION uTduT = ut*uTdtuT+ux*uTdxuT+uy*uTdyuT+un*uTdnuT; PRECISION F = 1+uT2; PRECISION F2 = F*F; PRECISION FS = sqrt(1+uT2); double z0 = t*un/sqrt(F); double z1 = 0; double z2 = 0; double z3 = ut/t/sqrt(F); double z02 = z0*z0; double z0z3 = z0*z3; double z32 = z3*z3; // g^{\mu\nu} double gtt = 1; double gxx = -1; double gyy = -1; double gnn = -1/t2; // \Delta_{\perp}^{\mu\nu} double Xitt = gtt-ut*ut+z02; double Xitx = -ut*ux; double Xity = -ut*uy; double Xitn = -ut*un+z0z3; double Xixx = gxx-ux*ux; double Xixy = -ux*uy; double Xixn = -ux*un; double Xiyy = gyy-uy*un; double Xiyn = -uy*un; double Xinn = gnn-un*un+z32; // covariant derivatives of z double dz0 = (ut*un+t*dun-t*un/F*uTduT)/sqrt(F); double dz3 = (-ut2/t2+dut/t-ut/t/F*uTduT)/sqrt(F); double Dz0 = dz0+t*un*z3; double Dz3Upper = dz3+(ut*z3+un*z0)/t; double Dz3 = -t2*Dz3Upper; double A = z02*stt-2*t2*z0z3*stn+t2*t2*z32*snn; // B double B0 = z0*stt-t2*z3*stn; double B1 = z0*stx-t2*z3*sxn; double B2 = z0*sty-t2*z3*syn; double B3 = z0*stn-t2*z3*snn; // Bw double Bw0 = z3*wtn; double Bw1 = z0*wtx+z3*wxn; double Bw2 = z0*wty+z3*wyn; double Bw3 = z0*wtn/t2; // transverse and longitudinal expansion scalars double thetaT = 2*theta/3+A; double zDzu = theta/3-A; zDzu = theta-thetaT; // transverse shear tensor double sttT = stt+2*z0*B0+z02*A-0.5*(1-ut*ut+z02)*A; double stxT = stx+z0*B1-0.5*(-ut*ux)*A; double styT = sty+z0*B2-0.5*(-ut*uy)*A; double stnT = stn+z0*B3+z3*B0+z0z3*A-0.5*(-ut*un+z0z3)*A; double sxxT = sxx-0.5*(-1-ux*ux)*A; double sxyT = sxy-0.5*(-ux*uy)*A; double sxnT = sxn+z3*B1-0.5*(-ux*un)*A; double syyT = syy-0.5*(-1-uy*uy)*A; double synT = syn+z3*B2-0.5*(-uy*un)*A; double snnT = snn+2*z3*B3+z32*A-0.5*(-1/t2-un*un+z32)*A; /************************************************************************************\ * Anisotropic hydro stuff /************************************************************************************/ if(e==0) e=1.e-7; PRECISION T = effectiveTemperature(e); PRECISION cs2 = speedOfSoundSquared(e); double a = pl/e; double a2 = a*a; double a3 = a2*a; double a4 = a3*a; double a5 = a4*a; double a6 = a5*a; double a7 = a6*a; double a8 = a7*a; double a9 = a8*a; double a10 = a9*a; double a11 = a10*a; double a12 = a11*a; double a13 = a12*a; double a14 = a13*a; double a15 = a14*a; PRECISION Rtilde = (-6.674731906076046e-6 + 0.004617789933500251*a + 0.7207562721999754*a2 + 9.097427250602184*a3 - 4.475814747302824*a4 - 36.37501529319408*a5 + 46.868405146729316*a6 - 15.833867583743228*a7)/ (0.06856675185266 + 2.9181587012768597*a + 11.951184087839218*a2 - 29.708257843442173*a3 - 2.618233802059826*a4 + 34.646239784689065*a5 - 19.62596366454439*a6 + 2.374808442453899*a7); PRECISION Rhat = (0.0024792827625583747 + 1.943027171680747*a + 53.46970495217282*a2 + 19.989171951866325*a3 - 347.1285593126723*a4 + 412.2647882672885*a5 - 140.53693383827797*a6)/(0.5061402347582388 + 29.466067530916984*a + 126.07947638942892*a2 - 334.420268508072*a3 + 86.57706367583984*a4 + 183.53625188578846*a5 - 91.68259808111912*a6); PRECISION Rbar0 = (0.015267955823446243 + 7.725572805021035*a + 421.0063884634789*a2 + 3422.877939650926*a3 - 5785.670846299543*a4 - 12261.66452089229*a5 + 31491.409484673808*a6 - 22737.05146992673*a7 + 5441.373392185447*a8)/ (0.05470696094814806 + 14.505878005231883*a + 522.6643024173569*a2 + 2731.7776413939037*a3 - 6161.1991042880445*a4 - 3989.4375208972588*a5 + 15008.260526258282*a6 - 10243.036679405379*a7 + 2116.74060159494*a8); PRECISION Rgamma = (0.0001373796340585521 - 0.6149634004722385*a + 3.1968875683514253*a2 + 246.35973783799196*a3 - 764.319750320186*a4 + 834.160165071214*a5 - 371.64955466673234*a6 + 52.87411921963021*a7)/ (-1.673322188488071 + 13.343782941396997*a + 561.7566534476223*a2 - 1790.2296622275915*a3 + 1896.4688704912812*a4 - 658.7933063369629*a5 - 85.96181900698849*a6 + 65.09739194472589*a7); double Rbar0P = (2.473173363908116e-10 - 4.899839370307281e-6*a + 155055.91462124084*a10 - 275435.45350226434*a11 + 350689.68825705117*a12 - 299725.38986957155*a13 + 151477.08809203724*a14 - 33196.47417939176*a15 - 0.004301975027942015*a2 - 0.14858206981041563*a3 + 6.249255189587875*a4 - 92.79641927240235*a5 + 807.175057749925*a6 - 4760.015905266286*a7 + 20324.533122685436*a8 - 64758.869552496515*a9)/(0.00008222793468208523 + 0.03411917870833943*a + 4.895969276094396e6*a10 - 8.84162305829353e6*a11 + 1.1445063656613324e7*a12 - 9.918442713390596e6*a13 + 5.065882388219598e6*a14 - 1.1181016364928822e6*a15 + 0.23871740573818725*a2 - 23.50912574236691*a3 + 417.4953123877312*a4 - 4234.215775452717*a5 + 29824.022790048104*a6 - 157419.8447785501*a7 + 641300.6529027821*a8 - 2.0248032895288002e6*a9); double R0g1m2031 = (-1.0233483506421896e-7 - 0.005510394233958543*a - 0.5161308003737349*a2 - 4.115511461930346*a3 + 6.378431203946746*a4 + 3.926438723664259*a5 - 8.465485699618803*a6 + 2.7925630611642154*a7)/ (0.001958161993306958 + 0.22517859370360388*a + 2.883216830325076*a2 + 0.1905363935371778*a3 - 12.192584184275201*a4 + 10.729468548753893*a5 - 0.8635431725599291*a6 - 0.9690254375998808*a7); // longitudinal pressure PRECISION dxpl = (*(currentVars->pl + s + 1) - *(currentVars->pl + s - 1)) * facX; PRECISION dypl = (*(currentVars->pl + s + d_ncx) - *(currentVars->pl + s - d_ncx)) * facY; PRECISION dnpl = (*(currentVars->pl + s + stride) - *(currentVars->pl + s - stride)) * facZ; PRECISION ptHat = transversePressureHat(e, p, pl); PRECISION pt = ptHat + 1.5*Pi; PRECISION DP = pl-pt; // L functions PRECISION Ltt = DP*t2*un2/F; PRECISION Ltn = DP*ut*un/F; PRECISION Lnn = DP*ut2/F/t2; // W functions double Wtt = 2*WtTz*z0; double Wtx = WxTz*z0; double Wty = WyTz*z0; double Wtn = WtTz*z3+WnTz*z0; double Wxx = 0; double Wxy = 0; double Wxn = WxTz*z3; double Wyy = 0; double Wyn = WyTz*z3; double Wnn = 2*WnTz*z3; // derivatives of z0 double dxz0 = t*(dxun/sqrt(F)-un/pow(F,1.5)*uTdxuT); double dyz0 = t*(dyun/sqrt(F)-un/pow(F,1.5)*uTdyuT); double dnz0 = t*(dnun/sqrt(F)-un/pow(F,1.5)*uTdnuT); // derivatives of z3 double dxz3 = (dxut/sqrt(F)-ut/pow(F,1.5)*uTdxuT)/t; double dyz3 = (dyut/sqrt(F)-ut/pow(F,1.5)*uTdyuT)/t; double dnz3 = (dnut/sqrt(F)-ut/pow(F,1.5)*uTdnuT)/t; // derivative of W^{\mu}_{\perp z} #ifdef W_TZ_MU // WtTz PRECISION dxWtTz = (*(currentVars->WtTz + s + 1) - *(currentVars->WtTz + s - 1)) * facX; PRECISION dyWtTz = (*(currentVars->WtTz + s + d_ncx) - *(currentVars->WtTz + s - d_ncx)) * facY; PRECISION dnWtTz = (*(currentVars->WtTz + s + stride) - *(currentVars->WtTz + s - stride)) * facZ; // WxTz PRECISION dxWxTz = (*(currentVars->WxTz + s + 1) - *(currentVars->WxTz + s - 1)) * facX; PRECISION dyWxTz = (*(currentVars->WxTz + s + d_ncx) - *(currentVars->WxTz + s - d_ncx)) * facY; PRECISION dnWxTz = (*(currentVars->WxTz + s + stride) - *(currentVars->WxTz + s - stride)) * facZ; // WyTz PRECISION dxWyTz = (*(currentVars->WyTz + s + 1) - *(currentVars->WyTz + s - 1)) * facX; PRECISION dyWyTz = (*(currentVars->WyTz + s + d_ncx) - *(currentVars->WyTz + s - d_ncx)) * facY; PRECISION dnWyTz = (*(currentVars->WyTz + s + stride) - *(currentVars->WyTz + s - stride)) * facZ; // WnTz PRECISION dxWnTz = (*(currentVars->WnTz + s + 1) - *(currentVars->WnTz + s - 1)) * facX; PRECISION dyWnTz = (*(currentVars->WnTz + s + d_ncx) - *(currentVars->WnTz + s - d_ncx)) * facY; PRECISION dnWnTz = (*(currentVars->WnTz + s + stride) - *(currentVars->WnTz + s - stride)) * facZ; #else // WnTz PRECISION dxWtTz = 0; PRECISION dyWtTz = 0; PRECISION dnWtTz = 0; // WxTz PRECISION dxWxTz = 0; PRECISION dyWxTz = 0; PRECISION dnWxTz = 0; // WyTz PRECISION dxWyTz = 0; PRECISION dyWyTz = 0; PRECISION dnWyTz = 0; // WnTz PRECISION dxWnTz = 0; PRECISION dyWnTz = 0; PRECISION dnWnTz = 0; #endif //========================================================= // derivatives of W in conservation law source terms //========================================================= // Wtt double dxWtt = 2*t*(WtTz*dxun-un*WtTz*uTdxuT/F+un*dxWtTz)/FS; double dyWtt = 2*t*(WtTz*dyun-un*WtTz*uTdyuT/F+un*dyWtTz)/FS; double dnWtt = 2*t*(WtTz*dnun-un*WtTz*uTdnuT/F+un*dnWtTz)/FS; // Wtx double dxWtx = t*(WxTz*dxun-un*WxTz*uTdxuT/F+un*dxWxTz)/FS; double dyWtx = t*(WxTz*dyun-un*WxTz*uTdyuT/F+un*dyWxTz)/FS; double dnWtx = t*(WxTz*dnun-un*WxTz*uTdnuT/F+un*dnWxTz)/FS; // Wty double dxWty = t*(WyTz*dxun-un*WyTz*uTdxuT/F+un*dxWyTz)/FS; double dyWty = t*(WyTz*dyun-un*WyTz*uTdyuT/F+un*dyWyTz)/FS; double dnWty = t*(WyTz*dnun-un*WyTz*uTdnuT/F+un*dnWyTz)/FS; // Wtn double dxWtn = (WtTz*dxut-ut*WtTz*uTdxuT/F+ut*dxWyTz)/FS/t+t*(WnTz*dxun-un*WnTz*uTdxuT/F+un*dxWnTz)/FS; double dyWtn = (WtTz*dyut-ut*WtTz*uTdyuT/F+ut*dyWyTz)/FS/t+t*(WnTz*dyun-un*WnTz*uTdyuT/F+un*dyWnTz)/FS; double dnWtn = (WtTz*dnut-ut*WtTz*uTdnuT/F+ut*dnWyTz)/FS/t+t*(WnTz*dnun-un*WnTz*uTdnuT/F+un*dnWnTz)/FS; // Wxn double dxWxn = (WxTz*dxut-ut*WxTz*uTdxuT/F+ut*dxWxTz)/FS/t; double dnWxn = (WxTz*dnut-ut*WxTz*uTdnuT/F+ut*dnWxTz)/FS/t; // Wyn double dyWyn = (WyTz*dyut-ut*WyTz*uTdyuT/F+ut*dyWyTz)/FS/t; double dnWyn = (WyTz*dnut-ut*WyTz*uTdnuT/F+ut*dnWyTz)/FS/t; // Wnn double dnWnn = 2*(WnTz*dnut-ut*WnTz*uTdnuT/F+ut*dnWnTz)/FS/t; PRECISION tnn = (e+pt)*un*un+pt/t2+Lnn+Wnn+pinn; // deritive of Rbar double dxRbar0 = Rbar0P*(dxpl-a*dxe)/e; double dyRbar0 = Rbar0P*(dypl-a*dye)/e; double dnRbar0 = Rbar0P*(dnpl-a*dne)/e; // derivative of transverse pressure PRECISION dxptHat = 0.5*(dxe-dxpl-Rbar0*(dxe-3*dxp)-(e-3*p)*dxRbar0); PRECISION dyptHat = 0.5*(dye-dypl-Rbar0*(dye-3*dyp)-(e-3*p)*dyRbar0); PRECISION dnptHat = 0.5*(dne-dnpl-Rbar0*(dne-3*dnp)-(e-3*p)*dnRbar0); // derivative of \Delta P -- NEED TO ADD DERIVATIVES OF BULK PI PRECISION dxDP = dxpl-dxptHat; PRECISION dyDP = dypl-dyptHat; PRECISION dnDP = dnpl-dnptHat; // spatial derivatives of Ltt PRECISION dxLtt = (2*DP*dxun*t2*un)/F + (dxDP*t2*un2)/F - (2*DP*uTdxuT*t2*un2)/F2; PRECISION dyLtt = (2*DP*dyun*t2*un)/F + (dyDP*t2*un2)/F - (2*DP*uTdyuT*t2*un2)/F2; PRECISION dnLtt = (2*DP*dnun*t2*un)/F + (dnDP*t2*un2)/F - (2*DP*uTdnuT*t2*un2)/F2; // spatial derivatives of Ltn PRECISION dxLtn = (DP*dxut*un)/F + (DP*dxun*ut)/F + (dxDP*un*ut)/F - (2*DP*uTdxuT*un*ut)/F2; PRECISION dyLtn = (DP*dyut*un)/F + (DP*dyun*ut)/F + (dyDP*un*ut)/F - (2*DP*uTdyuT*un*ut)/F2; PRECISION dnLtn = (DP*dnut*un)/F + (DP*dnun*ut)/F + (dnDP*un*ut)/F - (2*DP*uTdnuT*un*ut)/F2; // spatial derivatives of Lnn PRECISION dnLnn = (2*DP*dnut*ut)/(F*t2) + (dnDP*ut2)/(F*t2) - (2*DP*uTdnuT*ut2)/(F2*t2); PRECISION zeta_zz = Rtilde*e-3*pl; PRECISION zeta_zT = (Rtilde*e + pl)/2.; //============================================== // second-order transport coefficients //============================================== double beta_lPi=0; double delta_lPi=0; double lambda_piPi=0; double beta_PiPi=0; double delta_PiPi=0; double lambda_Pipi=0; secondOrderTransportCoefficientsZ(e, p, pl, cs2, T, &beta_lPi, &delta_lPi, &lambda_piPi, &beta_PiPi, &delta_PiPi, &lambda_Pipi); // Pl double lambda_lWu = R0g1m2031; double lambda_lWT = 2+lambda_lWu; double lambda_lpi = Rgamma; // W double delta_WW = lambda_lWu/2-1; double lambda_WWu = 2 + lambda_lWu; double lambda_WWT = 1 + delta_WW; double lambda_Wpiu = lambda_lpi; double lambda_WpiT = lambda_Wpiu-1; // pi^\mu\nu double delta_pipi = (3+Rgamma)/2; double tau_pipi = 4*(delta_pipi-1/2)/3; double lambda_pipi = Rgamma-1; double lambda_piWu = delta_WW-1/2; double lambda_piWT = lambda_piWu+2; PRECISION taupiInv = 0.2 * T/d_etabar; PRECISION psT = pitt * sttT - 2 * pitx * stxT - 2 * pity * styT + pixx * sxxT + 2 * pixy * sxyT + piyy * syyT - 2 * pitn * stnT * t2 + 2 * pixn * sxnT * t2 + 2 * piyn * synT * t2 + pinn * snnT * t2 * t2; // IL1 double IL1 = -(WtTz*B0 - WxTz*B1 - WyTz*B2 - t2*WnTz*B3) + (WtTz*Bw0 - WxTz*Bw1 - WyTz*Bw2 - t2*WnTz*Bw3); // IL2 double IL2 = (WtTz*B0 - WxTz*B1 - WyTz*B2 - t2*WnTz*B3) + (WtTz*Bw0 - WxTz*Bw1 - WyTz*Bw2 - t2*WnTz*Bw3); // IL3 double IL3 = psT; // IL double IL = lambda_lWu * IL1 - lambda_lWT * IL2 - lambda_lpi * IL3; // IL=0; // PRECISION dPL = -(pl-p)*taupiInv + zeta_zz*zDzu - zeta_zT*thetaT - lambda_lpi * psT; PRECISION dPL = -(pl-p)*taupiInv + zeta_zz*zDzu - zeta_zT*thetaT - beta_lPi * Pi * zDzu - delta_lPi * Pi * thetaT + IL; S[4] = dPL / ut + dkvk * pl; /* if(isnan(S[4])) { printf("=======================================================================================\n"); printf("Found Nan in S[4]:\n"); printf("pl=%.9f;\n",pl); printf("Grid point = (%d, %d, %d) = (%.3f, %.3f, %.3f)\n", i, j, k, x, y, z); printf("Rhat=%.9f;Rtilde=%.39f;\n",Rhat,Rtilde); printf("pl = %.9f\n",pl); printf("e = %.9f\n",e); printf("a = %.9f\n",a); printf("T=%.9f;e=%.9f;p=%.9f;\n",T,e,p); printf("ut=%.9f;ux=%.9f;uy=%.9f\n",ut,ux,uy); printf("ux[s+1]=%.9f; ux[s-1]=%.9f\n",*(uxvec + s + 1),*(uxvec + s - 1)); printf("uy[s+1]=%.9f; uy[s-1]=%.9f\n",*(uyvec + s + 1),*(uyvec + s - 1)); printf("dx=%.3f;dy=%.3f;facX=%.3f;facY=%.3f\n",d_dx,d_dy,facX,facY); printf("zeta_zz=%.3f;zeta_zT=%.3f;dtu0=%.3f;zDzu=%.3f;thetaT=%.3f;taupiInv=%.3f;\n",zeta_zz,zeta_zT,dtut,zDzu,thetaT,taupiInv); printf("=======================================================================================\n"); exit(-1); } */ /************************************************************************************\ * T^{\mu\nu} source terms /************************************************************************************/ double Htt = Ltt+Wtt+pitt; S[0] = -(ttt / t + t * tnn) + dkvk * (Htt - pt) - vx * dxptHat - vy * dyptHat - vn * dnptHat + vx*(dxLtt+dxWtt)-dxWtx + vy*(dyLtt+dyWtt)-dyWty + vn*(dnLtt+dnWtt)-dnLtn-dnWtn; S[1] = -ttx / t - dxptHat + dkvk * (Wtx + pitx) + vx*dxWtx + vy*dyWtx + vn*dnWtx - dnWxn; S[2] = -tty / t - dyptHat + dkvk * (Wty + pity) + vx*dxWty + vy*dyWty + vn*dnWty - dnWyn; S[3] = -3 * ttn / t - dnptHat / t2 + dkvk * (Ltn + Wtn + pitn) + vx*(dxLtn+dxWtn)-dxWxn + vy*(dyLtn+dyWtn)-dyWyn + vn*(dnLtn+dnLtn)-dnLnn-dnWnn; /* if(isnan(S[0])) { printf("=======================================================================================\n"); printf("Found Nan in S[0]:\n"); printf("pl=%.9f;\n",pl); printf("Grid point = (%d, %d, %d) = (%.3f, %.3f, %.3f)\n", i, j, k, x, y, z); printf("Rhat=%.9f;Rtilde=%.39f;\n",Rhat,Rtilde); printf("pl = %.9f\n",pl); printf("e = %.9f\n",e); printf("a = %.9f\n",a); printf("T=%.9f;e=%.9f;p=%.9f;\n",T,e,p); printf("ut=%.9f;ux=%.9f;uy=%.9f\n",ut,ux,uy); printf("ux[s+1]=%.9f; ux[s-1]=%.9f\n",*(uxvec + s + 1),*(uxvec + s - 1)); printf("uy[s+1]=%.9f; uy[s-1]=%.9f\n",*(uyvec + s + 1),*(uyvec + s - 1)); printf("dx=%.3f;dy=%.3f;facX=%.3f;facY=%.3f\n",d_dx,d_dy,facX,facY); printf("zeta_zz=%.3f;zeta_zT=%.3f;dtu0=%.3f;zDzu=%.3f;thetaT=%.3f;taupiInv=%.3f;\n",zeta_zz,zeta_zT,dtut,zDzu,thetaT,taupiInv); printf("taupiInv=%.3f;\n",taupiInv); printf("-------------------------------------------\n"); printf("ttt=%.9f;tnn=%.9f\n",ttt,tnn); printf("dkvk=%.9f;vx=%.9f;vy=%.9f;vn=%.9f\n",dkvk,vx,vy,vn); printf("pt=%.9f;dxpt=%.9f;dypt=%.9f;dnpt=%.9f\n",pt,dxptHat,dyptHat,dnptHat); printf("Ltt=%.9f;dxLtt=%.9f;dyLtt=%.9f;dnLtt=%.9f\n",Ltt,dxLtt,dyLtt,dnLtt); printf("Ltn=%.9f;dxLtn=%.9f;dyLtn=%.9f;dnLtn=%.9f\n",Ltn,dxLtn,dyLtn,dnLtn); printf("dnLnn=%.9f\n",dnLnn); printf("dxpt=%.9f;dypt=%.9f;dnpt=%.9f;\n",dxptHat,dyptHat,dnptHat); printf("dxDP=%.9f;dyDP=%.9f;dnDP=%.9f;\n",dxDP,dyDP,dnDP); printf("DP=%.9f;F=%.9f;uT=%.9f\n",DP,F,uT); printf("uTdxuT=%.9f;uTdyuT=%.9f;uTdnuT=%.9f;\n",uTdxuT,uTdyuT,uTdnuT); printf("dxux=%.9f;dyux=%.9f;dnux=%.9f;\n",dxux,dyux,dnux); printf("dxuy=%.9f;dyuy=%.9f;dnuy=%.9f;\n",dxuy,dyuy,dnuy); printf("=======================================================================================\n"); exit(-1); } */ /************************************************************************************\ * \pi^{\mu\nu}_\perp source terms /************************************************************************************/ #ifdef PIMUNU double etaBar_TC = ((3-Rtilde)*e-2*pl)/8; // I1 PRECISION I1Utt = 2 * ut * (pitt * Dut + pitx * Dux + pity * Duy + pitn * Dun); PRECISION I1Utx = (pitt * ux + pitx * ut) * Dut + (pitx * ux + pixx * ut) * Dux + (pity * ux + pixy * ut) * Duy + (pitn * ux + pixn * ut) * Dun; PRECISION I1Uty = (pitt * uy + pity * ut) * Dut + (pitx * uy + pixy * ut) * Dux + (pity * uy + piyy * ut) * Duy + (pitn * uy + piyn * ut) * Dun; PRECISION I1Utn = (pitt * un + pitn * ut) * Dut + (pitx * un + pixn * ut) * Dux + (pity * un + piyn * ut) * Duy + (pitn * un + pinn * ut) * Dun; PRECISION I1Uxx = 2 * ux * (pitx * Dut + pixx * Dux + pixy * Duy + pixn * Dun); PRECISION I1Uxy = (pitx * uy + pity * ux) * Dut + (pixx * uy + pixy * ux) * Dux + (pixy * uy + piyy * ux) * Duy + (pixn * uy + piyn * ux) * Dun; PRECISION I1Uxn = (pitx * un + pitn * ux) * Dut + (pixx * un + pixn * ux) * Dux + (pixy * un + piyn * ux) * Duy + (pixn * un + pinn * ux) * Dun; PRECISION I1Uyy = 2 * uy * (pity * Dut + pixy * Dux + piyy * Duy + piyn * Dun); PRECISION I1Uyn = (pity * un + pitn * uy) * Dut + (pixy * un + pixn * uy) * Dux + (piyy * un + piyn * uy) * Duy + (piyn * un + pinn * uy) * Dun; PRECISION I1Unn = 2 * un * (pitn * Dut + pixn * Dux + piyn * Duy + pinn * Dun); //Dz0=0; //Dz3=0; PRECISION I1Ztt = 2 * z0 * (pitt * Dz0 + pitn * Dz3); PRECISION I1Ztx = ( pitx * z0) * Dz0 + (pitn * ux + pixn * z0) * Dz3; PRECISION I1Zty = (pity * z0) * Dz0 + (pitn * uy + piyn * z0) * Dz3; PRECISION I1Ztn = (pitt * z3 + pitn * z0) * Dz0 + (pitn * z3 + pinn * z0) * Dz3; PRECISION I1Zxx = 0; PRECISION I1Zxy = 0; PRECISION I1Zxn = (pitx * z3) * Dz0 + (pixn * z3) * Dz3; PRECISION I1Zyy = 0; PRECISION I1Zyn = (pity * z3) * Dz0 + (piyn * z3) * Dz3; PRECISION I1Znn = 2 * z3 * (pitn * Dz0 + pinn * Dz3); PRECISION I1tt = I1Utt - I1Ztt; PRECISION I1tx = I1Utx - I1Ztx; PRECISION I1ty = I1Uty - I1Zty; PRECISION I1tn = I1Utn - I1Ztn; PRECISION I1xx = I1Uxx - I1Zxx; PRECISION I1xy = I1Uxy - I1Zxy; PRECISION I1xn = I1Uxn - I1Zxn; PRECISION I1yy = I1Uyy - I1Zyy; PRECISION I1yn = I1Uyn - I1Zyn; PRECISION I1nn = I1Unn - I1Znn; // I2 PRECISION I2tt = thetaT * pitt; PRECISION I2tx = thetaT * pitx; PRECISION I2ty = thetaT * pity; PRECISION I2tn = thetaT * pitn; PRECISION I2xx = thetaT * pixx; PRECISION I2xy = thetaT * pixy; PRECISION I2xn = thetaT * pixn; PRECISION I2yy = thetaT * piyy; PRECISION I2yn = thetaT * piyn; PRECISION I2nn = thetaT * pinn; // I4 ///* PRECISION ux2 = ux * ux; PRECISION uy2 = uy * uy; PRECISION ps = pitt * sttT - 2 * pitx * stxT - 2 * pity * styT + pixx * sxxT + 2 * pixy * sxyT + piyy * syyT - 2 * pitn * stnT * t2 + 2 * pixn * sxnT * t2 + 2 * piyn * synT * t2 + pinn * snnT * t2 * t2; PRECISION ps2 = ps / 2; PRECISION I4tt = (pitt * sttT - pitx * stxT - pity * styT - t2 * pitn * stnT) - (1 - ut2+z02) * ps2; PRECISION I4tx = (pitt * stxT + pitx * sttT) / 2 - (pitx * sxxT + pixx * stxT) / 2 - (pity * sxyT + pixy * styT) / 2 - t2 * (pitn * sxnT + pixn * stnT) / 2 + (ut * ux) * ps2; PRECISION I4ty = (pitt * styT + pity * sttT) / 2 - (pitx * sxyT + pixy * stxT) / 2 - (pity * syyT + piyy * styT) / 2 - t2 * (pitn * synT + piyn * stnT) / 2 + (ut * uy) * ps2; PRECISION I4tn = (pitt * stnT + pitn * sttT) / 2 - (pitx * sxnT + pixn * stxT) / 2 - (pity * synT + piyn * styT) / 2 - t2 * (pitn * snnT + pinn * stnT) / 2 + (ut * un-z0z3) * ps2; PRECISION I4xx = (pitx * stxT - pixx * sxxT - pixy * sxyT - t2 * pixn * sxnT) + (1 + ux2) * ps2; PRECISION I4xy = (pitx * styT + pity * stxT) / 2 - (pixx * sxyT + pixy * sxxT) / 2 - (pixy * syyT + piyy * sxyT) / 2 - t2 * (pixn * synT + piyn * sxnT) / 2 + (ux * uy) * ps2; PRECISION I4xn = (pitx * stnT + pitn * stxT) / 2 - (pixx * sxnT + pixn * sxxT) / 2 - (pixy * synT + piyn * sxyT) / 2 - t2 * (pixn * snnT + pinn * sxnT) / 2 + (ux * un) * ps2; PRECISION I4yy = (pity * styT - pixy * sxyT - piyy * syyT - t2 * piyn * synT) + (1 + uy2) * ps2; PRECISION I4yn = (pity * stnT + pitn * styT) / 2 - (pixy * sxnT + pixn * sxyT) / 2 - (piyy * synT + piyn * syyT) / 2 - t2 * (piyn * snnT + pinn * synT) / 2 + (uy * un) * ps2; PRECISION I4nn = (pitn * stnT - pixn * sxnT - piyn * synT - t2 * pinn * snnT) + (1 / t2 + un2-z32) * ps2; //*/ /* PRECISION I4tt = 0; PRECISION I4tx = 0; PRECISION I4ty = 0; PRECISION I4tn = 0; PRECISION I4xx = 0; PRECISION I4xy = 0; PRECISION I4xn = 0; PRECISION I4yy = 0; PRECISION I4yn = 0; PRECISION I4nn = 0; //*/ // I5 PRECISION I5tt = zDzu * pitt; PRECISION I5tx = zDzu * pitx; PRECISION I5ty = zDzu * pity; PRECISION I5tn = zDzu * pitn; PRECISION I5xx = zDzu * pixx; PRECISION I5xy = zDzu * pixy; PRECISION I5xn = zDzu * pixn; PRECISION I5yy = zDzu * piyy; PRECISION I5yn = zDzu * piyn; PRECISION I5nn = zDzu * pinn; // I6 double L = z0*WtTz - t2*z3*WnTz; double WB = WtTz * B0 - WxTz * B1 - WyTz * B2 - t2 * WnTz * B3; // I6S double I6tt_S = ((WtTz*B0 + WtTz*B0) + (WtTz*z0 + z0*WtTz)*A + (z0*B0 + z0*B0)*L + 2*z0*z0*L*A)/2 - Xitt*(WB + L*A)/2; double I6tx_S = ((WtTz*B1 + WxTz*B0) + (WtTz*z1 + z0*WxTz)*A + (z0*B1 + z1*B0)*L + 2*z0*z1*L*A)/2 - Xitx*(WB + L*A)/2; double I6ty_S = ((WtTz*B2 + WyTz*B0) + (WtTz*z2 + z0*WyTz)*A + (z0*B2 + z2*B0)*L + 2*z0*z2*L*A)/2 - Xity*(WB + L*A)/2; double I6tn_S = ((WtTz*B3 + WnTz*B0) + (WtTz*z3 + z0*WnTz)*A + (z0*B3 + z3*B0)*L + 2*z0*z3*L*A)/2 - Xitn*(WB + L*A)/2; double I6xx_S = ((WxTz*B1 + WxTz*B1) + (WxTz*z1 + z1*WxTz)*A + (z1*B1 + z1*B1)*L + 2*z1*z1*L*A)/2 - Xixx*(WB + L*A)/2; double I6xy_S = ((WxTz*B2 + WyTz*B1) + (WxTz*z2 + z1*WyTz)*A + (z2*B1 + z1*B2)*L + 2*z1*z2*L*A)/2 - Xixy*(WB + L*A)/2; double I6xn_S = ((WxTz*B3 + WnTz*B1) + (WxTz*z3 + z1*WnTz)*A + (z1*B3 + z3*B1)*L + 2*z1*z3*L*A)/2 - Xixn*(WB + L*A)/2; double I6yy_S = ((WyTz*B2 + WyTz*B2) + (WyTz*z2 + z2*WyTz)*A + (z2*B2 + z2*B2)*L + 2*z2*z2*L*A)/2 - Xiyy*(WB + L*A)/2; double I6yn_S = ((WyTz*B3 + WnTz*B2) + (WyTz*z3 + z2*WnTz)*A + (z2*B3 + z3*B2)*L + 2*z2*z3*L*A)/2 - Xiyn*(WB + L*A)/2; double I6nn_S = ((WnTz*B3 + WnTz*B3) + (WnTz*z3 + z3*WnTz)*A + (z3*B3 + z3*B3)*L + 2*z3*z3*L*A)/2 - Xinn*(WB + L*A)/2; // I6W double I6tt_W = ((WtTz*Bw0 + WtTz*Bw0) + (z0*Bw0 + z0*Bw0)*L)/2 - Xitt*(WB)/2; double I6tx_W = ((WtTz*Bw1 + WxTz*Bw0) + (z0*Bw1 + z1*Bw0)*L)/2 - Xitx*(WB)/2; double I6ty_W = ((WtTz*Bw2 + WyTz*Bw0) + (z0*Bw2 + z2*Bw0)*L)/2 - Xity*(WB)/2; double I6tn_W = ((WtTz*Bw3 + WnTz*Bw0) + (z0*Bw3 + z3*Bw0)*L)/2 - Xitn*(WB)/2; double I6xx_W = ((WxTz*Bw1 + WxTz*Bw1) + (z1*Bw1 + z1*Bw1)*L)/2 - Xixx*(WB)/2; double I6xy_W = ((WxTz*Bw2 + WyTz*Bw1) + (z2*Bw1 + z1*Bw2)*L)/2 - Xixy*(WB)/2; double I6xn_W = ((WxTz*Bw3 + WnTz*Bw1) + (z1*Bw3 + z3*Bw1)*L)/2 - Xixn*(WB)/2; double I6yy_W = ((WyTz*Bw2 + WyTz*Bw2) + (z2*Bw2 + z2*Bw2)*L)/2 - Xiyy*(WB)/2; double I6yn_W = ((WyTz*Bw3 + WnTz*Bw2) + (z2*Bw3 + z3*Bw2)*L)/2 - Xiyn*(WB)/2; double I6nn_W = ((WnTz*Bw3 + WnTz*Bw3) + (z3*Bw3 + z3*Bw3)*L)/2 - Xinn*(WB)/2; // I6 double I6tt = -I6tt_S + I6tt_W; double I6tx = -I6tx_S + I6tx_W; double I6ty = -I6ty_S + I6ty_W; double I6tn = -I6tn_S + I6tn_W; double I6xx = -I6xx_S + I6xx_W; double I6xy = -I6xy_S + I6xy_W; double I6xn = -I6xn_S + I6xn_W; double I6yy = -I6yy_S + I6yy_W; double I6yn = -I6yn_S + I6yn_W; double I6nn = -I6nn_S + I6nn_W; /* I6tt = 0; I6tx = 0; I6ty = 0; I6tn = 0; I6xx = 0; I6xy = 0; I6xn = 0; I6yy = 0; I6yn = 0; I6nn = 0; //*/ // I7 double I7tt = I6tt_S + I6tt_W; double I7tx = I6tx_S + I6tx_W; double I7ty = I6ty_S + I6ty_W; double I7tn = I6tn_S + I6tn_W; double I7xx = I6xx_S + I6xx_W; double I7xy = I6xy_S + I6xy_W; double I7xn = I6xn_S + I6xn_W; double I7yy = I6yy_S + I6yy_W; double I7yn = I6yn_S + I6yn_W; double I7nn = I6nn_S + I6nn_W; /* I7tt = 0; I7tx = 0; I7ty = 0; I7tn = 0; I7xx = 0; I7xy = 0; I7xn = 0; I7yy = 0; I7yn = 0; I7nn = 0; //*/ PRECISION Itt = I1tt - delta_pipi * I2tt + tau_pipi * I4tt - lambda_pipi * I5tt + lambda_piWu * I6tt - lambda_piWT * I7tt - lambda_piPi * Pi * sttT; PRECISION Itx = I1tx - delta_pipi * I2tx + tau_pipi * I4tx - lambda_pipi * I5tx + lambda_piWu * I6tx - lambda_piWT * I7tx - lambda_piPi * Pi * sttT; PRECISION Ity = I1ty - delta_pipi * I2ty + tau_pipi * I4ty - lambda_pipi * I5ty + lambda_piWu * I6ty - lambda_piWT * I7ty - lambda_piPi * Pi * sttT; PRECISION Itn = I1tn - delta_pipi * I2tn + tau_pipi * I4tn - lambda_pipi * I5tn + lambda_piWu * I6tn - lambda_piWT * I7tn - lambda_piPi * Pi * sttT; PRECISION Ixx = I1xx - delta_pipi * I2xx + tau_pipi * I4xx - lambda_pipi * I5xx + lambda_piWu * I6xx - lambda_piWT * I7xx - lambda_piPi * Pi * sttT; PRECISION Ixy = I1xy - delta_pipi * I2xy + tau_pipi * I4xy - lambda_pipi * I5xy + lambda_piWu * I6xy - lambda_piWT * I7xy - lambda_piPi * Pi * sttT; PRECISION Ixn = I1xn - delta_pipi * I2xn + tau_pipi * I4xn - lambda_pipi * I5xn + lambda_piWu * I6xn - lambda_piWT * I7xn - lambda_piPi * Pi * sttT; PRECISION Iyy = I1yy - delta_pipi * I2yy + tau_pipi * I4yy - lambda_pipi * I5yy + lambda_piWu * I6yy - lambda_piWT * I7yy - lambda_piPi * Pi * sttT; PRECISION Iyn = I1yn - delta_pipi * I2yn + tau_pipi * I4yn - lambda_pipi * I5yn + lambda_piWu * I6yn - lambda_piWT * I7yn - lambda_piPi * Pi * sttT; PRECISION Inn = I1nn - delta_pipi * I2nn + tau_pipi * I4nn - lambda_pipi * I5nn + lambda_piWu * I6nn - lambda_piWT * I7nn - lambda_piPi * Pi * sttT; PRECISION dpitt = 2 * etaBar_TC * sttT - pitt * taupiInv - Itt - 2 * un * t * pitn; PRECISION dpitx = 2 * etaBar_TC * stxT - pitx * taupiInv - Itx - un * t * pixn; PRECISION dpity = 2 * etaBar_TC * styT - pity * taupiInv - Ity - un * t * piyn; PRECISION dpitn = 2 * etaBar_TC * stnT - pitn * taupiInv - Itn - un * t * pinn - (ut * pitn + un * pitt) / t; PRECISION dpixx = 2 * etaBar_TC * sxxT - pixx * taupiInv - Ixx; PRECISION dpixy = 2 * etaBar_TC * sxyT - pixy * taupiInv - Ixy; PRECISION dpixn = 2 * etaBar_TC * sxnT - pixn * taupiInv - Ixn - (ut * pixn + un * pitx) / t; PRECISION dpiyy = 2 * etaBar_TC * syyT - piyy * taupiInv - Iyy; PRECISION dpiyn = 2 * etaBar_TC * synT - piyn * taupiInv - Iyn - (ut * piyn + un * pity) / t; PRECISION dpinn = 2 * etaBar_TC * snnT - pinn * taupiInv - Inn - 2 * (ut * pinn + un * pitn) / t; S[5] = dpitt / ut + pitt * dkvk; S[6] = dpitx / ut + pitx * dkvk; S[7] = dpity / ut + pity * dkvk; S[8] = dpitn / ut + pitn * dkvk; S[9] = dpixx / ut + pixx * dkvk; S[10] = dpixy / ut + pixy * dkvk; S[11] = dpixn / ut + pixn * dkvk; S[12] = dpiyy / ut + piyy * dkvk; S[13] = dpiyn / ut + piyn * dkvk; S[14] = dpinn / ut + pinn * dkvk; #endif /************************************************************************************\ * W^{\mu}_{\perp z} source terms /************************************************************************************/ #ifdef W_TZ_MU double etaWu = zeta_zT/2.; double etaWT = ((Rtilde+1)*e-2*pl)/4; // I1 double WDU = WtTz*Dut + WxTz*Dux + WyTz*Duy + WnTz*Dun; double I1t = ut*WDU + (pitt-WtTz*z0-1.5*Pi*Xitt)*Dz0 + (pitn-WnTz*z0-1.5*Pi*Xitn)*Dz3; double I1x = ux*WDU + (pitx-1.5*Pi*Xitx)*Dz0 + (pixn-1.5*Pi*Xixn)*Dz3; double I1y = uy*WDU + (pity-1.5*Pi*Xity)*Dz0 + (piyn-1.5*Pi*Xiyn)*Dz3; double I1n = un*WDU + (pitn-WtTz*z3-1.5*Pi*Xitn)*Dz0 + (pinn-WnTz*z3-1.5*Pi*Xinn)*Dz3; // I2 double I2t = WtTz*thetaT; double I2x = WxTz*thetaT; double I2y = WyTz*thetaT; double I2n = WnTz*thetaT; // I3 double I3t = WtTz * zDzu; double I3x = WxTz * zDzu; double I3y = WyTz * zDzu; double I3n = WnTz * zDzu; // I4 double I4t = WtTz * sttT - WxTz * stxT - WyTz * styT - t2 * WnTz * stnT; double I4x = WtTz * stxT - WxTz * sxxT - WyTz * sxyT - t2 * WnTz * sxnT; double I4y = WtTz * styT - WxTz * sxyT - WyTz * syyT - t2 * WnTz * synT; double I4n = WtTz * stnT - WxTz * sxnT - WyTz * synT - t2 * WnTz * snnT; // I5 double I5t = 0; double I5x = 0; double I5y = 0; double I5n = 0; // I6 double BB0 = Bw0-B0; double BB1 = Bw1-B1; double BB2 = Bw2-B2; double BB3 = Bw3-B3; double I6t = pitt*BB0 - pitx*BB1 - pity*BB2 - t2*pitn*BB3; double I6x = pitx*BB0 - pixx*BB1 - pixy*BB2 - t2*pixn*BB3; double I6y = pity*BB0 - pixy*BB1 - piyy*BB2 - t2*piyn*BB3; double I6n = pitn*BB0 - pixn*BB1 - piyn*BB2 - t2*pinn*BB3; // I7 double St = B0 + z0*A + Bw0; double Sx = B1 + Bw1; double Sy = B2 + Bw2; double Sn = B3 + z3*A + Bw3; double I7t = pitt * St - pitx * Sx - pity * Sy - t2 * pitn * Sn; double I7x = pitx * St - pixx * Sx - pixy * Sy - t2 * pixn * Sn; double I7y = pity * St - pixy * Sx - piyy * Sy - t2 * piyn * Sn; double I7n = pitn * St - pixn * Sx - piyn * Sy - t2 * pinn * Sn; // J1 double J1t = -B0-z0*A+Bw0; double J1x = -B1+Bw1; double J1y = -B2+Bw2; double J1n = -B3-z3*A+Bw3; // J2 double J2t = B0+z0*A+Bw0; double J2x = B1+Bw1; double J2y = B2+Bw2; double J2n = B3+z3*A+Bw3; double Jt = 2*(etaWu * J1t - etaWT * J2t); double Jx = 2*(etaWu * J1x - etaWT * J2x); double Jy = 2*(etaWu * J1y - etaWT * J2y); double Jn = 2*(etaWu * J1n - etaWT * J2n); // I double IWt = I1t - delta_WW * I2t + lambda_WWu * I3t - lambda_WWT * I4t - I5t - lambda_Wpiu * I6t + lambda_WpiT * I7t; double IWx = I1x - delta_WW * I2x + lambda_WWu * I3x - lambda_WWT * I4x - I5x - lambda_Wpiu * I6x + lambda_WpiT * I7x; double IWy = I1y - delta_WW * I2y + lambda_WWu * I3y - lambda_WWT * I4y - I5y - lambda_Wpiu * I6y + lambda_WpiT * I7y; double IWn = I1n - delta_WW * I2n + lambda_WWu * I3n - lambda_WWT * I4n - I5n - lambda_Wpiu * I6n + lambda_WpiT * I7n; // G^{\mu}_{W} -- Christofel symbols from covariant derivative double GWt = t*un*WnTz; double GWn = (ut*WnTz+un*WtTz)/t; PRECISION dWtTz = Jt - WtTz*taupiInv - IWt - GWt; PRECISION dWxTz = Jx - WxTz*taupiInv - IWx; PRECISION dWyTz = Jy - WyTz*taupiInv - IWy; PRECISION dWnTz = Jn - WnTz*taupiInv - IWn - GWn; S[15] = dWtTz / ut + WtTz * dkvk; S[16] = dWxTz / ut + WxTz * dkvk; S[17] = dWyTz / ut + WyTz * dkvk; S[18] = dWnTz / ut + WnTz * dkvk; #endif /************************************************************************************\ * \Pi source terms /************************************************************************************/ #ifdef PI PRECISION b = 1.0/3.0 - cs2; PRECISION b2 = b*b; PRECISION zetabar = bulkViscosityToEntropyDensity(T); PRECISION tauPiInv = 15*b2*T/zetabar; double zeta_z = (Rhat-Rbar0)*(e-3*p)/3; double zeta_T = -(Rbar0+Rhat)*(e-3*p)/6; // PRECISION dPi = -((1-Rbar0)*(e-3*p)/3+Pi)*tauPiInv - zeta_z*zDzu -zeta_T*thetaT; PRECISION dPi = -((1-Rbar0)*(e-3*p)/3+Pi)*tauPiInv - zeta_z*zDzu -zeta_T*thetaT - beta_PiPi * Pi * zDzu - delta_PiPi * Pi * thetaT + lambda_Pipi * ps; S[NUMBER_CONSERVED_VARIABLES-1] = dPi / ut + Pi * dkvk; #endif //added by DEREK above /* //========================================================= // T^{\mu\nu} source terms //========================================================= PRECISION tnn = Tnn(e, p + Pi, un, pinn, t); PRECISION vx = ux / ut; PRECISION vy = uy / ut; PRECISION vn = un / ut; PRECISION dxvx = (dxux - vx * dxut) / ut; PRECISION dyvy = (dyuy - vy * dyut) / ut; PRECISION dnvn = (dnun - vn * dnut) / ut; PRECISION dkvk = dxvx + dyvy + dnvn; S[0] = -(ttt / t + t * tnn) + dkvk * (pitt - p - Pi) - vx * dxp - vy * dyp - vn * dnp; S[1] = -ttx / t - dxp + dkvk * pitx; S[2] = -tty / t - dyp + dkvk * pity; S[3] = -3 * ttn / t - dnp / powf(t, 2) + dkvk * pitn; #ifdef USE_CARTESIAN_COORDINATES S[0] = dkvk*(pitt-p-Pi) - vx*dxp - vy*dyp - vn*dnp; S[1] = -dxp + dkvk*pitx; S[2] = -dyp + dkvk*pity; S[3] = -dnp + dkvk*pitn; #endif //========================================================= // \pi^{\mu\nu} source terms //========================================================= #ifndef IDEAL PRECISION pimunuRHS[NUMBER_DISSIPATIVE_CURRENTS]; setPimunuSourceTerms(pimunuRHS, t, e, p, ut, ux, uy, un, utp, uxp, uyp, unp, pitt, pitx, pity, pitn, pixx, pixy, pixn, piyy, piyn, pinn, Pi, dxut, dyut, dnut, dxux, dyux, dnux, dxuy, dyuy, dnuy, dxun, dyun, dnun, dkvk); for (unsigned int n = 0; n < NUMBER_DISSIPATIVE_CURRENTS; ++n) S[n + 4] = pimunuRHS[n]; #endif */ }
41b6a03787ebbd6e2a2d44564d8a4fdae160e50d.cu
/* * SourceTerms.cu * * Created on: Oct 22, 2015 * Author: bazow */ #include <stdio.h> // for printf #include <math.h> // for math functions #include <cuda.h> #include <cuda_runtime.h> #include "../include/SourceTerms.cuh" #include "../include/FiniteDifference.cuh" #include "../include/EnergyMomentumTensor.cuh" #include "../include/DynamicalVariables.cuh" #include "../include/CudaConfiguration.cuh" #include "../include/EquationOfState.cuh" // for bulk terms #include "../include/TransportCoefficients.cuh" #include "../include/AnisotropicDistributionFunctions.cuh" //#define USE_CARTESIAN_COORDINATES /* // paramters for the analytic parameterization of the bulk viscosity \zeta/S #define A_1 -13.77 #define A_2 27.55 #define A_3 13.45 #define LAMBDA_1 0.9 #define LAMBDA_2 0.25 #define LAMBDA_3 0.9 #define LAMBDA_4 0.22 #define SIGMA_1 0.025 #define SIGMA_2 0.13 #define SIGMA_3 0.0025 #define SIGMA_4 0.022 inline PRECISION bulkViscosityToEntropyDensity(PRECISION T) { PRECISION x = T/1.01355; if(x > 1.05) return LAMBDA_1*exp(-(x-1)/SIGMA_1) + LAMBDA_2*exp(-(x-1)/SIGMA_2)+0.001; else if(x < 0.995) return LAMBDA_3*exp((x-1)/SIGMA_3)+ LAMBDA_4*exp((x-1)/SIGMA_4)+0.03; else return A_1*x*x + A_2*x - A_3; } */ __device__ void setPimunuSourceTerms(PRECISION * const __restrict__ pimunuRHS, PRECISION t, PRECISION e, PRECISION p, PRECISION ut, PRECISION ux, PRECISION uy, PRECISION un, PRECISION utp, PRECISION uxp, PRECISION uyp, PRECISION unp, PRECISION pitt, PRECISION pitx, PRECISION pity, PRECISION pitn, PRECISION pixx, PRECISION pixy, PRECISION pixn, PRECISION piyy, PRECISION piyn, PRECISION pinn, PRECISION Pi, PRECISION dxut, PRECISION dyut, PRECISION dnut, PRECISION dxux, PRECISION dyux, PRECISION dnux, PRECISION dxuy, PRECISION dyuy, PRECISION dnuy, PRECISION dxun, PRECISION dyun, PRECISION dnun, PRECISION dkvk) { /*********************************************************\ * Temperature dependent shear transport coefficients /*********************************************************/ PRECISION T = effectiveTemperature(e); PRECISION taupiInv = 0.2f * fdividef(T, d_etabar); PRECISION beta_pi = 0.2f * (e + p); /*********************************************************\ * Temperature dependent bulk transport coefficients /*********************************************************/ PRECISION cs2 = speedOfSoundSquared(e); PRECISION a = 0.333333f - cs2; PRECISION a2 = a * a; PRECISION beta_Pi = 15 * a2 * (e + p); PRECISION lambda_Pipi = 1.6f * a; PRECISION zetabar = bulkViscosityToEntropyDensity(T); PRECISION tauPiInv = 15 * a2 * fdividef(T, zetabar); PRECISION ut2 = ut * ut; PRECISION un2 = un * un; PRECISION t2 = t * t; PRECISION t3 = t * t2; // time derivatives of u PRECISION dtut = (ut - utp) / d_dt; PRECISION dtux = (ux - uxp) / d_dt; PRECISION dtuy = (uy - uyp) / d_dt; PRECISION dtun = (un - unp) / d_dt; /*********************************************************\ * covariant derivatives /*********************************************************/ PRECISION Dut = ut * dtut + ux * dxut + uy * dyut + un * dnut + t * un * un; PRECISION dut = Dut - t * un * un; PRECISION dux = ut * dtux + ux * dxux + uy * dyux + un * dnux; PRECISION Dux = -dux; PRECISION duy = ut * dtuy + ux * dxuy + uy * dyuy + un * dnuy; PRECISION Duy = -duy; PRECISION dun = ut * dtun + ux * dxun + uy * dyun + un * dnun; PRECISION Dun = -t2 * dun - 2 * t * ut * un; /*********************************************************\ * expansion rate /*********************************************************/ PRECISION theta = ut / t + dtut + dxux + dyuy + dnun; /*********************************************************\ * Velocity shear stress tensor /*********************************************************/ PRECISION theta3 = theta / 3; PRECISION stt = -t * ut * un2 + (dtut - ut * dut) + (ut2 - 1) * theta3; PRECISION stx = -(t * un2 * ux) / 2 + (dtux - dxut) / 2 - (ux * dut + ut * dux) / 2 + ut * ux * theta3; PRECISION sty = -(t * un2 * uy) / 2 + (dtuy - dyut) / 2 - (uy * dut + ut * duy) / 2 + ut * uy * theta3; PRECISION stn = -un * (2 * ut2 + t2 * un2) / (2 * t) + (dtun - dnut / t2) / 2 - (un * dut + ut * dun) / 2 + ut * un * theta3; PRECISION sxx = -(dxux + ux * dux) + (1 + ux * ux) * theta3; PRECISION sxy = -(dxuy + dyux) / 2 - (uy * dux + ux * duy) / 2 + ux * uy * theta3; PRECISION sxn = -ut * ux * un / t - (dxun + dnux / t2) / 2 - (un * dux + ux * dun) / 2 + ux * un * theta3; PRECISION syy = -(dyuy + uy * duy) + (1 + uy * uy) * theta3; PRECISION syn = -ut * uy * un / t - (dyun + dnuy / t2) / 2 - (un * duy + uy * dun) / 2 + uy * un * theta3; PRECISION snn = -ut * (1 + 2 * t2 * un2) / t3 - dnun / t2 - un * dun + (1 / t2 + un2) * theta3; /*********************************************************\ * vorticity tensor /*********************************************************/ PRECISION wtx = (dtux + dxut) / 2 + (ux * dut - ut * dux) / 2 + t * un2 * ux / 2; PRECISION wty = (dtuy + dyut) / 2 + (uy * dut - ut * duy) / 2 + t * un2 * uy / 2; PRECISION wtn = (t2 * dtun + 2 * t * un + dnut) / 2 + (t2 * un * dut - ut * Dun) + t3 * un * un2 / 2; PRECISION wxy = (dyux - dxuy) / 2 + (uy * dux - ux * duy) / 2; PRECISION wxn = (dnux - t2 * dxun) / 2 + (t2 * un * dux - ux * Dun) / 2; PRECISION wyn = (dnuy - t2 * dyun) / 2 + (t2 * un * duy - uy * Dun) / 2; // anti-symmetric vorticity components PRECISION wxt = wtx; PRECISION wyt = wty; PRECISION wnt = wtn / t2; PRECISION wyx = -wxy; PRECISION wnx = -wxn / t2; PRECISION wny = -wyn / t2; /*********************************************************\ * I1 /*********************************************************/ PRECISION I1tt = 2 * ut * (pitt * Dut + pitx * Dux + pity * Duy + pitn * Dun); PRECISION I1tx = (pitt * ux + pitx * ut) * Dut + (pitx * ux + pixx * ut) * Dux + (pity * ux + pixy * ut) * Duy + (pitn * ux + pixn * ut) * Dun; PRECISION I1ty = (pitt * uy + pity * ut) * Dut + (pitx * uy + pixy * ut) * Dux + (pity * uy + piyy * ut) * Duy + (pitn * uy + piyn * ut) * Dun; PRECISION I1tn = (pitt * un + pitn * ut) * Dut + (pitx * un + pixn * ut) * Dux + (pity * un + piyn * ut) * Duy + (pitn * un + pinn * ut) * Dun; PRECISION I1xx = 2 * ux * (pitx * Dut + pixx * Dux + pixy * Duy + pixn * Dun); PRECISION I1xy = (pitx * uy + pity * ux) * Dut + (pixx * uy + pixy * ux) * Dux + (pixy * uy + piyy * ux) * Duy + (pixn * uy + piyn * ux) * Dun; PRECISION I1xn = (pitx * un + pitn * ux) * Dut + (pixx * un + pixn * ux) * Dux + (pixy * un + piyn * ux) * Duy + (pixn * un + pinn * ux) * Dun; PRECISION I1yy = 2 * uy * (pity * Dut + pixy * Dux + piyy * Duy + piyn * Dun); PRECISION I1yn = (pity * un + pitn * uy) * Dut + (pixy * un + pixn * uy) * Dux + (piyy * un + piyn * uy) * Duy + (piyn * un + pinn * uy) * Dun; PRECISION I1nn = 2 * un * (pitn * Dut + pixn * Dux + piyn * Duy + pinn * Dun); /*********************************************************\ * I2 /*********************************************************/ PRECISION I2tt = theta * pitt; PRECISION I2tx = theta * pitx; PRECISION I2ty = theta * pity; PRECISION I2tn = theta * pitn; PRECISION I2xx = theta * pixx; PRECISION I2xy = theta * pixy; PRECISION I2xn = theta * pixn; PRECISION I2yy = theta * piyy; PRECISION I2yn = theta * piyn; PRECISION I2nn = theta * pinn; /*********************************************************\ * I3 /*********************************************************/ PRECISION I3tt = 2 * (pitx * wtx + pity * wty + pitn * wtn); PRECISION I3tx = pitt * wxt + pity * wxy + pitn * wxn + pixx * wtx + pixy * wty + pixn * wtn; PRECISION I3ty = pitt * wyt + pitx * wyx + pitn * wyn + pixy * wtx + piyy * wty + piyn * wtn; PRECISION I3tn = pitt * wnt + pitx * wnx + pity * wny + pixn * wtx + piyn * wty + pinn * wtn; PRECISION I3xx = 2 * (pitx * wxt + pixy * wxy + pixn * wxn); PRECISION I3xy = pitx * wyt + pity * wxt + pixx * wyx + piyy * wxy + pixn * wyn + piyn * wxn; PRECISION I3xn = pitx * wnt + pitn * wxt + pixx * wnx + pixy * wny + piyn * wxy + pinn * wxn; PRECISION I3yy = 2 * (pity * wyt + pixy * wyx + piyn * wyn); PRECISION I3yn = pity * wnt + pitn * wyt + pixy * wnx + pixn * wyx + piyy * wny + pinn * wyn; PRECISION I3nn = 2 * (pitn * wnt + pixn * wnx + piyn * wny); /*********************************************************\ * I4 /*********************************************************/ PRECISION ux2 = ux * ux; PRECISION uy2 = uy * uy; PRECISION ps = pitt * stt - 2 * pitx * stx - 2 * pity * sty + pixx * sxx + 2 * pixy * sxy + piyy * syy - 2 * pitn * stn * t2 + 2 * pixn * sxn * t2 + 2 * piyn * syn * t2 + pinn * snn * t2 * t2; PRECISION ps3 = ps / 3; PRECISION I4tt = (pitt * stt - pitx * stx - pity * sty - t2 * pitn * stn) - (1 - ut2) * ps3; PRECISION I4tx = (pitt * stx + pitx * stt) / 2 - (pitx * sxx + pixx * stx) / 2 - (pity * sxy + pixy * sty) / 2 - t2 * (pitn * sxn + pixn * stn) / 2 + (ut * ux) * ps3; PRECISION I4ty = (pitt * sty + pity * stt) / 2 - (pitx * sxy + pixy * stx) / 2 - (pity * syy + piyy * sty) / 2 - t2 * (pitn * syn + piyn * stn) / 2 + (ut * uy) * ps3; PRECISION I4tn = (pitt * stn + pitn * stt) / 2 - (pitx * sxn + pixn * stx) / 2 - (pity * syn + piyn * sty) / 2 - t2 * (pitn * snn + pinn * stn) / 2 + (ut * un) * ps3; PRECISION I4xx = (pitx * stx - pixx * sxx - pixy * sxy - t2 * pixn * sxn) + (1 + ux2) * ps3; PRECISION I4xy = (pitx * sty + pity * stx) / 2 - (pixx * sxy + pixy * sxx) / 2 - (pixy * syy + piyy * sxy) / 2 - t2 * (pixn * syn + piyn * sxn) / 2 + (ux * uy) * ps3; PRECISION I4xn = (pitx * stn + pitn * stx) / 2 - (pixx * sxn + pixn * sxx) / 2 - (pixy * syn + piyn * sxy) / 2 - t2 * (pixn * snn + pinn * sxn) / 2 + (ux * un) * ps3; PRECISION I4yy = (pity * sty - pixy * sxy - piyy * syy - t2 * piyn * syn) + (1 + uy2) * ps3; PRECISION I4yn = (pity * stn + pitn * sty) / 2 - (pixy * sxn + pixn * sxy) / 2 - (piyy * syn + piyn * syy) / 2 - t2 * (piyn * snn + pinn * syn) / 2 + (uy * un) * ps3; PRECISION I4nn = (pitn * stn - pixn * sxn - piyn * syn - t2 * pinn * snn) + (1 / t2 + un2) * ps3; /*********************************************************\ * I /*********************************************************/ // PRECISION ps = 0; /* // PRECISION ps = pitt*stt + 2*(pixy*sxy - pitx*stx - pity*sty + (pixn*sxn + piyn*syn - pitn*stn)*t2) + pixx*sxx + piyy*syy + pinn*snn*t2*t2; PRECISION ps = pitt*stt-2*pitx*stx-2*pity*sty+pixx*sxx+2*pixy*sxy+piyy*syy-2*pitn*stn*t2+2*pixn*sxn*t2+2*piyn*syn*t2+pinn*snn*t2*t2; PRECISION I4tt = 0; PRECISION I4tx = 0; PRECISION I4ty = 0; PRECISION I4tn = 0; PRECISION I4xx = 0; PRECISION I4xy = 0; PRECISION I4xn = 0; PRECISION I4yy = 0; PRECISION I4yn = 0; PRECISION I4nn = 0; //*/ /* PRECISION I3tt = 0; PRECISION I3tx = 0; PRECISION I3ty = 0; PRECISION I3tn = 0; PRECISION I3xx = 0; PRECISION I3xy = 0; PRECISION I3xn = 0; PRECISION I3yy = 0; PRECISION I3yn = 0; PRECISION I3nn = 0; //*/ PRECISION Itt = I1tt + delta_pipi * I2tt - I3tt + tau_pipi * I4tt - lambda_piPi * Pi * stt; PRECISION Itx = I1tx + delta_pipi * I2tx - I3tx + tau_pipi * I4tx - lambda_piPi * Pi * stx; PRECISION Ity = I1ty + delta_pipi * I2ty - I3ty + tau_pipi * I4ty - lambda_piPi * Pi * sty; PRECISION Itn = I1tn + delta_pipi * I2tn - I3tn + tau_pipi * I4tn - lambda_piPi * Pi * stn; PRECISION Ixx = I1xx + delta_pipi * I2xx - I3xx + tau_pipi * I4xx - lambda_piPi * Pi * sxx; PRECISION Ixy = I1xy + delta_pipi * I2xy - I3xy + tau_pipi * I4xy - lambda_piPi * Pi * sxy; PRECISION Ixn = I1xn + delta_pipi * I2xn - I3xn + tau_pipi * I4xn - lambda_piPi * Pi * sxn; PRECISION Iyy = I1yy + delta_pipi * I2yy - I3yy + tau_pipi * I4yy - lambda_piPi * Pi * syy; PRECISION Iyn = I1yn + delta_pipi * I2yn - I3yn + tau_pipi * I4yn - lambda_piPi * Pi * syn; PRECISION Inn = I1nn + delta_pipi * I2nn - I3nn + tau_pipi * I4nn - lambda_piPi * Pi * snn; /*********************************************************\ * shear stress tensor source terms, i.e. terms on RHS /*********************************************************/ /* Itt = I1tt; Itx = I1tx; Ity = I1ty; Itn = I1tn; Ixx = I1xx; Ixy = I1xy; Ixn = I1xn; Iyy = I1yy; Iyn = I1yn; Inn = I1nn; //*/ Itt = I1tt + delta_pipi * I2tt + tau_pipi * I4tt; Itx = I1tx + delta_pipi * I2tx + tau_pipi * I4tx; Ity = I1ty + delta_pipi * I2ty + tau_pipi * I4ty; Itn = I1tn + delta_pipi * I2tn + tau_pipi * I4tn; Ixx = I1xx + delta_pipi * I2xx + tau_pipi * I4xx; Ixy = I1xy + delta_pipi * I2xy + tau_pipi * I4xy; Ixn = I1xn + delta_pipi * I2xn + tau_pipi * I4xn; Iyy = I1yy + delta_pipi * I2yy + tau_pipi * I4yy; Iyn = I1yn + delta_pipi * I2yn + tau_pipi * I4yn; Inn = I1nn + delta_pipi * I2nn + tau_pipi * I4nn; // PRECISION dpitt = 2 * beta_pi * stt - pitt * taupiInv - Itt - 2 * un * t * pitn; PRECISION dpitx = 2 * beta_pi * stx - pitx * taupiInv - Itx - un * t * pixn; PRECISION dpity = 2 * beta_pi * sty - pity * taupiInv - Ity - un * t * piyn; PRECISION dpitn = 2 * beta_pi * stn - pitn * taupiInv - Itn - un * t * pinn - (ut * pitn + un * pitt) / t; PRECISION dpixx = 2 * beta_pi * sxx - pixx * taupiInv - Ixx; PRECISION dpixy = 2 * beta_pi * sxy - pixy * taupiInv - Ixy; PRECISION dpixn = 2 * beta_pi * sxn - pixn * taupiInv - Ixn - (ut * pixn + un * pitx) / t; PRECISION dpiyy = 2 * beta_pi * syy - piyy * taupiInv - Iyy; PRECISION dpiyn = 2 * beta_pi * syn - piyn * taupiInv - Iyn - (ut * piyn + un * pity) / t; PRECISION dpinn = 2 * beta_pi * snn - pinn * taupiInv - Inn - 2 * (ut * pinn + un * pitn) / t; /*********************************************************\ * bulk viscous pressure source terms, i.e. terms on RHS /*********************************************************/ PRECISION dPi = -beta_Pi * theta - Pi * tauPiInv - delta_PiPi * Pi * theta + lambda_Pipi * ps; /*********************************************************\ * time derivative of the dissipative quantities /*********************************************************/ pimunuRHS[0] = dpitt / ut + pitt * dkvk; pimunuRHS[1] = dpitx / ut + pitx * dkvk; pimunuRHS[2] = dpity / ut + pity * dkvk; pimunuRHS[3] = dpitn / ut + pitn * dkvk; pimunuRHS[4] = dpixx / ut + pixx * dkvk; pimunuRHS[5] = dpixy / ut + pixy * dkvk; pimunuRHS[6] = dpixn / ut + pixn * dkvk; pimunuRHS[7] = dpiyy / ut + piyy * dkvk; pimunuRHS[8] = dpiyn / ut + piyn * dkvk; pimunuRHS[9] = dpinn / ut + pinn * dkvk; #ifdef PI pimunuRHS[10] = dPi / ut + Pi * dkvk; #endif } /***************************************************************************************************************************************************/ __device__ void loadSourceTerms(const PRECISION * const __restrict__ I, const PRECISION * const __restrict__ J, const PRECISION * const __restrict__ K, const PRECISION * const __restrict__ Q, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, PRECISION utp, PRECISION uxp, PRECISION uyp, PRECISION unp, PRECISION t, const PRECISION * const __restrict__ evec, const PRECISION * const __restrict__ pvec, const CONSERVED_VARIABLES * const __restrict__ currentVars, int s) { //========================================================= // conserved variables //========================================================= PRECISION ttt = Q[0]; PRECISION ttx = Q[1]; PRECISION tty = Q[2]; PRECISION ttn = Q[3]; PRECISION pl = Q[4]; #ifdef PIMUNU PRECISION pitt = Q[5]; PRECISION pitx = Q[6]; PRECISION pity = Q[7]; PRECISION pitn = Q[8]; PRECISION pixx = Q[9]; PRECISION pixy = Q[10]; PRECISION pixn = Q[11]; PRECISION piyy = Q[12]; PRECISION piyn = Q[13]; PRECISION pinn = Q[14]; #else PRECISION pitt = 0; PRECISION pitx = 0; PRECISION pity = 0; PRECISION pitn = 0; PRECISION pixx = 0; PRECISION pixy = 0; PRECISION pixn = 0; PRECISION piyy = 0; PRECISION piyn = 0; PRECISION pinn = 0; #endif #ifdef W_TZ_MU PRECISION WtTz = Q[15]; PRECISION WxTz = Q[16]; PRECISION WyTz = Q[17]; PRECISION WnTz = Q[18]; #else PRECISION WtTz = 0; PRECISION WxTz = 0; PRECISION WyTz = 0; PRECISION WnTz = 0; #endif #ifdef PI PRECISION Pi = Q[NUMBER_CONSERVED_VARIABLES-1]; #else PRECISION Pi = 0; #endif //========================================================= // primary variables //========================================================= PRECISION *utvec = u->ut; PRECISION *uxvec = u->ux; PRECISION *uyvec = u->uy; PRECISION *unvec = u->un; PRECISION e = evec[s]; PRECISION p = pvec[s]; PRECISION ut = utvec[s]; PRECISION ux = uxvec[s]; PRECISION uy = uyvec[s]; PRECISION un = unvec[s]; //========================================================= // spatial derivatives of primary variables //========================================================= PRECISION facX = 1 / d_dx / 2; PRECISION facY = 1 / d_dy / 2; PRECISION facZ = 1 / d_dz / 2; // dx of u^{\mu} components PRECISION dxut = (*(utvec + s + 1) - *(utvec + s - 1)) * facX; PRECISION dxux = (*(uxvec + s + 1) - *(uxvec + s - 1)) * facX; PRECISION dxuy = (*(uyvec + s + 1) - *(uyvec + s - 1)) * facX; PRECISION dxun = (*(unvec + s + 1) - *(unvec + s - 1)) * facX; // dy of u^{\mu} components PRECISION dyut = (*(utvec + s + d_ncx) - *(utvec + s - d_ncx)) * facY; PRECISION dyux = (*(uxvec + s + d_ncx) - *(uxvec + s - d_ncx)) * facY; PRECISION dyuy = (*(uyvec + s + d_ncx) - *(uyvec + s - d_ncx)) * facY; PRECISION dyun = (*(unvec + s + d_ncx) - *(unvec + s - d_ncx)) * facY; // dn of u^{\mu} components int stride = d_ncx * d_ncy; PRECISION dnut = (*(utvec + s + stride) - *(utvec + s - stride)) * facZ; PRECISION dnux = (*(uxvec + s + stride) - *(uxvec + s - stride)) * facZ; PRECISION dnuy = (*(uyvec + s + stride) - *(uyvec + s - stride)) * facZ; PRECISION dnun = (*(unvec + s + stride) - *(unvec + s - stride)) * facZ; // pressure PRECISION dxp = (*(pvec + s + 1) - *(pvec + s - 1)) * facX; PRECISION dyp = (*(pvec + s + d_ncx) - *(pvec + s - d_ncx)) * facY; PRECISION dnp = (*(pvec + s + stride) - *(pvec + s - stride)) * facZ; // energy density PRECISION dxe = (*(evec + s + 1) - *(evec + s - 1)) * facX; PRECISION dye = (*(evec + s + d_ncx) - *(evec + s - d_ncx)) * facY; PRECISION dne = (*(evec + s + stride) - *(evec + s - stride)) * facZ; //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dxpitt = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpity = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixy = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 20; PRECISION dxPi = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; // Y ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dypitt = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitx = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypity = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypixy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypiyy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypiyn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dyPi = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; // Z ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dnpitt = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitx = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpity = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 15; PRECISION dnpixn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 10; PRECISION dnpiyn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpinn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnPi = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; //========================================================= // T^{\mu\nu} source terms //========================================================= PRECISION tnn = Tnn(e, p + Pi, un, pinn, t); PRECISION vx = ux / ut; PRECISION vy = uy / ut; PRECISION vn = un / ut; PRECISION dxvx = (dxux - vx * dxut) / ut; PRECISION dyvy = (dyuy - vy * dyut) / ut; PRECISION dnvn = (dnun - vn * dnut) / ut; PRECISION dkvk = dxvx + dyvy + dnvn; S[0] = -(ttt / t + t * tnn) + dkvk * (pitt - p - Pi) - vx * dxp - vy * dyp - vn * dnp; S[1] = -ttx / t - dxp + dkvk * pitx; S[2] = -tty / t - dyp + dkvk * pity; S[3] = -3 * ttn / t - dnp / powf(t, 2.0f) + dkvk * pitn; #ifdef USE_CARTESIAN_COORDINATES S[0] = dkvk*(pitt-p-Pi) - vx*dxp - vy*dyp - vn*dnp; S[1] = -dxp + dkvk*pitx; S[2] = -dyp + dkvk*pity; S[3] = -dnp + dkvk*pitn; #endif //X #ifndef PI S[0] += dxpitt*vx - dxpitx + dypitt*vy - dypity + dnpitt*vn - dnpitn; S[1] += dxpitx*vx - dxpixx + dypitx*vy - dypixy + dnpitx*vn - dnpixn; S[2] += dxpity*vx - dxpixy + dypity*vy - dypiyy + dnpity*vn - dnpiyn; S[3] += dxpitn*vx - dxpixn + dypitn*vy - dypiyn + dnpitn*vn - dnpinn; #else S[0] += dxpitt * vx - dxpitx - vx * dxPi + dypitt * vy - dypity - vy * dyPi + dnpitt * vn - dnpitn - vn * dnPi; S[1] += dxpitx * vx - dxpixx + dypitx * vy - dypixy + dnpitx * vn - dnpixn - dxPi; S[2] += dxpity * vx - dxpixy + dypity * vy - dypiyy + dnpity * vn - dnpiyn - dyPi; S[3] += dxpitn * vx - dxpixn + dypitn * vy - dypiyn + dnpitn * vn - dnpinn - dnPi / powf(t, 2.0f); #endif //========================================================= // \pi^{\mu\nu} source terms //========================================================= #ifndef IDEAL PRECISION pimunuRHS[NUMBER_DISSIPATIVE_CURRENTS]; setPimunuSourceTerms(pimunuRHS, t, e, p, ut, ux, uy, un, utp, uxp, uyp, unp, pitt, pitx, pity, pitn, pixx, pixy, pixn, piyy, piyn, pinn, Pi, dxut, dyut, dnut, dxux, dyux, dnux, dxuy, dyuy, dnuy, dxun, dyun, dnun, dkvk); for (unsigned int n = 0; n < NUMBER_DISSIPATIVE_CURRENTS; ++n) S[n + 4] = pimunuRHS[n]; #endif } /***************************************************************************************************************************************************/ __device__ void loadSourceTermsX(const PRECISION * const __restrict__ I, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, int s) { //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= PRECISION facX = 1 / d_dx / 2; int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dxpitt = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpity = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpitn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixx = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixy = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 5; PRECISION dxpixn = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; ptr += 20; PRECISION ut = u->ut[s]; PRECISION ux = u->ux[s]; //========================================================= // set dx terms in the source terms //========================================================= PRECISION vx = ux / ut; #ifndef PI S[0] = dxpitt*vx - dxpitx; S[1] = dxpitx*vx - dxpixx; #else PRECISION dxPi = (*(I + ptr + 3) - *(I + ptr + 1)) * facX; S[0] = dxpitt * vx - dxpitx - vx * dxPi; S[1] = dxpitx * vx - dxpixx - dxPi; #endif S[2] = dxpity * vx - dxpixy; S[3] = dxpitn * vx - dxpixn; } __device__ void loadSourceTermsY(const PRECISION * const __restrict__ J, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, int s) { //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= PRECISION facY = 1 / d_dy / 2; int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dypitt = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitx = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypity = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypitn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypixy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION dypiyy = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 5; PRECISION dypiyn = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; ptr += 10; PRECISION ut = u->ut[s]; PRECISION uy = u->uy[s]; //========================================================= // set dy terms in the source terms //========================================================= PRECISION vy = uy / ut; #ifndef PI S[0] = dypitt*vy - dypity; S[2] = dypity*vy - dypiyy; #else PRECISION dyPi = (*(J + ptr + 3) - *(J + ptr + 1)) * facY; S[0] = dypitt * vy - dypity - vy * dyPi; S[2] = dypity * vy - dypiyy - dyPi; #endif S[1] = dypitx * vy - dypixy; S[3] = dypitn * vy - dypiyn; } __device__ void loadSourceTermsZ(const PRECISION * const __restrict__ K, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, int s, PRECISION t) { //========================================================= // spatial derivatives of the conserved variables \pi^{\mu\nu} //========================================================= PRECISION facZ = 1 / d_dz / 2; int ptr = 20; // 5 * n (with n = 4 corresponding to pitt) PRECISION dnpitt = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitx = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpity = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpitn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 15; PRECISION dnpixn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 10; PRECISION dnpiyn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION dnpinn = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; ptr += 5; PRECISION ut = u->ut[s]; PRECISION un = u->un[s]; //========================================================= // set dn terms in the source terms //========================================================= PRECISION vn = un / ut; #ifndef PI S[0] = dnpitt*vn - dnpitn; S[3] = dnpitn*vn - dnpinn; #else PRECISION dnPi = (*(K + ptr + 3) - *(K + ptr + 1)) * facZ; S[0] = dnpitt * vn - dnpitn - vn * dnPi; S[3] = dnpitn * vn - dnpinn - dnPi / powf(t, 2); #endif S[1] = dnpitx * vn - dnpixn; S[2] = dnpity * vn - dnpiyn; } __device__ void loadSourceTerms2(const PRECISION * const __restrict__ Q, PRECISION * const __restrict__ S, const FLUID_VELOCITY * const __restrict__ u, PRECISION utp, PRECISION uxp, PRECISION uyp, PRECISION unp, PRECISION t, const PRECISION * const __restrict__ evec, const PRECISION * const __restrict__ pvec, const CONSERVED_VARIABLES * const __restrict__ currentVars, int s) { //========================================================= // conserved variables //========================================================= PRECISION ttt = Q[0]; PRECISION ttx = Q[1]; PRECISION tty = Q[2]; PRECISION ttn = Q[3]; PRECISION pl = Q[4]; #ifdef PIMUNU PRECISION pitt = Q[5]; PRECISION pitx = Q[6]; PRECISION pity = Q[7]; PRECISION pitn = Q[8]; PRECISION pixx = Q[9]; PRECISION pixy = Q[10]; PRECISION pixn = Q[11]; PRECISION piyy = Q[12]; PRECISION piyn = Q[13]; PRECISION pinn = Q[14]; #else PRECISION pitt = 0; PRECISION pitx = 0; PRECISION pity = 0; PRECISION pitn = 0; PRECISION pixx = 0; PRECISION pixy = 0; PRECISION pixn = 0; PRECISION piyy = 0; PRECISION piyn = 0; PRECISION pinn = 0; #endif #ifdef W_TZ_MU PRECISION WtTz = Q[15]; PRECISION WxTz = Q[16]; PRECISION WyTz = Q[17]; PRECISION WnTz = Q[18]; #else PRECISION WtTz = 0; PRECISION WxTz = 0; PRECISION WyTz = 0; PRECISION WnTz = 0; #endif // \Pi #ifdef PI PRECISION Pi = Q[NUMBER_CONSERVED_VARIABLES-1]; #else PRECISION Pi = 0; #endif //========================================================= // primary variables //========================================================= PRECISION *utvec = u->ut; PRECISION *uxvec = u->ux; PRECISION *uyvec = u->uy; PRECISION *unvec = u->un; PRECISION e = evec[s]; PRECISION p = pvec[s]; PRECISION ut = utvec[s]; PRECISION ux = uxvec[s]; PRECISION uy = uyvec[s]; PRECISION un = unvec[s]; //========================================================= // spatial derivatives of primary variables //========================================================= PRECISION facX = 1 / d_dx / 2; PRECISION facY = 1 / d_dy / 2; PRECISION facZ = 1 / d_dz / 2; // dx of u^{\mu} components PRECISION dxut = (*(utvec + s + 1) - *(utvec + s - 1)) * facX; PRECISION dxux = (*(uxvec + s + 1) - *(uxvec + s - 1)) * facX; PRECISION dxuy = (*(uyvec + s + 1) - *(uyvec + s - 1)) * facX; PRECISION dxun = (*(unvec + s + 1) - *(unvec + s - 1)) * facX; // dy of u^{\mu} components PRECISION dyut = (*(utvec + s + d_ncx) - *(utvec + s - d_ncx)) * facY; PRECISION dyux = (*(uxvec + s + d_ncx) - *(uxvec + s - d_ncx)) * facY; PRECISION dyuy = (*(uyvec + s + d_ncx) - *(uyvec + s - d_ncx)) * facY; PRECISION dyun = (*(unvec + s + d_ncx) - *(unvec + s - d_ncx)) * facY; // dn of u^{\mu} components int stride = d_ncx * d_ncy; PRECISION dnut = (*(utvec + s + stride) - *(utvec + s - stride)) * facZ; PRECISION dnux = (*(uxvec + s + stride) - *(uxvec + s - stride)) * facZ; PRECISION dnuy = (*(uyvec + s + stride) - *(uyvec + s - stride)) * facZ; PRECISION dnun = (*(unvec + s + stride) - *(unvec + s - stride)) * facZ; // pressure PRECISION dxp = (*(pvec + s + 1) - *(pvec + s - 1)) * facX; PRECISION dyp = (*(pvec + s + d_ncx) - *(pvec + s - d_ncx)) * facY; PRECISION dnp = (*(pvec + s + stride) - *(pvec + s - stride)) * facZ; // energy density PRECISION dxe = (*(evec + s + 1) - *(evec + s - 1)) * facX; PRECISION dye = (*(evec + s + d_ncx) - *(evec + s - d_ncx)) * facY; PRECISION dne = (*(evec + s + stride) - *(evec + s - stride)) * facZ; //added by DEREK below //========================================================= // Deriviatives of v //========================================================= PRECISION vx = ux/ut; PRECISION vy = uy/ut; PRECISION vn = un/ut; PRECISION dxvx = (dxux - vx * dxut)/ ut; PRECISION dyvy = (dyuy - vy * dyut)/ ut; PRECISION dnvn = (dnun - vn * dnut)/ ut; PRECISION dkvk = dxvx + dyvy + dnvn; PRECISION t2 = t*t; PRECISION t3 = t*t2; PRECISION un2 = un*un; PRECISION ut2 = ut*ut; /************************************************************************************\ * Gradient terms of the fluid velocity /************************************************************************************/ // time derivatives of u PRECISION dtut = (ut - utp) / d_dt; PRECISION dtux = (ux - uxp) / d_dt; PRECISION dtuy = (uy - uyp) / d_dt; PRECISION dtun = (un - unp) / d_dt; // covariant derivatives PRECISION Dut = ut*dtut + ux*dxut + uy*dyut + un*dnut + t*un*un; PRECISION DuxUpper = ut*dtux + ux*dxux + uy*dyux + un*dnux; PRECISION Dux = -DuxUpper; PRECISION DuyUpper = ut*dtuy + ux*dxuy + uy*dyuy + un*dnuy; PRECISION Duy = -DuyUpper; PRECISION DunUpper = ut*dtun + ux*dxun + uy*dyun + un*dnun + 2*ut*un/t; PRECISION Dun = -t2*DunUpper; PRECISION dut = Dut -t*un*un; PRECISION dux = ut*dtux + ux*dxux + uy*dyux + un*dnux; PRECISION duy = ut*dtuy + ux*dxuy + uy*dyuy + un*dnuy; PRECISION dun = ut*dtun + ux*dxun + uy*dyun + un*dnun; // expansion rate PRECISION theta = ut / t + dtut + dxux + dyuy + dnun; // shear tensor PRECISION stt = -t * ut * un2 + (dtut - ut * dut) + (ut2 - 1) * theta / 3; PRECISION stx = -(t * un2 * ux) / 2 + (dtux - dxut) / 2 - (ux * dut + ut * dux) / 2 + ut * ux * theta / 3; PRECISION sty = -(t * un2 * uy) / 2 + (dtuy - dyut) / 2 - (uy * dut + ut * duy) / 2 + ut * uy * theta / 3; PRECISION stn = -un * (2 * ut2 + t2 * un2) / (2 * t) + (dtun - dnut / t2) / 2 - (un * dut + ut * dun) / 2 + ut * un * theta / 3; PRECISION sxx = -(dxux + ux * dux) + (1 + ux*ux) * theta / 3; PRECISION sxy = -(dxuy + dyux) / 2 - (uy * dux + ux * duy) / 2 + ux * uy * theta / 3; PRECISION sxn = -ut * ux * un / t - (dxun + dnux / t2) / 2 - (un * dux + ux * dun) / 2 + ux * un * theta / 3; PRECISION syy = -(dyuy + uy * duy) + (1 + uy*uy) * theta / 3; PRECISION syn = -ut * uy * un / t - (dyun + dnuy / t2) / 2 - (un * duy + uy * dun) / 2 + uy * un * theta / 3; PRECISION snn = -ut * (1 + 2 * t2 * un2) / t3 - dnun / t2 - un * dun + (1 / t2 + un2) * theta / 3; // vorticity tensor PRECISION wtx = (dtux + dxut) / 2 + (ux * dut - ut * dux) / 2 + t * un2 * ux / 2; PRECISION wty = (dtuy + dyut) / 2 + (uy * dut - ut * duy) / 2 + t * un2 * uy / 2; PRECISION wtn = (t2 * dtun + 2 * t * un + dnut) / 2 + (t2 * un * dut - ut * Dun) + t3 * un*un2 / 2; PRECISION wxy = (dyux - dxuy) / 2 + (uy * dux - ux * duy) / 2; PRECISION wxn = (dnux - t2 * dxun) / 2 + (t2 * un * dux - ux * Dun) / 2; PRECISION wyn = (dnuy - t2 * dyun) / 2 + (t2 * un * duy - uy * Dun) / 2; // anti-symmetric vorticity components PRECISION wxt = wtx; PRECISION wyt = wty; PRECISION wnt = wtn / t2; PRECISION wyx = -wxy; PRECISION wnx = -wxn / t2; PRECISION wny = -wyn / t2; /************************************************************************************\ * Split transverse and longitudinal gradients of the fluid velocity /************************************************************************************/ // transverse flow velocity PRECISION uT2 = ux*ux+uy*uy; PRECISION uT = sqrt(uT2); PRECISION uTdtuT = (ux*dtux+uy*dtuy); PRECISION uTdxuT = (ux*dxux+uy*dxuy); PRECISION uTdyuT = (ux*dyux+uy*dyuy); PRECISION uTdnuT = (ux*dnux+uy*dnuy); PRECISION uTduT = ut*uTdtuT+ux*uTdxuT+uy*uTdyuT+un*uTdnuT; PRECISION F = 1+uT2; PRECISION F2 = F*F; PRECISION FS = sqrt(1+uT2); double z0 = t*un/sqrt(F); double z1 = 0; double z2 = 0; double z3 = ut/t/sqrt(F); double z02 = z0*z0; double z0z3 = z0*z3; double z32 = z3*z3; // g^{\mu\nu} double gtt = 1; double gxx = -1; double gyy = -1; double gnn = -1/t2; // \Delta_{\perp}^{\mu\nu} double Xitt = gtt-ut*ut+z02; double Xitx = -ut*ux; double Xity = -ut*uy; double Xitn = -ut*un+z0z3; double Xixx = gxx-ux*ux; double Xixy = -ux*uy; double Xixn = -ux*un; double Xiyy = gyy-uy*un; double Xiyn = -uy*un; double Xinn = gnn-un*un+z32; // covariant derivatives of z double dz0 = (ut*un+t*dun-t*un/F*uTduT)/sqrt(F); double dz3 = (-ut2/t2+dut/t-ut/t/F*uTduT)/sqrt(F); double Dz0 = dz0+t*un*z3; double Dz3Upper = dz3+(ut*z3+un*z0)/t; double Dz3 = -t2*Dz3Upper; double A = z02*stt-2*t2*z0z3*stn+t2*t2*z32*snn; // B double B0 = z0*stt-t2*z3*stn; double B1 = z0*stx-t2*z3*sxn; double B2 = z0*sty-t2*z3*syn; double B3 = z0*stn-t2*z3*snn; // Bw double Bw0 = z3*wtn; double Bw1 = z0*wtx+z3*wxn; double Bw2 = z0*wty+z3*wyn; double Bw3 = z0*wtn/t2; // transverse and longitudinal expansion scalars double thetaT = 2*theta/3+A; double zDzu = theta/3-A; zDzu = theta-thetaT; // transverse shear tensor double sttT = stt+2*z0*B0+z02*A-0.5*(1-ut*ut+z02)*A; double stxT = stx+z0*B1-0.5*(-ut*ux)*A; double styT = sty+z0*B2-0.5*(-ut*uy)*A; double stnT = stn+z0*B3+z3*B0+z0z3*A-0.5*(-ut*un+z0z3)*A; double sxxT = sxx-0.5*(-1-ux*ux)*A; double sxyT = sxy-0.5*(-ux*uy)*A; double sxnT = sxn+z3*B1-0.5*(-ux*un)*A; double syyT = syy-0.5*(-1-uy*uy)*A; double synT = syn+z3*B2-0.5*(-uy*un)*A; double snnT = snn+2*z3*B3+z32*A-0.5*(-1/t2-un*un+z32)*A; /************************************************************************************\ * Anisotropic hydro stuff /************************************************************************************/ if(e==0) e=1.e-7; PRECISION T = effectiveTemperature(e); PRECISION cs2 = speedOfSoundSquared(e); double a = pl/e; double a2 = a*a; double a3 = a2*a; double a4 = a3*a; double a5 = a4*a; double a6 = a5*a; double a7 = a6*a; double a8 = a7*a; double a9 = a8*a; double a10 = a9*a; double a11 = a10*a; double a12 = a11*a; double a13 = a12*a; double a14 = a13*a; double a15 = a14*a; PRECISION Rtilde = (-6.674731906076046e-6 + 0.004617789933500251*a + 0.7207562721999754*a2 + 9.097427250602184*a3 - 4.475814747302824*a4 - 36.37501529319408*a5 + 46.868405146729316*a6 - 15.833867583743228*a7)/ (0.06856675185266 + 2.9181587012768597*a + 11.951184087839218*a2 - 29.708257843442173*a3 - 2.618233802059826*a4 + 34.646239784689065*a5 - 19.62596366454439*a6 + 2.374808442453899*a7); PRECISION Rhat = (0.0024792827625583747 + 1.943027171680747*a + 53.46970495217282*a2 + 19.989171951866325*a3 - 347.1285593126723*a4 + 412.2647882672885*a5 - 140.53693383827797*a6)/(0.5061402347582388 + 29.466067530916984*a + 126.07947638942892*a2 - 334.420268508072*a3 + 86.57706367583984*a4 + 183.53625188578846*a5 - 91.68259808111912*a6); PRECISION Rbar0 = (0.015267955823446243 + 7.725572805021035*a + 421.0063884634789*a2 + 3422.877939650926*a3 - 5785.670846299543*a4 - 12261.66452089229*a5 + 31491.409484673808*a6 - 22737.05146992673*a7 + 5441.373392185447*a8)/ (0.05470696094814806 + 14.505878005231883*a + 522.6643024173569*a2 + 2731.7776413939037*a3 - 6161.1991042880445*a4 - 3989.4375208972588*a5 + 15008.260526258282*a6 - 10243.036679405379*a7 + 2116.74060159494*a8); PRECISION Rgamma = (0.0001373796340585521 - 0.6149634004722385*a + 3.1968875683514253*a2 + 246.35973783799196*a3 - 764.319750320186*a4 + 834.160165071214*a5 - 371.64955466673234*a6 + 52.87411921963021*a7)/ (-1.673322188488071 + 13.343782941396997*a + 561.7566534476223*a2 - 1790.2296622275915*a3 + 1896.4688704912812*a4 - 658.7933063369629*a5 - 85.96181900698849*a6 + 65.09739194472589*a7); double Rbar0P = (2.473173363908116e-10 - 4.899839370307281e-6*a + 155055.91462124084*a10 - 275435.45350226434*a11 + 350689.68825705117*a12 - 299725.38986957155*a13 + 151477.08809203724*a14 - 33196.47417939176*a15 - 0.004301975027942015*a2 - 0.14858206981041563*a3 + 6.249255189587875*a4 - 92.79641927240235*a5 + 807.175057749925*a6 - 4760.015905266286*a7 + 20324.533122685436*a8 - 64758.869552496515*a9)/(0.00008222793468208523 + 0.03411917870833943*a + 4.895969276094396e6*a10 - 8.84162305829353e6*a11 + 1.1445063656613324e7*a12 - 9.918442713390596e6*a13 + 5.065882388219598e6*a14 - 1.1181016364928822e6*a15 + 0.23871740573818725*a2 - 23.50912574236691*a3 + 417.4953123877312*a4 - 4234.215775452717*a5 + 29824.022790048104*a6 - 157419.8447785501*a7 + 641300.6529027821*a8 - 2.0248032895288002e6*a9); double R0g1m2031 = (-1.0233483506421896e-7 - 0.005510394233958543*a - 0.5161308003737349*a2 - 4.115511461930346*a3 + 6.378431203946746*a4 + 3.926438723664259*a5 - 8.465485699618803*a6 + 2.7925630611642154*a7)/ (0.001958161993306958 + 0.22517859370360388*a + 2.883216830325076*a2 + 0.1905363935371778*a3 - 12.192584184275201*a4 + 10.729468548753893*a5 - 0.8635431725599291*a6 - 0.9690254375998808*a7); // longitudinal pressure PRECISION dxpl = (*(currentVars->pl + s + 1) - *(currentVars->pl + s - 1)) * facX; PRECISION dypl = (*(currentVars->pl + s + d_ncx) - *(currentVars->pl + s - d_ncx)) * facY; PRECISION dnpl = (*(currentVars->pl + s + stride) - *(currentVars->pl + s - stride)) * facZ; PRECISION ptHat = transversePressureHat(e, p, pl); PRECISION pt = ptHat + 1.5*Pi; PRECISION DP = pl-pt; // L functions PRECISION Ltt = DP*t2*un2/F; PRECISION Ltn = DP*ut*un/F; PRECISION Lnn = DP*ut2/F/t2; // W functions double Wtt = 2*WtTz*z0; double Wtx = WxTz*z0; double Wty = WyTz*z0; double Wtn = WtTz*z3+WnTz*z0; double Wxx = 0; double Wxy = 0; double Wxn = WxTz*z3; double Wyy = 0; double Wyn = WyTz*z3; double Wnn = 2*WnTz*z3; // derivatives of z0 double dxz0 = t*(dxun/sqrt(F)-un/pow(F,1.5)*uTdxuT); double dyz0 = t*(dyun/sqrt(F)-un/pow(F,1.5)*uTdyuT); double dnz0 = t*(dnun/sqrt(F)-un/pow(F,1.5)*uTdnuT); // derivatives of z3 double dxz3 = (dxut/sqrt(F)-ut/pow(F,1.5)*uTdxuT)/t; double dyz3 = (dyut/sqrt(F)-ut/pow(F,1.5)*uTdyuT)/t; double dnz3 = (dnut/sqrt(F)-ut/pow(F,1.5)*uTdnuT)/t; // derivative of W^{\mu}_{\perp z} #ifdef W_TZ_MU // WtTz PRECISION dxWtTz = (*(currentVars->WtTz + s + 1) - *(currentVars->WtTz + s - 1)) * facX; PRECISION dyWtTz = (*(currentVars->WtTz + s + d_ncx) - *(currentVars->WtTz + s - d_ncx)) * facY; PRECISION dnWtTz = (*(currentVars->WtTz + s + stride) - *(currentVars->WtTz + s - stride)) * facZ; // WxTz PRECISION dxWxTz = (*(currentVars->WxTz + s + 1) - *(currentVars->WxTz + s - 1)) * facX; PRECISION dyWxTz = (*(currentVars->WxTz + s + d_ncx) - *(currentVars->WxTz + s - d_ncx)) * facY; PRECISION dnWxTz = (*(currentVars->WxTz + s + stride) - *(currentVars->WxTz + s - stride)) * facZ; // WyTz PRECISION dxWyTz = (*(currentVars->WyTz + s + 1) - *(currentVars->WyTz + s - 1)) * facX; PRECISION dyWyTz = (*(currentVars->WyTz + s + d_ncx) - *(currentVars->WyTz + s - d_ncx)) * facY; PRECISION dnWyTz = (*(currentVars->WyTz + s + stride) - *(currentVars->WyTz + s - stride)) * facZ; // WnTz PRECISION dxWnTz = (*(currentVars->WnTz + s + 1) - *(currentVars->WnTz + s - 1)) * facX; PRECISION dyWnTz = (*(currentVars->WnTz + s + d_ncx) - *(currentVars->WnTz + s - d_ncx)) * facY; PRECISION dnWnTz = (*(currentVars->WnTz + s + stride) - *(currentVars->WnTz + s - stride)) * facZ; #else // WnTz PRECISION dxWtTz = 0; PRECISION dyWtTz = 0; PRECISION dnWtTz = 0; // WxTz PRECISION dxWxTz = 0; PRECISION dyWxTz = 0; PRECISION dnWxTz = 0; // WyTz PRECISION dxWyTz = 0; PRECISION dyWyTz = 0; PRECISION dnWyTz = 0; // WnTz PRECISION dxWnTz = 0; PRECISION dyWnTz = 0; PRECISION dnWnTz = 0; #endif //========================================================= // derivatives of W in conservation law source terms //========================================================= // Wtt double dxWtt = 2*t*(WtTz*dxun-un*WtTz*uTdxuT/F+un*dxWtTz)/FS; double dyWtt = 2*t*(WtTz*dyun-un*WtTz*uTdyuT/F+un*dyWtTz)/FS; double dnWtt = 2*t*(WtTz*dnun-un*WtTz*uTdnuT/F+un*dnWtTz)/FS; // Wtx double dxWtx = t*(WxTz*dxun-un*WxTz*uTdxuT/F+un*dxWxTz)/FS; double dyWtx = t*(WxTz*dyun-un*WxTz*uTdyuT/F+un*dyWxTz)/FS; double dnWtx = t*(WxTz*dnun-un*WxTz*uTdnuT/F+un*dnWxTz)/FS; // Wty double dxWty = t*(WyTz*dxun-un*WyTz*uTdxuT/F+un*dxWyTz)/FS; double dyWty = t*(WyTz*dyun-un*WyTz*uTdyuT/F+un*dyWyTz)/FS; double dnWty = t*(WyTz*dnun-un*WyTz*uTdnuT/F+un*dnWyTz)/FS; // Wtn double dxWtn = (WtTz*dxut-ut*WtTz*uTdxuT/F+ut*dxWyTz)/FS/t+t*(WnTz*dxun-un*WnTz*uTdxuT/F+un*dxWnTz)/FS; double dyWtn = (WtTz*dyut-ut*WtTz*uTdyuT/F+ut*dyWyTz)/FS/t+t*(WnTz*dyun-un*WnTz*uTdyuT/F+un*dyWnTz)/FS; double dnWtn = (WtTz*dnut-ut*WtTz*uTdnuT/F+ut*dnWyTz)/FS/t+t*(WnTz*dnun-un*WnTz*uTdnuT/F+un*dnWnTz)/FS; // Wxn double dxWxn = (WxTz*dxut-ut*WxTz*uTdxuT/F+ut*dxWxTz)/FS/t; double dnWxn = (WxTz*dnut-ut*WxTz*uTdnuT/F+ut*dnWxTz)/FS/t; // Wyn double dyWyn = (WyTz*dyut-ut*WyTz*uTdyuT/F+ut*dyWyTz)/FS/t; double dnWyn = (WyTz*dnut-ut*WyTz*uTdnuT/F+ut*dnWyTz)/FS/t; // Wnn double dnWnn = 2*(WnTz*dnut-ut*WnTz*uTdnuT/F+ut*dnWnTz)/FS/t; PRECISION tnn = (e+pt)*un*un+pt/t2+Lnn+Wnn+pinn; // deritive of Rbar double dxRbar0 = Rbar0P*(dxpl-a*dxe)/e; double dyRbar0 = Rbar0P*(dypl-a*dye)/e; double dnRbar0 = Rbar0P*(dnpl-a*dne)/e; // derivative of transverse pressure PRECISION dxptHat = 0.5*(dxe-dxpl-Rbar0*(dxe-3*dxp)-(e-3*p)*dxRbar0); PRECISION dyptHat = 0.5*(dye-dypl-Rbar0*(dye-3*dyp)-(e-3*p)*dyRbar0); PRECISION dnptHat = 0.5*(dne-dnpl-Rbar0*(dne-3*dnp)-(e-3*p)*dnRbar0); // derivative of \Delta P -- NEED TO ADD DERIVATIVES OF BULK PI PRECISION dxDP = dxpl-dxptHat; PRECISION dyDP = dypl-dyptHat; PRECISION dnDP = dnpl-dnptHat; // spatial derivatives of Ltt PRECISION dxLtt = (2*DP*dxun*t2*un)/F + (dxDP*t2*un2)/F - (2*DP*uTdxuT*t2*un2)/F2; PRECISION dyLtt = (2*DP*dyun*t2*un)/F + (dyDP*t2*un2)/F - (2*DP*uTdyuT*t2*un2)/F2; PRECISION dnLtt = (2*DP*dnun*t2*un)/F + (dnDP*t2*un2)/F - (2*DP*uTdnuT*t2*un2)/F2; // spatial derivatives of Ltn PRECISION dxLtn = (DP*dxut*un)/F + (DP*dxun*ut)/F + (dxDP*un*ut)/F - (2*DP*uTdxuT*un*ut)/F2; PRECISION dyLtn = (DP*dyut*un)/F + (DP*dyun*ut)/F + (dyDP*un*ut)/F - (2*DP*uTdyuT*un*ut)/F2; PRECISION dnLtn = (DP*dnut*un)/F + (DP*dnun*ut)/F + (dnDP*un*ut)/F - (2*DP*uTdnuT*un*ut)/F2; // spatial derivatives of Lnn PRECISION dnLnn = (2*DP*dnut*ut)/(F*t2) + (dnDP*ut2)/(F*t2) - (2*DP*uTdnuT*ut2)/(F2*t2); PRECISION zeta_zz = Rtilde*e-3*pl; PRECISION zeta_zT = (Rtilde*e + pl)/2.; //============================================== // second-order transport coefficients //============================================== double beta_lPi=0; double delta_lPi=0; double lambda_piPi=0; double beta_PiPi=0; double delta_PiPi=0; double lambda_Pipi=0; secondOrderTransportCoefficientsZ(e, p, pl, cs2, T, &beta_lPi, &delta_lPi, &lambda_piPi, &beta_PiPi, &delta_PiPi, &lambda_Pipi); // Pl double lambda_lWu = R0g1m2031; double lambda_lWT = 2+lambda_lWu; double lambda_lpi = Rgamma; // W double delta_WW = lambda_lWu/2-1; double lambda_WWu = 2 + lambda_lWu; double lambda_WWT = 1 + delta_WW; double lambda_Wpiu = lambda_lpi; double lambda_WpiT = lambda_Wpiu-1; // pi^\mu\nu double delta_pipi = (3+Rgamma)/2; double tau_pipi = 4*(delta_pipi-1/2)/3; double lambda_pipi = Rgamma-1; double lambda_piWu = delta_WW-1/2; double lambda_piWT = lambda_piWu+2; PRECISION taupiInv = 0.2 * T/d_etabar; PRECISION psT = pitt * sttT - 2 * pitx * stxT - 2 * pity * styT + pixx * sxxT + 2 * pixy * sxyT + piyy * syyT - 2 * pitn * stnT * t2 + 2 * pixn * sxnT * t2 + 2 * piyn * synT * t2 + pinn * snnT * t2 * t2; // IL1 double IL1 = -(WtTz*B0 - WxTz*B1 - WyTz*B2 - t2*WnTz*B3) + (WtTz*Bw0 - WxTz*Bw1 - WyTz*Bw2 - t2*WnTz*Bw3); // IL2 double IL2 = (WtTz*B0 - WxTz*B1 - WyTz*B2 - t2*WnTz*B3) + (WtTz*Bw0 - WxTz*Bw1 - WyTz*Bw2 - t2*WnTz*Bw3); // IL3 double IL3 = psT; // IL double IL = lambda_lWu * IL1 - lambda_lWT * IL2 - lambda_lpi * IL3; // IL=0; // PRECISION dPL = -(pl-p)*taupiInv + zeta_zz*zDzu - zeta_zT*thetaT - lambda_lpi * psT; PRECISION dPL = -(pl-p)*taupiInv + zeta_zz*zDzu - zeta_zT*thetaT - beta_lPi * Pi * zDzu - delta_lPi * Pi * thetaT + IL; S[4] = dPL / ut + dkvk * pl; /* if(isnan(S[4])) { printf("=======================================================================================\n"); printf("Found Nan in S[4]:\n"); printf("pl=%.9f;\n",pl); printf("Grid point = (%d, %d, %d) = (%.3f, %.3f, %.3f)\n", i, j, k, x, y, z); printf("Rhat=%.9f;Rtilde=%.39f;\n",Rhat,Rtilde); printf("pl = %.9f\n",pl); printf("e = %.9f\n",e); printf("a = %.9f\n",a); printf("T=%.9f;e=%.9f;p=%.9f;\n",T,e,p); printf("ut=%.9f;ux=%.9f;uy=%.9f\n",ut,ux,uy); printf("ux[s+1]=%.9f; ux[s-1]=%.9f\n",*(uxvec + s + 1),*(uxvec + s - 1)); printf("uy[s+1]=%.9f; uy[s-1]=%.9f\n",*(uyvec + s + 1),*(uyvec + s - 1)); printf("dx=%.3f;dy=%.3f;facX=%.3f;facY=%.3f\n",d_dx,d_dy,facX,facY); printf("zeta_zz=%.3f;zeta_zT=%.3f;dtu0=%.3f;zDzu=%.3f;thetaT=%.3f;taupiInv=%.3f;\n",zeta_zz,zeta_zT,dtut,zDzu,thetaT,taupiInv); printf("=======================================================================================\n"); exit(-1); } */ /************************************************************************************\ * T^{\mu\nu} source terms /************************************************************************************/ double Htt = Ltt+Wtt+pitt; S[0] = -(ttt / t + t * tnn) + dkvk * (Htt - pt) - vx * dxptHat - vy * dyptHat - vn * dnptHat + vx*(dxLtt+dxWtt)-dxWtx + vy*(dyLtt+dyWtt)-dyWty + vn*(dnLtt+dnWtt)-dnLtn-dnWtn; S[1] = -ttx / t - dxptHat + dkvk * (Wtx + pitx) + vx*dxWtx + vy*dyWtx + vn*dnWtx - dnWxn; S[2] = -tty / t - dyptHat + dkvk * (Wty + pity) + vx*dxWty + vy*dyWty + vn*dnWty - dnWyn; S[3] = -3 * ttn / t - dnptHat / t2 + dkvk * (Ltn + Wtn + pitn) + vx*(dxLtn+dxWtn)-dxWxn + vy*(dyLtn+dyWtn)-dyWyn + vn*(dnLtn+dnLtn)-dnLnn-dnWnn; /* if(isnan(S[0])) { printf("=======================================================================================\n"); printf("Found Nan in S[0]:\n"); printf("pl=%.9f;\n",pl); printf("Grid point = (%d, %d, %d) = (%.3f, %.3f, %.3f)\n", i, j, k, x, y, z); printf("Rhat=%.9f;Rtilde=%.39f;\n",Rhat,Rtilde); printf("pl = %.9f\n",pl); printf("e = %.9f\n",e); printf("a = %.9f\n",a); printf("T=%.9f;e=%.9f;p=%.9f;\n",T,e,p); printf("ut=%.9f;ux=%.9f;uy=%.9f\n",ut,ux,uy); printf("ux[s+1]=%.9f; ux[s-1]=%.9f\n",*(uxvec + s + 1),*(uxvec + s - 1)); printf("uy[s+1]=%.9f; uy[s-1]=%.9f\n",*(uyvec + s + 1),*(uyvec + s - 1)); printf("dx=%.3f;dy=%.3f;facX=%.3f;facY=%.3f\n",d_dx,d_dy,facX,facY); printf("zeta_zz=%.3f;zeta_zT=%.3f;dtu0=%.3f;zDzu=%.3f;thetaT=%.3f;taupiInv=%.3f;\n",zeta_zz,zeta_zT,dtut,zDzu,thetaT,taupiInv); printf("taupiInv=%.3f;\n",taupiInv); printf("-------------------------------------------\n"); printf("ttt=%.9f;tnn=%.9f\n",ttt,tnn); printf("dkvk=%.9f;vx=%.9f;vy=%.9f;vn=%.9f\n",dkvk,vx,vy,vn); printf("pt=%.9f;dxpt=%.9f;dypt=%.9f;dnpt=%.9f\n",pt,dxptHat,dyptHat,dnptHat); printf("Ltt=%.9f;dxLtt=%.9f;dyLtt=%.9f;dnLtt=%.9f\n",Ltt,dxLtt,dyLtt,dnLtt); printf("Ltn=%.9f;dxLtn=%.9f;dyLtn=%.9f;dnLtn=%.9f\n",Ltn,dxLtn,dyLtn,dnLtn); printf("dnLnn=%.9f\n",dnLnn); printf("dxpt=%.9f;dypt=%.9f;dnpt=%.9f;\n",dxptHat,dyptHat,dnptHat); printf("dxDP=%.9f;dyDP=%.9f;dnDP=%.9f;\n",dxDP,dyDP,dnDP); printf("DP=%.9f;F=%.9f;uT=%.9f\n",DP,F,uT); printf("uTdxuT=%.9f;uTdyuT=%.9f;uTdnuT=%.9f;\n",uTdxuT,uTdyuT,uTdnuT); printf("dxux=%.9f;dyux=%.9f;dnux=%.9f;\n",dxux,dyux,dnux); printf("dxuy=%.9f;dyuy=%.9f;dnuy=%.9f;\n",dxuy,dyuy,dnuy); printf("=======================================================================================\n"); exit(-1); } */ /************************************************************************************\ * \pi^{\mu\nu}_\perp source terms /************************************************************************************/ #ifdef PIMUNU double etaBar_TC = ((3-Rtilde)*e-2*pl)/8; // I1 PRECISION I1Utt = 2 * ut * (pitt * Dut + pitx * Dux + pity * Duy + pitn * Dun); PRECISION I1Utx = (pitt * ux + pitx * ut) * Dut + (pitx * ux + pixx * ut) * Dux + (pity * ux + pixy * ut) * Duy + (pitn * ux + pixn * ut) * Dun; PRECISION I1Uty = (pitt * uy + pity * ut) * Dut + (pitx * uy + pixy * ut) * Dux + (pity * uy + piyy * ut) * Duy + (pitn * uy + piyn * ut) * Dun; PRECISION I1Utn = (pitt * un + pitn * ut) * Dut + (pitx * un + pixn * ut) * Dux + (pity * un + piyn * ut) * Duy + (pitn * un + pinn * ut) * Dun; PRECISION I1Uxx = 2 * ux * (pitx * Dut + pixx * Dux + pixy * Duy + pixn * Dun); PRECISION I1Uxy = (pitx * uy + pity * ux) * Dut + (pixx * uy + pixy * ux) * Dux + (pixy * uy + piyy * ux) * Duy + (pixn * uy + piyn * ux) * Dun; PRECISION I1Uxn = (pitx * un + pitn * ux) * Dut + (pixx * un + pixn * ux) * Dux + (pixy * un + piyn * ux) * Duy + (pixn * un + pinn * ux) * Dun; PRECISION I1Uyy = 2 * uy * (pity * Dut + pixy * Dux + piyy * Duy + piyn * Dun); PRECISION I1Uyn = (pity * un + pitn * uy) * Dut + (pixy * un + pixn * uy) * Dux + (piyy * un + piyn * uy) * Duy + (piyn * un + pinn * uy) * Dun; PRECISION I1Unn = 2 * un * (pitn * Dut + pixn * Dux + piyn * Duy + pinn * Dun); //Dz0=0; //Dz3=0; PRECISION I1Ztt = 2 * z0 * (pitt * Dz0 + pitn * Dz3); PRECISION I1Ztx = ( pitx * z0) * Dz0 + (pitn * ux + pixn * z0) * Dz3; PRECISION I1Zty = (pity * z0) * Dz0 + (pitn * uy + piyn * z0) * Dz3; PRECISION I1Ztn = (pitt * z3 + pitn * z0) * Dz0 + (pitn * z3 + pinn * z0) * Dz3; PRECISION I1Zxx = 0; PRECISION I1Zxy = 0; PRECISION I1Zxn = (pitx * z3) * Dz0 + (pixn * z3) * Dz3; PRECISION I1Zyy = 0; PRECISION I1Zyn = (pity * z3) * Dz0 + (piyn * z3) * Dz3; PRECISION I1Znn = 2 * z3 * (pitn * Dz0 + pinn * Dz3); PRECISION I1tt = I1Utt - I1Ztt; PRECISION I1tx = I1Utx - I1Ztx; PRECISION I1ty = I1Uty - I1Zty; PRECISION I1tn = I1Utn - I1Ztn; PRECISION I1xx = I1Uxx - I1Zxx; PRECISION I1xy = I1Uxy - I1Zxy; PRECISION I1xn = I1Uxn - I1Zxn; PRECISION I1yy = I1Uyy - I1Zyy; PRECISION I1yn = I1Uyn - I1Zyn; PRECISION I1nn = I1Unn - I1Znn; // I2 PRECISION I2tt = thetaT * pitt; PRECISION I2tx = thetaT * pitx; PRECISION I2ty = thetaT * pity; PRECISION I2tn = thetaT * pitn; PRECISION I2xx = thetaT * pixx; PRECISION I2xy = thetaT * pixy; PRECISION I2xn = thetaT * pixn; PRECISION I2yy = thetaT * piyy; PRECISION I2yn = thetaT * piyn; PRECISION I2nn = thetaT * pinn; // I4 ///* PRECISION ux2 = ux * ux; PRECISION uy2 = uy * uy; PRECISION ps = pitt * sttT - 2 * pitx * stxT - 2 * pity * styT + pixx * sxxT + 2 * pixy * sxyT + piyy * syyT - 2 * pitn * stnT * t2 + 2 * pixn * sxnT * t2 + 2 * piyn * synT * t2 + pinn * snnT * t2 * t2; PRECISION ps2 = ps / 2; PRECISION I4tt = (pitt * sttT - pitx * stxT - pity * styT - t2 * pitn * stnT) - (1 - ut2+z02) * ps2; PRECISION I4tx = (pitt * stxT + pitx * sttT) / 2 - (pitx * sxxT + pixx * stxT) / 2 - (pity * sxyT + pixy * styT) / 2 - t2 * (pitn * sxnT + pixn * stnT) / 2 + (ut * ux) * ps2; PRECISION I4ty = (pitt * styT + pity * sttT) / 2 - (pitx * sxyT + pixy * stxT) / 2 - (pity * syyT + piyy * styT) / 2 - t2 * (pitn * synT + piyn * stnT) / 2 + (ut * uy) * ps2; PRECISION I4tn = (pitt * stnT + pitn * sttT) / 2 - (pitx * sxnT + pixn * stxT) / 2 - (pity * synT + piyn * styT) / 2 - t2 * (pitn * snnT + pinn * stnT) / 2 + (ut * un-z0z3) * ps2; PRECISION I4xx = (pitx * stxT - pixx * sxxT - pixy * sxyT - t2 * pixn * sxnT) + (1 + ux2) * ps2; PRECISION I4xy = (pitx * styT + pity * stxT) / 2 - (pixx * sxyT + pixy * sxxT) / 2 - (pixy * syyT + piyy * sxyT) / 2 - t2 * (pixn * synT + piyn * sxnT) / 2 + (ux * uy) * ps2; PRECISION I4xn = (pitx * stnT + pitn * stxT) / 2 - (pixx * sxnT + pixn * sxxT) / 2 - (pixy * synT + piyn * sxyT) / 2 - t2 * (pixn * snnT + pinn * sxnT) / 2 + (ux * un) * ps2; PRECISION I4yy = (pity * styT - pixy * sxyT - piyy * syyT - t2 * piyn * synT) + (1 + uy2) * ps2; PRECISION I4yn = (pity * stnT + pitn * styT) / 2 - (pixy * sxnT + pixn * sxyT) / 2 - (piyy * synT + piyn * syyT) / 2 - t2 * (piyn * snnT + pinn * synT) / 2 + (uy * un) * ps2; PRECISION I4nn = (pitn * stnT - pixn * sxnT - piyn * synT - t2 * pinn * snnT) + (1 / t2 + un2-z32) * ps2; //*/ /* PRECISION I4tt = 0; PRECISION I4tx = 0; PRECISION I4ty = 0; PRECISION I4tn = 0; PRECISION I4xx = 0; PRECISION I4xy = 0; PRECISION I4xn = 0; PRECISION I4yy = 0; PRECISION I4yn = 0; PRECISION I4nn = 0; //*/ // I5 PRECISION I5tt = zDzu * pitt; PRECISION I5tx = zDzu * pitx; PRECISION I5ty = zDzu * pity; PRECISION I5tn = zDzu * pitn; PRECISION I5xx = zDzu * pixx; PRECISION I5xy = zDzu * pixy; PRECISION I5xn = zDzu * pixn; PRECISION I5yy = zDzu * piyy; PRECISION I5yn = zDzu * piyn; PRECISION I5nn = zDzu * pinn; // I6 double L = z0*WtTz - t2*z3*WnTz; double WB = WtTz * B0 - WxTz * B1 - WyTz * B2 - t2 * WnTz * B3; // I6S double I6tt_S = ((WtTz*B0 + WtTz*B0) + (WtTz*z0 + z0*WtTz)*A + (z0*B0 + z0*B0)*L + 2*z0*z0*L*A)/2 - Xitt*(WB + L*A)/2; double I6tx_S = ((WtTz*B1 + WxTz*B0) + (WtTz*z1 + z0*WxTz)*A + (z0*B1 + z1*B0)*L + 2*z0*z1*L*A)/2 - Xitx*(WB + L*A)/2; double I6ty_S = ((WtTz*B2 + WyTz*B0) + (WtTz*z2 + z0*WyTz)*A + (z0*B2 + z2*B0)*L + 2*z0*z2*L*A)/2 - Xity*(WB + L*A)/2; double I6tn_S = ((WtTz*B3 + WnTz*B0) + (WtTz*z3 + z0*WnTz)*A + (z0*B3 + z3*B0)*L + 2*z0*z3*L*A)/2 - Xitn*(WB + L*A)/2; double I6xx_S = ((WxTz*B1 + WxTz*B1) + (WxTz*z1 + z1*WxTz)*A + (z1*B1 + z1*B1)*L + 2*z1*z1*L*A)/2 - Xixx*(WB + L*A)/2; double I6xy_S = ((WxTz*B2 + WyTz*B1) + (WxTz*z2 + z1*WyTz)*A + (z2*B1 + z1*B2)*L + 2*z1*z2*L*A)/2 - Xixy*(WB + L*A)/2; double I6xn_S = ((WxTz*B3 + WnTz*B1) + (WxTz*z3 + z1*WnTz)*A + (z1*B3 + z3*B1)*L + 2*z1*z3*L*A)/2 - Xixn*(WB + L*A)/2; double I6yy_S = ((WyTz*B2 + WyTz*B2) + (WyTz*z2 + z2*WyTz)*A + (z2*B2 + z2*B2)*L + 2*z2*z2*L*A)/2 - Xiyy*(WB + L*A)/2; double I6yn_S = ((WyTz*B3 + WnTz*B2) + (WyTz*z3 + z2*WnTz)*A + (z2*B3 + z3*B2)*L + 2*z2*z3*L*A)/2 - Xiyn*(WB + L*A)/2; double I6nn_S = ((WnTz*B3 + WnTz*B3) + (WnTz*z3 + z3*WnTz)*A + (z3*B3 + z3*B3)*L + 2*z3*z3*L*A)/2 - Xinn*(WB + L*A)/2; // I6W double I6tt_W = ((WtTz*Bw0 + WtTz*Bw0) + (z0*Bw0 + z0*Bw0)*L)/2 - Xitt*(WB)/2; double I6tx_W = ((WtTz*Bw1 + WxTz*Bw0) + (z0*Bw1 + z1*Bw0)*L)/2 - Xitx*(WB)/2; double I6ty_W = ((WtTz*Bw2 + WyTz*Bw0) + (z0*Bw2 + z2*Bw0)*L)/2 - Xity*(WB)/2; double I6tn_W = ((WtTz*Bw3 + WnTz*Bw0) + (z0*Bw3 + z3*Bw0)*L)/2 - Xitn*(WB)/2; double I6xx_W = ((WxTz*Bw1 + WxTz*Bw1) + (z1*Bw1 + z1*Bw1)*L)/2 - Xixx*(WB)/2; double I6xy_W = ((WxTz*Bw2 + WyTz*Bw1) + (z2*Bw1 + z1*Bw2)*L)/2 - Xixy*(WB)/2; double I6xn_W = ((WxTz*Bw3 + WnTz*Bw1) + (z1*Bw3 + z3*Bw1)*L)/2 - Xixn*(WB)/2; double I6yy_W = ((WyTz*Bw2 + WyTz*Bw2) + (z2*Bw2 + z2*Bw2)*L)/2 - Xiyy*(WB)/2; double I6yn_W = ((WyTz*Bw3 + WnTz*Bw2) + (z2*Bw3 + z3*Bw2)*L)/2 - Xiyn*(WB)/2; double I6nn_W = ((WnTz*Bw3 + WnTz*Bw3) + (z3*Bw3 + z3*Bw3)*L)/2 - Xinn*(WB)/2; // I6 double I6tt = -I6tt_S + I6tt_W; double I6tx = -I6tx_S + I6tx_W; double I6ty = -I6ty_S + I6ty_W; double I6tn = -I6tn_S + I6tn_W; double I6xx = -I6xx_S + I6xx_W; double I6xy = -I6xy_S + I6xy_W; double I6xn = -I6xn_S + I6xn_W; double I6yy = -I6yy_S + I6yy_W; double I6yn = -I6yn_S + I6yn_W; double I6nn = -I6nn_S + I6nn_W; /* I6tt = 0; I6tx = 0; I6ty = 0; I6tn = 0; I6xx = 0; I6xy = 0; I6xn = 0; I6yy = 0; I6yn = 0; I6nn = 0; //*/ // I7 double I7tt = I6tt_S + I6tt_W; double I7tx = I6tx_S + I6tx_W; double I7ty = I6ty_S + I6ty_W; double I7tn = I6tn_S + I6tn_W; double I7xx = I6xx_S + I6xx_W; double I7xy = I6xy_S + I6xy_W; double I7xn = I6xn_S + I6xn_W; double I7yy = I6yy_S + I6yy_W; double I7yn = I6yn_S + I6yn_W; double I7nn = I6nn_S + I6nn_W; /* I7tt = 0; I7tx = 0; I7ty = 0; I7tn = 0; I7xx = 0; I7xy = 0; I7xn = 0; I7yy = 0; I7yn = 0; I7nn = 0; //*/ PRECISION Itt = I1tt - delta_pipi * I2tt + tau_pipi * I4tt - lambda_pipi * I5tt + lambda_piWu * I6tt - lambda_piWT * I7tt - lambda_piPi * Pi * sttT; PRECISION Itx = I1tx - delta_pipi * I2tx + tau_pipi * I4tx - lambda_pipi * I5tx + lambda_piWu * I6tx - lambda_piWT * I7tx - lambda_piPi * Pi * sttT; PRECISION Ity = I1ty - delta_pipi * I2ty + tau_pipi * I4ty - lambda_pipi * I5ty + lambda_piWu * I6ty - lambda_piWT * I7ty - lambda_piPi * Pi * sttT; PRECISION Itn = I1tn - delta_pipi * I2tn + tau_pipi * I4tn - lambda_pipi * I5tn + lambda_piWu * I6tn - lambda_piWT * I7tn - lambda_piPi * Pi * sttT; PRECISION Ixx = I1xx - delta_pipi * I2xx + tau_pipi * I4xx - lambda_pipi * I5xx + lambda_piWu * I6xx - lambda_piWT * I7xx - lambda_piPi * Pi * sttT; PRECISION Ixy = I1xy - delta_pipi * I2xy + tau_pipi * I4xy - lambda_pipi * I5xy + lambda_piWu * I6xy - lambda_piWT * I7xy - lambda_piPi * Pi * sttT; PRECISION Ixn = I1xn - delta_pipi * I2xn + tau_pipi * I4xn - lambda_pipi * I5xn + lambda_piWu * I6xn - lambda_piWT * I7xn - lambda_piPi * Pi * sttT; PRECISION Iyy = I1yy - delta_pipi * I2yy + tau_pipi * I4yy - lambda_pipi * I5yy + lambda_piWu * I6yy - lambda_piWT * I7yy - lambda_piPi * Pi * sttT; PRECISION Iyn = I1yn - delta_pipi * I2yn + tau_pipi * I4yn - lambda_pipi * I5yn + lambda_piWu * I6yn - lambda_piWT * I7yn - lambda_piPi * Pi * sttT; PRECISION Inn = I1nn - delta_pipi * I2nn + tau_pipi * I4nn - lambda_pipi * I5nn + lambda_piWu * I6nn - lambda_piWT * I7nn - lambda_piPi * Pi * sttT; PRECISION dpitt = 2 * etaBar_TC * sttT - pitt * taupiInv - Itt - 2 * un * t * pitn; PRECISION dpitx = 2 * etaBar_TC * stxT - pitx * taupiInv - Itx - un * t * pixn; PRECISION dpity = 2 * etaBar_TC * styT - pity * taupiInv - Ity - un * t * piyn; PRECISION dpitn = 2 * etaBar_TC * stnT - pitn * taupiInv - Itn - un * t * pinn - (ut * pitn + un * pitt) / t; PRECISION dpixx = 2 * etaBar_TC * sxxT - pixx * taupiInv - Ixx; PRECISION dpixy = 2 * etaBar_TC * sxyT - pixy * taupiInv - Ixy; PRECISION dpixn = 2 * etaBar_TC * sxnT - pixn * taupiInv - Ixn - (ut * pixn + un * pitx) / t; PRECISION dpiyy = 2 * etaBar_TC * syyT - piyy * taupiInv - Iyy; PRECISION dpiyn = 2 * etaBar_TC * synT - piyn * taupiInv - Iyn - (ut * piyn + un * pity) / t; PRECISION dpinn = 2 * etaBar_TC * snnT - pinn * taupiInv - Inn - 2 * (ut * pinn + un * pitn) / t; S[5] = dpitt / ut + pitt * dkvk; S[6] = dpitx / ut + pitx * dkvk; S[7] = dpity / ut + pity * dkvk; S[8] = dpitn / ut + pitn * dkvk; S[9] = dpixx / ut + pixx * dkvk; S[10] = dpixy / ut + pixy * dkvk; S[11] = dpixn / ut + pixn * dkvk; S[12] = dpiyy / ut + piyy * dkvk; S[13] = dpiyn / ut + piyn * dkvk; S[14] = dpinn / ut + pinn * dkvk; #endif /************************************************************************************\ * W^{\mu}_{\perp z} source terms /************************************************************************************/ #ifdef W_TZ_MU double etaWu = zeta_zT/2.; double etaWT = ((Rtilde+1)*e-2*pl)/4; // I1 double WDU = WtTz*Dut + WxTz*Dux + WyTz*Duy + WnTz*Dun; double I1t = ut*WDU + (pitt-WtTz*z0-1.5*Pi*Xitt)*Dz0 + (pitn-WnTz*z0-1.5*Pi*Xitn)*Dz3; double I1x = ux*WDU + (pitx-1.5*Pi*Xitx)*Dz0 + (pixn-1.5*Pi*Xixn)*Dz3; double I1y = uy*WDU + (pity-1.5*Pi*Xity)*Dz0 + (piyn-1.5*Pi*Xiyn)*Dz3; double I1n = un*WDU + (pitn-WtTz*z3-1.5*Pi*Xitn)*Dz0 + (pinn-WnTz*z3-1.5*Pi*Xinn)*Dz3; // I2 double I2t = WtTz*thetaT; double I2x = WxTz*thetaT; double I2y = WyTz*thetaT; double I2n = WnTz*thetaT; // I3 double I3t = WtTz * zDzu; double I3x = WxTz * zDzu; double I3y = WyTz * zDzu; double I3n = WnTz * zDzu; // I4 double I4t = WtTz * sttT - WxTz * stxT - WyTz * styT - t2 * WnTz * stnT; double I4x = WtTz * stxT - WxTz * sxxT - WyTz * sxyT - t2 * WnTz * sxnT; double I4y = WtTz * styT - WxTz * sxyT - WyTz * syyT - t2 * WnTz * synT; double I4n = WtTz * stnT - WxTz * sxnT - WyTz * synT - t2 * WnTz * snnT; // I5 double I5t = 0; double I5x = 0; double I5y = 0; double I5n = 0; // I6 double BB0 = Bw0-B0; double BB1 = Bw1-B1; double BB2 = Bw2-B2; double BB3 = Bw3-B3; double I6t = pitt*BB0 - pitx*BB1 - pity*BB2 - t2*pitn*BB3; double I6x = pitx*BB0 - pixx*BB1 - pixy*BB2 - t2*pixn*BB3; double I6y = pity*BB0 - pixy*BB1 - piyy*BB2 - t2*piyn*BB3; double I6n = pitn*BB0 - pixn*BB1 - piyn*BB2 - t2*pinn*BB3; // I7 double St = B0 + z0*A + Bw0; double Sx = B1 + Bw1; double Sy = B2 + Bw2; double Sn = B3 + z3*A + Bw3; double I7t = pitt * St - pitx * Sx - pity * Sy - t2 * pitn * Sn; double I7x = pitx * St - pixx * Sx - pixy * Sy - t2 * pixn * Sn; double I7y = pity * St - pixy * Sx - piyy * Sy - t2 * piyn * Sn; double I7n = pitn * St - pixn * Sx - piyn * Sy - t2 * pinn * Sn; // J1 double J1t = -B0-z0*A+Bw0; double J1x = -B1+Bw1; double J1y = -B2+Bw2; double J1n = -B3-z3*A+Bw3; // J2 double J2t = B0+z0*A+Bw0; double J2x = B1+Bw1; double J2y = B2+Bw2; double J2n = B3+z3*A+Bw3; double Jt = 2*(etaWu * J1t - etaWT * J2t); double Jx = 2*(etaWu * J1x - etaWT * J2x); double Jy = 2*(etaWu * J1y - etaWT * J2y); double Jn = 2*(etaWu * J1n - etaWT * J2n); // I double IWt = I1t - delta_WW * I2t + lambda_WWu * I3t - lambda_WWT * I4t - I5t - lambda_Wpiu * I6t + lambda_WpiT * I7t; double IWx = I1x - delta_WW * I2x + lambda_WWu * I3x - lambda_WWT * I4x - I5x - lambda_Wpiu * I6x + lambda_WpiT * I7x; double IWy = I1y - delta_WW * I2y + lambda_WWu * I3y - lambda_WWT * I4y - I5y - lambda_Wpiu * I6y + lambda_WpiT * I7y; double IWn = I1n - delta_WW * I2n + lambda_WWu * I3n - lambda_WWT * I4n - I5n - lambda_Wpiu * I6n + lambda_WpiT * I7n; // G^{\mu}_{W} -- Christofel symbols from covariant derivative double GWt = t*un*WnTz; double GWn = (ut*WnTz+un*WtTz)/t; PRECISION dWtTz = Jt - WtTz*taupiInv - IWt - GWt; PRECISION dWxTz = Jx - WxTz*taupiInv - IWx; PRECISION dWyTz = Jy - WyTz*taupiInv - IWy; PRECISION dWnTz = Jn - WnTz*taupiInv - IWn - GWn; S[15] = dWtTz / ut + WtTz * dkvk; S[16] = dWxTz / ut + WxTz * dkvk; S[17] = dWyTz / ut + WyTz * dkvk; S[18] = dWnTz / ut + WnTz * dkvk; #endif /************************************************************************************\ * \Pi source terms /************************************************************************************/ #ifdef PI PRECISION b = 1.0/3.0 - cs2; PRECISION b2 = b*b; PRECISION zetabar = bulkViscosityToEntropyDensity(T); PRECISION tauPiInv = 15*b2*T/zetabar; double zeta_z = (Rhat-Rbar0)*(e-3*p)/3; double zeta_T = -(Rbar0+Rhat)*(e-3*p)/6; // PRECISION dPi = -((1-Rbar0)*(e-3*p)/3+Pi)*tauPiInv - zeta_z*zDzu -zeta_T*thetaT; PRECISION dPi = -((1-Rbar0)*(e-3*p)/3+Pi)*tauPiInv - zeta_z*zDzu -zeta_T*thetaT - beta_PiPi * Pi * zDzu - delta_PiPi * Pi * thetaT + lambda_Pipi * ps; S[NUMBER_CONSERVED_VARIABLES-1] = dPi / ut + Pi * dkvk; #endif //added by DEREK above /* //========================================================= // T^{\mu\nu} source terms //========================================================= PRECISION tnn = Tnn(e, p + Pi, un, pinn, t); PRECISION vx = ux / ut; PRECISION vy = uy / ut; PRECISION vn = un / ut; PRECISION dxvx = (dxux - vx * dxut) / ut; PRECISION dyvy = (dyuy - vy * dyut) / ut; PRECISION dnvn = (dnun - vn * dnut) / ut; PRECISION dkvk = dxvx + dyvy + dnvn; S[0] = -(ttt / t + t * tnn) + dkvk * (pitt - p - Pi) - vx * dxp - vy * dyp - vn * dnp; S[1] = -ttx / t - dxp + dkvk * pitx; S[2] = -tty / t - dyp + dkvk * pity; S[3] = -3 * ttn / t - dnp / powf(t, 2) + dkvk * pitn; #ifdef USE_CARTESIAN_COORDINATES S[0] = dkvk*(pitt-p-Pi) - vx*dxp - vy*dyp - vn*dnp; S[1] = -dxp + dkvk*pitx; S[2] = -dyp + dkvk*pity; S[3] = -dnp + dkvk*pitn; #endif //========================================================= // \pi^{\mu\nu} source terms //========================================================= #ifndef IDEAL PRECISION pimunuRHS[NUMBER_DISSIPATIVE_CURRENTS]; setPimunuSourceTerms(pimunuRHS, t, e, p, ut, ux, uy, un, utp, uxp, uyp, unp, pitt, pitx, pity, pitn, pixx, pixy, pixn, piyy, piyn, pinn, Pi, dxut, dyut, dnut, dxux, dyux, dnux, dxuy, dyuy, dnuy, dxun, dyun, dnun, dkvk); for (unsigned int n = 0; n < NUMBER_DISSIPATIVE_CURRENTS; ++n) S[n + 4] = pimunuRHS[n]; #endif */ }
f1c986a30fa4d52b453f12c5b47de931d4f9c79e.hip
// !!! This is a file automatically generated by hipify!!! // Copyright 2013 Google Inc. 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include <pthread.h> #define MAX_STRING 100 #define EXP_TABLE_SIZE 1000 #define MAX_EXP 6 #define MAX_SENTENCE_LENGTH 1000 #define MAX_CODE_LENGTH 40 #define checkCUDAError(err) {\ hipError_t cet = err;\ if(hipSuccess != cet){\ printf("%s %d : %s\n", __FILE__, __LINE__, hipGetErrorString(cet));\ exit(0);\ }\ } const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary typedef float real; // Precision of float numbers struct vocab_word { long long cn; int *point; char *word, *code, codelen; }; #include "cbow.cu" int *vocab_codelen; int *d_vocab_codelen; char *vocab_code; char *d_vocab_code; int *vocab_point; int *d_vocab_point; char train_file[MAX_STRING], output_file[MAX_STRING]; char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING]; struct vocab_word *vocab; int binary = 0, cbow = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1; int *vocab_hash; long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100; long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0; real alpha = 0.025, starting_alpha, sample = 1e-3; real *syn0, *syn1, *syn1neg, *expTable; real *d_syn0, *d_syn1, *d_syn1neg, *d_expTable; int *d_table; clock_t start; int hs = 0, negative = 5; const int table_size = 1e8; int *table; void InitUnigramTable() { int a, i; long long train_words_pow = 0; real d1, power = 0.75; table = (int *)malloc(table_size * sizeof(int)); checkCUDAError(hipMalloc((void**)&d_table, table_size*sizeof(int))); for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power); i = 0; d1 = pow(vocab[i].cn, power) / (real)train_words_pow; for (a = 0; a < table_size; a++) { table[a] = i; if (a / (real)table_size > d1) { i++; d1 += pow(vocab[i].cn, power) / (real)train_words_pow; } if (i >= vocab_size) i = vocab_size - 1; } checkCUDAError(hipMemcpy(d_table, table, table_size*sizeof(int), hipMemcpyHostToDevice)); } // Reads a single word from a file, assuming space + tab + EOL to be word boundaries void ReadWord(char *word, FILE *fin) { int a = 0, ch; while (!feof(fin)) { ch = fgetc(fin); if (ch == 13) continue; if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { if (a > 0) { if (ch == '\n') ungetc(ch, fin); break; } if (ch == '\n') { strcpy(word, (char *)"</s>"); return; } else continue; } word[a] = ch; a++; if (a >= MAX_STRING - 1) a--; // Truncate too long words } word[a] = 0; } // Returns hash value of a word int GetWordHash(char *word) { unsigned long long a, hash = 0; for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; hash = hash % vocab_hash_size; return hash; } // Returns position of a word in the vocabulary; if the word is not found, returns -1 int SearchVocab(char *word) { unsigned int hash = GetWordHash(word); while (1) { if (vocab_hash[hash] == -1) return -1; if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; hash = (hash + 1) % vocab_hash_size; } return -1; } // Reads a word and returns its index in the vocabulary int ReadWordIndex(FILE *fin) { char word[MAX_STRING]; ReadWord(word, fin); if (feof(fin)) return -1; return SearchVocab(word); } // Adds a word to the vocabulary int AddWordToVocab(char *word) { unsigned int hash, length = strlen(word) + 1; if (length > MAX_STRING) length = MAX_STRING; vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); strcpy(vocab[vocab_size].word, word); vocab[vocab_size].cn = 0; vocab_size++; // Reallocate memory if needed if (vocab_size + 2 >= vocab_max_size) { vocab_max_size += 1000; vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); } hash = GetWordHash(word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = vocab_size - 1; return vocab_size - 1; } // Used later for sorting by word counts int VocabCompare(const void *a, const void *b) { return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; } // Sorts the vocabulary by frequency using word counts void SortVocab() { int a, size; unsigned int hash; // Sort the vocabulary and keep </s> at the first position qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; size = vocab_size; train_words = 0; for (a = 0; a < size; a++) { // Words occuring less than min_count times will be discarded from the vocab if (vocab[a].cn < min_count) { vocab_size--; free(vocab[vocab_size].word); } else { // Hash will be re-computed, as after the sorting it is not actual hash=GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; train_words += vocab[a].cn; } } vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); // Allocate memory for the binary tree construction for (a = 0; a < vocab_size; a++) { vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char)); vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int)); } } // Reduces the vocabulary by removing infrequent tokens void ReduceVocab() { int a, b = 0; unsigned int hash; for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { vocab[b].cn = vocab[a].cn; vocab[b].word = vocab[a].word; b++; } else free(vocab[a].word); vocab_size = b; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; for (a = 0; a < vocab_size; a++) { // Hash will be re-computed, as it is not actual hash = GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; } fflush(stdout); min_reduce++; } // Create binary Huffman tree using the word counts // Frequent words will have short uniqe binary codes void CreateBinaryTree() { long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH]; char code[MAX_CODE_LENGTH]; long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15; pos1 = vocab_size - 1; pos2 = vocab_size; // Following algorithm constructs the Huffman tree by adding one node at a time for (a = 0; a < vocab_size - 1; a++) { // First, find two smallest nodes 'min1, min2' if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min1i = pos1; pos1--; } else { min1i = pos2; pos2++; } } else { min1i = pos2; pos2++; } if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min2i = pos1; pos1--; } else { min2i = pos2; pos2++; } } else { min2i = pos2; pos2++; } count[vocab_size + a] = count[min1i] + count[min2i]; parent_node[min1i] = vocab_size + a; parent_node[min2i] = vocab_size + a; binary[min2i] = 1; } // Now assign binary code to each vocabulary word for (a = 0; a < vocab_size; a++) { b = a; i = 0; while (1) { code[i] = binary[b]; point[i] = b; i++; b = parent_node[b]; if (b == vocab_size * 2 - 2) break; } vocab[a].codelen = i; vocab[a].point[0] = vocab_size - 2; for (b = 0; b < i; b++) { vocab[a].code[i - b - 1] = code[b]; vocab[a].point[i - b] = point[b] - vocab_size; } } free(count); free(binary); free(parent_node); } void LearnVocabFromTrainFile() { char word[MAX_STRING]; FILE *fin; long long a, i; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } vocab_size = 0; AddWordToVocab((char *)"</s>"); while (1) { ReadWord(word, fin); if (feof(fin)) break; train_words++; if ((debug_mode > 1) && (train_words % 100000 == 0)) { printf("%lldK%c", train_words / 1000, 13); fflush(stdout); } i = SearchVocab(word); if (i == -1) { a = AddWordToVocab(word); vocab[a].cn = 1; } else vocab[i].cn++; if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); } SortVocab(); if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } file_size = ftell(fin); fclose(fin); } void SaveVocab() { long long i; FILE *fo = fopen(save_vocab_file, "wb"); for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn); fclose(fo); } void ReadVocab() { long long a, i = 0; char c; char word[MAX_STRING]; FILE *fin = fopen(read_vocab_file, "rb"); if (fin == NULL) { printf("Vocabulary file not found\n"); exit(1); } for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; vocab_size = 0; while (1) { ReadWord(word, fin); if (feof(fin)) break; a = AddWordToVocab(word); fscanf(fin, "%lld%c", &vocab[a].cn, &c); i++; } SortVocab(); if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } fseek(fin, 0, SEEK_END); file_size = ftell(fin); fclose(fin); } void InitNet() { long long a, b; unsigned long long next_random = 1; a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);} checkCUDAError(hipMalloc((void**)&d_syn0, sizeof(real)*vocab_size*layer1_size)); if (hs) { a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);} checkCUDAError(hipMalloc((void**)&d_syn1, sizeof(real)*vocab_size*layer1_size)); checkCUDAError(hipMemset(d_syn1, 0, sizeof(real)*vocab_size*layer1_size)); } if (negative>0) { a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);} checkCUDAError(hipMalloc((void**)&d_syn1neg, sizeof(real)*vocab_size*layer1_size)); checkCUDAError(hipMemset(d_syn1neg, 0, sizeof(real)*vocab_size*layer1_size)); } for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) { next_random = next_random * (unsigned long long)25214903917 + 11; syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; } checkCUDAError(hipMemcpy(d_syn0, syn0, sizeof(real)*vocab_size*layer1_size, hipMemcpyHostToDevice)); CreateBinaryTree(); } void *TrainModelThread(void *id) { long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0; long long word_count = 0, last_word_count = 0; int *sen, *d_sen; checkCUDAError(hipHostMalloc((void**)&sen,(MAX_SENTENCE_LENGTH + 1)*sizeof(int))); checkCUDAError(hipMalloc((void**)&d_sen, (MAX_SENTENCE_LENGTH+1)*sizeof(int))); long long l1, l2, c, target, label, local_iter = iter; srand((long long)id); real f, g; clock_t now; FILE *fi = fopen(train_file, "rb"); fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); int blockSize = 256; int gridSize = (MAX_SENTENCE_LENGTH+blockSize)/blockSize; while (1) { if (word_count - last_word_count > 10000) { word_count_actual += word_count - last_word_count; last_word_count = word_count; if ((debug_mode > 1)) { now=clock(); printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha, word_count_actual / (real)(iter * train_words + 1) * 100, word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000)); fflush(stdout); } alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1)); if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001; } sentence_length = 0; while (1) { word = ReadWordIndex(fi); if (feof(fi)) break; if (word == -1) continue; word_count++; if (word == 0) break; // The subsampling randomly discards frequent words while keeping the ranking same if (sample > 0) { real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn; int next_random = rand(); if (ran < (next_random & 0xFFFF) / (real)65536) continue; } sen[sentence_length] = word; sentence_length++; if (sentence_length >= MAX_SENTENCE_LENGTH) break; } if (feof(fi) || (word_count > train_words / num_threads)) { word_count_actual += word_count - last_word_count; local_iter--; if (local_iter == 0) break; word_count = 0; last_word_count = 0; sentence_length = 0; fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); continue; } if (cbow) { //train the cbow architecture // in -> hidden checkCUDAError(hipMemcpy(d_sen, sen, sentence_length*sizeof(int), hipMemcpyHostToDevice)); cbow_cuda(window, negative, alpha, sentence_length, d_sen, layer1_size, d_syn0, hs, d_syn1, d_expTable, d_vocab_codelen, d_vocab_code, d_vocab_point, d_table, table_size, vocab_size, d_syn1neg); } else { //train skip-gram real *neu1 = (real *)calloc(layer1_size, sizeof(real)); real *neu1e = (real *)calloc(layer1_size, sizeof(real)); for(int sentence_position = 0; sentence_position < sentence_length; sentence_position++){ word = sen[sentence_position]; if (word == -1) continue; int next_random = rand(); b = next_random % window; for (c = 0; c < layer1_size; c++) neu1[c] = 0; for (c = 0; c < layer1_size; c++) neu1e[c] = 0; //skip_gram(); } free(neu1); free(neu1e); } } checkCUDAError(hipDeviceSynchronize()); checkCUDAError(hipMemcpy(syn0, d_syn0, vocab_size*layer1_size*sizeof(real), hipMemcpyDeviceToHost)); fclose(fi); pthread_exit(NULL); } void TrainModel() { long a, b, c, d; FILE *fo; pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); printf("Starting training using file %s\n", train_file); starting_alpha = alpha; if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile(); if (save_vocab_file[0] != 0) SaveVocab(); if (output_file[0] == 0) return; InitNet(); if (negative > 0) InitUnigramTable(); start = clock(); //rogy printf("vocab size = %d\n", vocab_size); vocab_codelen = (int*)malloc((vocab_size + 1)*sizeof(int)); checkCUDAError(hipMalloc((void**)&d_vocab_codelen, (vocab_size+1)*sizeof(int))); assert(NULL != vocab_codelen); vocab_codelen[0] = 0; for(int i = 1; i < vocab_size+1; i++){ vocab_codelen[i] = vocab_codelen[i-1] + vocab[i-1].codelen; // printf("codelen of %d is %d\n", i, vocab_codelen[i]); } checkCUDAError(hipMemcpy(d_vocab_codelen, vocab_codelen, (vocab_size+1)*sizeof(int), hipMemcpyHostToDevice)); vocab_code = (char*)malloc(vocab_codelen[vocab_size]*sizeof(char)); assert(NULL != vocab_code); checkCUDAError(hipMalloc((void**)&d_vocab_code, vocab_codelen[vocab_size]*sizeof(char))); vocab_point = (int*)malloc(vocab_codelen[vocab_size]*sizeof(int)); assert(NULL != vocab_code); checkCUDAError(hipMalloc((void**)&d_vocab_point, vocab_codelen[vocab_size]*sizeof(int))); for(int i = 0; i < vocab_size; i++){ for(int j =0; j < vocab[i].codelen; j++){ vocab_code[vocab_codelen[i] + j] = vocab[i].code[j]; vocab_point[vocab_codelen[i] + j] = vocab[i].point[j]; } } checkCUDAError(hipMemcpy(d_vocab_code, vocab_code, vocab_codelen[vocab_size]*sizeof(char), hipMemcpyHostToDevice)); checkCUDAError(hipMemcpy(d_vocab_point, vocab_point, vocab_codelen[vocab_size]*sizeof(int), hipMemcpyHostToDevice)); for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL); //rogy free(vocab_codelen); free(vocab_code); free(vocab_point); fo = fopen(output_file, "wb"); if (classes == 0) { // Save the word vectors fprintf(fo, "%lld %lld\n", vocab_size, layer1_size); for (a = 0; a < vocab_size; a++) { fprintf(fo, "%s ", vocab[a].word); if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo); else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]); fprintf(fo, "\n"); } } else { // Run K-means on the word vectors int clcn = classes, iter = 10, closeid; int *centcn = (int *)malloc(classes * sizeof(int)); int *cl = (int *)calloc(vocab_size, sizeof(int)); real closev, x; real *cent = (real *)calloc(classes * layer1_size, sizeof(real)); for (a = 0; a < vocab_size; a++) cl[a] = a % clcn; for (a = 0; a < iter; a++) { for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0; for (b = 0; b < clcn; b++) centcn[b] = 1; for (c = 0; c < vocab_size; c++) { for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d]; centcn[cl[c]]++; } for (b = 0; b < clcn; b++) { closev = 0; for (c = 0; c < layer1_size; c++) { cent[layer1_size * b + c] /= centcn[b]; closev += cent[layer1_size * b + c] * cent[layer1_size * b + c]; } closev = sqrt(closev); for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev; } for (c = 0; c < vocab_size; c++) { closev = -10; closeid = 0; for (d = 0; d < clcn; d++) { x = 0; for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b]; if (x > closev) { closev = x; closeid = d; } } cl[c] = closeid; } } // Save the K-means classes for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]); free(centcn); free(cent); free(cl); } fclose(fo); } int ArgPos(char *str, int argc, char **argv) { int a; for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } return -1; } int main(int argc, char **argv) { int i; if (argc == 1) { printf("WORD VECTOR estimation toolkit v 0.1c\n\n"); printf("Options:\n"); printf("Parameters for training:\n"); printf("\t-train <file>\n"); printf("\t\tUse text data from <file> to train the model\n"); printf("\t-output <file>\n"); printf("\t\tUse <file> to save the resulting word vectors / word clusters\n"); printf("\t-size <int>\n"); printf("\t\tSet size of word vectors; default is 100\n"); printf("\t-window <int>\n"); printf("\t\tSet max skip length between words; default is 5\n"); printf("\t-sample <float>\n"); printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n"); printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n"); printf("\t-hs <int>\n"); printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n"); printf("\t-negative <int>\n"); printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n"); printf("\t-threads <int>\n"); printf("\t\tUse <int> threads (default 12)\n"); printf("\t-iter <int>\n"); printf("\t\tRun more training iterations (default 5)\n"); printf("\t-min-count <int>\n"); printf("\t\tThis will discard words that appear less than <int> times; default is 5\n"); printf("\t-alpha <float>\n"); printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n"); printf("\t-classes <int>\n"); printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n"); printf("\t-debug <int>\n"); printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); printf("\t-binary <int>\n"); printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n"); printf("\t-save-vocab <file>\n"); printf("\t\tThe vocabulary will be saved to <file>\n"); printf("\t-read-vocab <file>\n"); printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n"); printf("\t-cbow <int>\n"); printf("\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n"); printf("\nExamples:\n"); printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n"); return 0; } output_file[0] = 0; save_vocab_file[0] = 0; read_vocab_file[0] = 0; if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]); if (cbow) alpha = 0.05; if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]); if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]); if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]); vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real)); for(i = 0; i < EXP_TABLE_SIZE+1; i++) { expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1) } checkCUDAError(hipMalloc((void**)&d_expTable, (EXP_TABLE_SIZE+1)*sizeof(real))); checkCUDAError(hipMemcpy(d_expTable, expTable, (EXP_TABLE_SIZE+1)*sizeof(real), hipMemcpyHostToDevice)); TrainModel(); return 0; }
f1c986a30fa4d52b453f12c5b47de931d4f9c79e.cu
// Copyright 2013 Google Inc. 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 <stdio.h> #include <stdlib.h> #include <string.h> #include <assert.h> #include <math.h> #include <pthread.h> #define MAX_STRING 100 #define EXP_TABLE_SIZE 1000 #define MAX_EXP 6 #define MAX_SENTENCE_LENGTH 1000 #define MAX_CODE_LENGTH 40 #define checkCUDAError(err) {\ cudaError_t cet = err;\ if(cudaSuccess != cet){\ printf("%s %d : %s\n", __FILE__, __LINE__, cudaGetErrorString(cet));\ exit(0);\ }\ } const int vocab_hash_size = 30000000; // Maximum 30 * 0.7 = 21M words in the vocabulary typedef float real; // Precision of float numbers struct vocab_word { long long cn; int *point; char *word, *code, codelen; }; #include "cbow.cu" int *vocab_codelen; int *d_vocab_codelen; char *vocab_code; char *d_vocab_code; int *vocab_point; int *d_vocab_point; char train_file[MAX_STRING], output_file[MAX_STRING]; char save_vocab_file[MAX_STRING], read_vocab_file[MAX_STRING]; struct vocab_word *vocab; int binary = 0, cbow = 1, debug_mode = 2, window = 5, min_count = 5, num_threads = 12, min_reduce = 1; int *vocab_hash; long long vocab_max_size = 1000, vocab_size = 0, layer1_size = 100; long long train_words = 0, word_count_actual = 0, iter = 5, file_size = 0, classes = 0; real alpha = 0.025, starting_alpha, sample = 1e-3; real *syn0, *syn1, *syn1neg, *expTable; real *d_syn0, *d_syn1, *d_syn1neg, *d_expTable; int *d_table; clock_t start; int hs = 0, negative = 5; const int table_size = 1e8; int *table; void InitUnigramTable() { int a, i; long long train_words_pow = 0; real d1, power = 0.75; table = (int *)malloc(table_size * sizeof(int)); checkCUDAError(cudaMalloc((void**)&d_table, table_size*sizeof(int))); for (a = 0; a < vocab_size; a++) train_words_pow += pow(vocab[a].cn, power); i = 0; d1 = pow(vocab[i].cn, power) / (real)train_words_pow; for (a = 0; a < table_size; a++) { table[a] = i; if (a / (real)table_size > d1) { i++; d1 += pow(vocab[i].cn, power) / (real)train_words_pow; } if (i >= vocab_size) i = vocab_size - 1; } checkCUDAError(cudaMemcpy(d_table, table, table_size*sizeof(int), cudaMemcpyHostToDevice)); } // Reads a single word from a file, assuming space + tab + EOL to be word boundaries void ReadWord(char *word, FILE *fin) { int a = 0, ch; while (!feof(fin)) { ch = fgetc(fin); if (ch == 13) continue; if ((ch == ' ') || (ch == '\t') || (ch == '\n')) { if (a > 0) { if (ch == '\n') ungetc(ch, fin); break; } if (ch == '\n') { strcpy(word, (char *)"</s>"); return; } else continue; } word[a] = ch; a++; if (a >= MAX_STRING - 1) a--; // Truncate too long words } word[a] = 0; } // Returns hash value of a word int GetWordHash(char *word) { unsigned long long a, hash = 0; for (a = 0; a < strlen(word); a++) hash = hash * 257 + word[a]; hash = hash % vocab_hash_size; return hash; } // Returns position of a word in the vocabulary; if the word is not found, returns -1 int SearchVocab(char *word) { unsigned int hash = GetWordHash(word); while (1) { if (vocab_hash[hash] == -1) return -1; if (!strcmp(word, vocab[vocab_hash[hash]].word)) return vocab_hash[hash]; hash = (hash + 1) % vocab_hash_size; } return -1; } // Reads a word and returns its index in the vocabulary int ReadWordIndex(FILE *fin) { char word[MAX_STRING]; ReadWord(word, fin); if (feof(fin)) return -1; return SearchVocab(word); } // Adds a word to the vocabulary int AddWordToVocab(char *word) { unsigned int hash, length = strlen(word) + 1; if (length > MAX_STRING) length = MAX_STRING; vocab[vocab_size].word = (char *)calloc(length, sizeof(char)); strcpy(vocab[vocab_size].word, word); vocab[vocab_size].cn = 0; vocab_size++; // Reallocate memory if needed if (vocab_size + 2 >= vocab_max_size) { vocab_max_size += 1000; vocab = (struct vocab_word *)realloc(vocab, vocab_max_size * sizeof(struct vocab_word)); } hash = GetWordHash(word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = vocab_size - 1; return vocab_size - 1; } // Used later for sorting by word counts int VocabCompare(const void *a, const void *b) { return ((struct vocab_word *)b)->cn - ((struct vocab_word *)a)->cn; } // Sorts the vocabulary by frequency using word counts void SortVocab() { int a, size; unsigned int hash; // Sort the vocabulary and keep </s> at the first position qsort(&vocab[1], vocab_size - 1, sizeof(struct vocab_word), VocabCompare); for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; size = vocab_size; train_words = 0; for (a = 0; a < size; a++) { // Words occuring less than min_count times will be discarded from the vocab if (vocab[a].cn < min_count) { vocab_size--; free(vocab[vocab_size].word); } else { // Hash will be re-computed, as after the sorting it is not actual hash=GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; train_words += vocab[a].cn; } } vocab = (struct vocab_word *)realloc(vocab, (vocab_size + 1) * sizeof(struct vocab_word)); // Allocate memory for the binary tree construction for (a = 0; a < vocab_size; a++) { vocab[a].code = (char *)calloc(MAX_CODE_LENGTH, sizeof(char)); vocab[a].point = (int *)calloc(MAX_CODE_LENGTH, sizeof(int)); } } // Reduces the vocabulary by removing infrequent tokens void ReduceVocab() { int a, b = 0; unsigned int hash; for (a = 0; a < vocab_size; a++) if (vocab[a].cn > min_reduce) { vocab[b].cn = vocab[a].cn; vocab[b].word = vocab[a].word; b++; } else free(vocab[a].word); vocab_size = b; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; for (a = 0; a < vocab_size; a++) { // Hash will be re-computed, as it is not actual hash = GetWordHash(vocab[a].word); while (vocab_hash[hash] != -1) hash = (hash + 1) % vocab_hash_size; vocab_hash[hash] = a; } fflush(stdout); min_reduce++; } // Create binary Huffman tree using the word counts // Frequent words will have short uniqe binary codes void CreateBinaryTree() { long long a, b, i, min1i, min2i, pos1, pos2, point[MAX_CODE_LENGTH]; char code[MAX_CODE_LENGTH]; long long *count = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *binary = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); long long *parent_node = (long long *)calloc(vocab_size * 2 + 1, sizeof(long long)); for (a = 0; a < vocab_size; a++) count[a] = vocab[a].cn; for (a = vocab_size; a < vocab_size * 2; a++) count[a] = 1e15; pos1 = vocab_size - 1; pos2 = vocab_size; // Following algorithm constructs the Huffman tree by adding one node at a time for (a = 0; a < vocab_size - 1; a++) { // First, find two smallest nodes 'min1, min2' if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min1i = pos1; pos1--; } else { min1i = pos2; pos2++; } } else { min1i = pos2; pos2++; } if (pos1 >= 0) { if (count[pos1] < count[pos2]) { min2i = pos1; pos1--; } else { min2i = pos2; pos2++; } } else { min2i = pos2; pos2++; } count[vocab_size + a] = count[min1i] + count[min2i]; parent_node[min1i] = vocab_size + a; parent_node[min2i] = vocab_size + a; binary[min2i] = 1; } // Now assign binary code to each vocabulary word for (a = 0; a < vocab_size; a++) { b = a; i = 0; while (1) { code[i] = binary[b]; point[i] = b; i++; b = parent_node[b]; if (b == vocab_size * 2 - 2) break; } vocab[a].codelen = i; vocab[a].point[0] = vocab_size - 2; for (b = 0; b < i; b++) { vocab[a].code[i - b - 1] = code[b]; vocab[a].point[i - b] = point[b] - vocab_size; } } free(count); free(binary); free(parent_node); } void LearnVocabFromTrainFile() { char word[MAX_STRING]; FILE *fin; long long a, i; for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } vocab_size = 0; AddWordToVocab((char *)"</s>"); while (1) { ReadWord(word, fin); if (feof(fin)) break; train_words++; if ((debug_mode > 1) && (train_words % 100000 == 0)) { printf("%lldK%c", train_words / 1000, 13); fflush(stdout); } i = SearchVocab(word); if (i == -1) { a = AddWordToVocab(word); vocab[a].cn = 1; } else vocab[i].cn++; if (vocab_size > vocab_hash_size * 0.7) ReduceVocab(); } SortVocab(); if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } file_size = ftell(fin); fclose(fin); } void SaveVocab() { long long i; FILE *fo = fopen(save_vocab_file, "wb"); for (i = 0; i < vocab_size; i++) fprintf(fo, "%s %lld\n", vocab[i].word, vocab[i].cn); fclose(fo); } void ReadVocab() { long long a, i = 0; char c; char word[MAX_STRING]; FILE *fin = fopen(read_vocab_file, "rb"); if (fin == NULL) { printf("Vocabulary file not found\n"); exit(1); } for (a = 0; a < vocab_hash_size; a++) vocab_hash[a] = -1; vocab_size = 0; while (1) { ReadWord(word, fin); if (feof(fin)) break; a = AddWordToVocab(word); fscanf(fin, "%lld%c", &vocab[a].cn, &c); i++; } SortVocab(); if (debug_mode > 0) { printf("Vocab size: %lld\n", vocab_size); printf("Words in train file: %lld\n", train_words); } fin = fopen(train_file, "rb"); if (fin == NULL) { printf("ERROR: training data file not found!\n"); exit(1); } fseek(fin, 0, SEEK_END); file_size = ftell(fin); fclose(fin); } void InitNet() { long long a, b; unsigned long long next_random = 1; a = posix_memalign((void **)&syn0, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn0 == NULL) {printf("Memory allocation failed\n"); exit(1);} checkCUDAError(cudaMalloc((void**)&d_syn0, sizeof(real)*vocab_size*layer1_size)); if (hs) { a = posix_memalign((void **)&syn1, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1 == NULL) {printf("Memory allocation failed\n"); exit(1);} checkCUDAError(cudaMalloc((void**)&d_syn1, sizeof(real)*vocab_size*layer1_size)); checkCUDAError(cudaMemset(d_syn1, 0, sizeof(real)*vocab_size*layer1_size)); } if (negative>0) { a = posix_memalign((void **)&syn1neg, 128, (long long)vocab_size * layer1_size * sizeof(real)); if (syn1neg == NULL) {printf("Memory allocation failed\n"); exit(1);} checkCUDAError(cudaMalloc((void**)&d_syn1neg, sizeof(real)*vocab_size*layer1_size)); checkCUDAError(cudaMemset(d_syn1neg, 0, sizeof(real)*vocab_size*layer1_size)); } for (a = 0; a < vocab_size; a++) for (b = 0; b < layer1_size; b++) { next_random = next_random * (unsigned long long)25214903917 + 11; syn0[a * layer1_size + b] = (((next_random & 0xFFFF) / (real)65536) - 0.5) / layer1_size; } checkCUDAError(cudaMemcpy(d_syn0, syn0, sizeof(real)*vocab_size*layer1_size, cudaMemcpyHostToDevice)); CreateBinaryTree(); } void *TrainModelThread(void *id) { long long a, b, d, cw, word, last_word, sentence_length = 0, sentence_position = 0; long long word_count = 0, last_word_count = 0; int *sen, *d_sen; checkCUDAError(cudaMallocHost((void**)&sen,(MAX_SENTENCE_LENGTH + 1)*sizeof(int))); checkCUDAError(cudaMalloc((void**)&d_sen, (MAX_SENTENCE_LENGTH+1)*sizeof(int))); long long l1, l2, c, target, label, local_iter = iter; srand((long long)id); real f, g; clock_t now; FILE *fi = fopen(train_file, "rb"); fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); int blockSize = 256; int gridSize = (MAX_SENTENCE_LENGTH+blockSize)/blockSize; while (1) { if (word_count - last_word_count > 10000) { word_count_actual += word_count - last_word_count; last_word_count = word_count; if ((debug_mode > 1)) { now=clock(); printf("%cAlpha: %f Progress: %.2f%% Words/thread/sec: %.2fk ", 13, alpha, word_count_actual / (real)(iter * train_words + 1) * 100, word_count_actual / ((real)(now - start + 1) / (real)CLOCKS_PER_SEC * 1000)); fflush(stdout); } alpha = starting_alpha * (1 - word_count_actual / (real)(iter * train_words + 1)); if (alpha < starting_alpha * 0.0001) alpha = starting_alpha * 0.0001; } sentence_length = 0; while (1) { word = ReadWordIndex(fi); if (feof(fi)) break; if (word == -1) continue; word_count++; if (word == 0) break; // The subsampling randomly discards frequent words while keeping the ranking same if (sample > 0) { real ran = (sqrt(vocab[word].cn / (sample * train_words)) + 1) * (sample * train_words) / vocab[word].cn; int next_random = rand(); if (ran < (next_random & 0xFFFF) / (real)65536) continue; } sen[sentence_length] = word; sentence_length++; if (sentence_length >= MAX_SENTENCE_LENGTH) break; } if (feof(fi) || (word_count > train_words / num_threads)) { word_count_actual += word_count - last_word_count; local_iter--; if (local_iter == 0) break; word_count = 0; last_word_count = 0; sentence_length = 0; fseek(fi, file_size / (long long)num_threads * (long long)id, SEEK_SET); continue; } if (cbow) { //train the cbow architecture // in -> hidden checkCUDAError(cudaMemcpy(d_sen, sen, sentence_length*sizeof(int), cudaMemcpyHostToDevice)); cbow_cuda(window, negative, alpha, sentence_length, d_sen, layer1_size, d_syn0, hs, d_syn1, d_expTable, d_vocab_codelen, d_vocab_code, d_vocab_point, d_table, table_size, vocab_size, d_syn1neg); } else { //train skip-gram real *neu1 = (real *)calloc(layer1_size, sizeof(real)); real *neu1e = (real *)calloc(layer1_size, sizeof(real)); for(int sentence_position = 0; sentence_position < sentence_length; sentence_position++){ word = sen[sentence_position]; if (word == -1) continue; int next_random = rand(); b = next_random % window; for (c = 0; c < layer1_size; c++) neu1[c] = 0; for (c = 0; c < layer1_size; c++) neu1e[c] = 0; //skip_gram(); } free(neu1); free(neu1e); } } checkCUDAError(cudaDeviceSynchronize()); checkCUDAError(cudaMemcpy(syn0, d_syn0, vocab_size*layer1_size*sizeof(real), cudaMemcpyDeviceToHost)); fclose(fi); pthread_exit(NULL); } void TrainModel() { long a, b, c, d; FILE *fo; pthread_t *pt = (pthread_t *)malloc(num_threads * sizeof(pthread_t)); printf("Starting training using file %s\n", train_file); starting_alpha = alpha; if (read_vocab_file[0] != 0) ReadVocab(); else LearnVocabFromTrainFile(); if (save_vocab_file[0] != 0) SaveVocab(); if (output_file[0] == 0) return; InitNet(); if (negative > 0) InitUnigramTable(); start = clock(); //rogy printf("vocab size = %d\n", vocab_size); vocab_codelen = (int*)malloc((vocab_size + 1)*sizeof(int)); checkCUDAError(cudaMalloc((void**)&d_vocab_codelen, (vocab_size+1)*sizeof(int))); assert(NULL != vocab_codelen); vocab_codelen[0] = 0; for(int i = 1; i < vocab_size+1; i++){ vocab_codelen[i] = vocab_codelen[i-1] + vocab[i-1].codelen; // printf("codelen of %d is %d\n", i, vocab_codelen[i]); } checkCUDAError(cudaMemcpy(d_vocab_codelen, vocab_codelen, (vocab_size+1)*sizeof(int), cudaMemcpyHostToDevice)); vocab_code = (char*)malloc(vocab_codelen[vocab_size]*sizeof(char)); assert(NULL != vocab_code); checkCUDAError(cudaMalloc((void**)&d_vocab_code, vocab_codelen[vocab_size]*sizeof(char))); vocab_point = (int*)malloc(vocab_codelen[vocab_size]*sizeof(int)); assert(NULL != vocab_code); checkCUDAError(cudaMalloc((void**)&d_vocab_point, vocab_codelen[vocab_size]*sizeof(int))); for(int i = 0; i < vocab_size; i++){ for(int j =0; j < vocab[i].codelen; j++){ vocab_code[vocab_codelen[i] + j] = vocab[i].code[j]; vocab_point[vocab_codelen[i] + j] = vocab[i].point[j]; } } checkCUDAError(cudaMemcpy(d_vocab_code, vocab_code, vocab_codelen[vocab_size]*sizeof(char), cudaMemcpyHostToDevice)); checkCUDAError(cudaMemcpy(d_vocab_point, vocab_point, vocab_codelen[vocab_size]*sizeof(int), cudaMemcpyHostToDevice)); for (a = 0; a < num_threads; a++) pthread_create(&pt[a], NULL, TrainModelThread, (void *)a); for (a = 0; a < num_threads; a++) pthread_join(pt[a], NULL); //rogy free(vocab_codelen); free(vocab_code); free(vocab_point); fo = fopen(output_file, "wb"); if (classes == 0) { // Save the word vectors fprintf(fo, "%lld %lld\n", vocab_size, layer1_size); for (a = 0; a < vocab_size; a++) { fprintf(fo, "%s ", vocab[a].word); if (binary) for (b = 0; b < layer1_size; b++) fwrite(&syn0[a * layer1_size + b], sizeof(real), 1, fo); else for (b = 0; b < layer1_size; b++) fprintf(fo, "%lf ", syn0[a * layer1_size + b]); fprintf(fo, "\n"); } } else { // Run K-means on the word vectors int clcn = classes, iter = 10, closeid; int *centcn = (int *)malloc(classes * sizeof(int)); int *cl = (int *)calloc(vocab_size, sizeof(int)); real closev, x; real *cent = (real *)calloc(classes * layer1_size, sizeof(real)); for (a = 0; a < vocab_size; a++) cl[a] = a % clcn; for (a = 0; a < iter; a++) { for (b = 0; b < clcn * layer1_size; b++) cent[b] = 0; for (b = 0; b < clcn; b++) centcn[b] = 1; for (c = 0; c < vocab_size; c++) { for (d = 0; d < layer1_size; d++) cent[layer1_size * cl[c] + d] += syn0[c * layer1_size + d]; centcn[cl[c]]++; } for (b = 0; b < clcn; b++) { closev = 0; for (c = 0; c < layer1_size; c++) { cent[layer1_size * b + c] /= centcn[b]; closev += cent[layer1_size * b + c] * cent[layer1_size * b + c]; } closev = sqrt(closev); for (c = 0; c < layer1_size; c++) cent[layer1_size * b + c] /= closev; } for (c = 0; c < vocab_size; c++) { closev = -10; closeid = 0; for (d = 0; d < clcn; d++) { x = 0; for (b = 0; b < layer1_size; b++) x += cent[layer1_size * d + b] * syn0[c * layer1_size + b]; if (x > closev) { closev = x; closeid = d; } } cl[c] = closeid; } } // Save the K-means classes for (a = 0; a < vocab_size; a++) fprintf(fo, "%s %d\n", vocab[a].word, cl[a]); free(centcn); free(cent); free(cl); } fclose(fo); } int ArgPos(char *str, int argc, char **argv) { int a; for (a = 1; a < argc; a++) if (!strcmp(str, argv[a])) { if (a == argc - 1) { printf("Argument missing for %s\n", str); exit(1); } return a; } return -1; } int main(int argc, char **argv) { int i; if (argc == 1) { printf("WORD VECTOR estimation toolkit v 0.1c\n\n"); printf("Options:\n"); printf("Parameters for training:\n"); printf("\t-train <file>\n"); printf("\t\tUse text data from <file> to train the model\n"); printf("\t-output <file>\n"); printf("\t\tUse <file> to save the resulting word vectors / word clusters\n"); printf("\t-size <int>\n"); printf("\t\tSet size of word vectors; default is 100\n"); printf("\t-window <int>\n"); printf("\t\tSet max skip length between words; default is 5\n"); printf("\t-sample <float>\n"); printf("\t\tSet threshold for occurrence of words. Those that appear with higher frequency in the training data\n"); printf("\t\twill be randomly down-sampled; default is 1e-3, useful range is (0, 1e-5)\n"); printf("\t-hs <int>\n"); printf("\t\tUse Hierarchical Softmax; default is 0 (not used)\n"); printf("\t-negative <int>\n"); printf("\t\tNumber of negative examples; default is 5, common values are 3 - 10 (0 = not used)\n"); printf("\t-threads <int>\n"); printf("\t\tUse <int> threads (default 12)\n"); printf("\t-iter <int>\n"); printf("\t\tRun more training iterations (default 5)\n"); printf("\t-min-count <int>\n"); printf("\t\tThis will discard words that appear less than <int> times; default is 5\n"); printf("\t-alpha <float>\n"); printf("\t\tSet the starting learning rate; default is 0.025 for skip-gram and 0.05 for CBOW\n"); printf("\t-classes <int>\n"); printf("\t\tOutput word classes rather than word vectors; default number of classes is 0 (vectors are written)\n"); printf("\t-debug <int>\n"); printf("\t\tSet the debug mode (default = 2 = more info during training)\n"); printf("\t-binary <int>\n"); printf("\t\tSave the resulting vectors in binary moded; default is 0 (off)\n"); printf("\t-save-vocab <file>\n"); printf("\t\tThe vocabulary will be saved to <file>\n"); printf("\t-read-vocab <file>\n"); printf("\t\tThe vocabulary will be read from <file>, not constructed from the training data\n"); printf("\t-cbow <int>\n"); printf("\t\tUse the continuous bag of words model; default is 1 (use 0 for skip-gram model)\n"); printf("\nExamples:\n"); printf("./word2vec -train data.txt -output vec.txt -size 200 -window 5 -sample 1e-4 -negative 5 -hs 0 -binary 0 -cbow 1 -iter 3\n\n"); return 0; } output_file[0] = 0; save_vocab_file[0] = 0; read_vocab_file[0] = 0; if ((i = ArgPos((char *)"-size", argc, argv)) > 0) layer1_size = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-train", argc, argv)) > 0) strcpy(train_file, argv[i + 1]); if ((i = ArgPos((char *)"-save-vocab", argc, argv)) > 0) strcpy(save_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-read-vocab", argc, argv)) > 0) strcpy(read_vocab_file, argv[i + 1]); if ((i = ArgPos((char *)"-debug", argc, argv)) > 0) debug_mode = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-binary", argc, argv)) > 0) binary = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-cbow", argc, argv)) > 0) cbow = atoi(argv[i + 1]); if (cbow) alpha = 0.05; if ((i = ArgPos((char *)"-alpha", argc, argv)) > 0) alpha = atof(argv[i + 1]); if ((i = ArgPos((char *)"-output", argc, argv)) > 0) strcpy(output_file, argv[i + 1]); if ((i = ArgPos((char *)"-window", argc, argv)) > 0) window = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-sample", argc, argv)) > 0) sample = atof(argv[i + 1]); if ((i = ArgPos((char *)"-hs", argc, argv)) > 0) hs = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-negative", argc, argv)) > 0) negative = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-threads", argc, argv)) > 0) num_threads = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-iter", argc, argv)) > 0) iter = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-min-count", argc, argv)) > 0) min_count = atoi(argv[i + 1]); if ((i = ArgPos((char *)"-classes", argc, argv)) > 0) classes = atoi(argv[i + 1]); vocab = (struct vocab_word *)calloc(vocab_max_size, sizeof(struct vocab_word)); vocab_hash = (int *)calloc(vocab_hash_size, sizeof(int)); expTable = (real *)malloc((EXP_TABLE_SIZE + 1) * sizeof(real)); for(i = 0; i < EXP_TABLE_SIZE+1; i++) { expTable[i] = exp((i / (real)EXP_TABLE_SIZE * 2 - 1) * MAX_EXP); // Precompute the exp() table expTable[i] = expTable[i] / (expTable[i] + 1); // Precompute f(x) = x / (x + 1) } checkCUDAError(cudaMalloc((void**)&d_expTable, (EXP_TABLE_SIZE+1)*sizeof(real))); checkCUDAError(cudaMemcpy(d_expTable, expTable, (EXP_TABLE_SIZE+1)*sizeof(real), cudaMemcpyHostToDevice)); TrainModel(); return 0; }
3717e104c33dfea64e931536b6bd64e0962c733c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" //#include "ProjHelperFun.cu.h" #include "Constants.h" #include "InitKernels.cu.h" #include "CoreKernels.cu.h" #include "tridagpar.cu.h" //////////////////////////////////////////////////////////////////////////////// ////////////////////////////DEBUGGING////////////////////// void printMatrix(REAL* matrix, unsigned int rows, unsigned int cols){ printf("Matrix = \n[\n"); for(unsigned int i=0; i< rows; ++i){ printf("["); for(unsigned int j=0; j< cols; ++j){ printf("%.5f, ", matrix[i*cols+j]); } printf("]\n"); } printf("]\n"); } __global__ void getList(PrivGlobsCuda* globsList, REAL* res_out, const unsigned size, int g, REAL* mat ){ const unsigned int gid = threadIdx.x + blockIdx.x*blockDim.x; PrivGlobsCuda globs = globsList[8]; if(gid < size){ res_out[gid] = globs.myResult[gid]; } } void cpListSeq(REAL** h_out, REAL* d_in, const unsigned size, const unsigned outer, unsigned index){ unsigned mem_size = outer*size*sizeof(REAL); printf("cpListSeq1\n"); REAL* tmp = (REAL*) malloc(mem_size); printf("cpListSeq2\n"); hipMemcpy(tmp, d_in, mem_size, hipMemcpyDeviceToHost); tmp = &tmp[index*size]; printf("cpListSeq3\n"); for(unsigned i=0; i<size; i++){ (*h_out)[i] = tmp[i]; } free(tmp); } //////////////////////////////////////////////////////////////////////////////// //wrapper for the kernelUpdate void updateWrapper( PrivGlobs* globs, const unsigned g, const unsigned outer, const REAL alpha, const REAL beta, const REAL nu ){ PrivGlobs glob = globs[0]; unsigned myXsize = glob.myXsize; unsigned myYsize = glob.myYsize; unsigned myVarXCols = glob.myVarXCols; unsigned myVarXRows = glob.myVarXRows; unsigned myVarYCols = glob.myVarYCols; unsigned myVarYRows = glob.myVarYRows; unsigned myTimelineSize = glob.myTimelineSize; const int x = myXsize; const int y = myYsize; const int z = outer; const int dimx = ceil( ((float)x) / TVAL ); const int dimy = ceil( ((float)y) / TVAL ); const int dimz = z; dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); REAL *d_myVarX, *d_myX, *d_myVarY, *d_myY, *d_myTimeline; globToDevice(globs, outer, myXsize, &d_myX, 1); globToDevice(globs, outer, myYsize, &d_myY, 2); globToDevice(globs, outer, myVarXCols*myVarXRows, &d_myVarX, 5); globToDevice(globs, outer, myVarYCols*myVarYRows, &d_myVarY, 6); globToDevice(globs, outer, myTimelineSize, &d_myTimeline, 3); hipLaunchKernelGGL(( kernelUpdate) , dim3(grid), dim3(block), 0, 0, d_myVarX, d_myX, d_myVarY, d_myY, d_myTimeline, myXsize, myYsize, myVarXCols, myVarXRows, myVarYCols, myVarYRows, myTimelineSize, g, outer, alpha, beta, nu); hipDeviceSynchronize(); globFromDevice(globs, outer, myVarXCols*myVarXRows, d_myVarX, 5); globFromDevice(globs, outer, myVarYCols*myVarYRows, d_myVarY, 6); } void rollbackWrapper(PrivGlobs* globs, const unsigned g, const unsigned outer, const unsigned numX, const unsigned numY ){ // create all arrays as multidim arrays for rollback() REAL *u, *uT, *v, *y, *yy; hipMalloc((void**)&u, outer*( numY*numX*sizeof(REAL) )); hipMalloc((void**)&uT, outer*( numX*numY*sizeof(REAL) )); hipMalloc((void**)&v, outer*( numX*numY*sizeof(REAL) )); hipMalloc((void**)&y, outer*( numX*numY*sizeof(REAL) )); hipMalloc((void**)&yy, outer*( numX*numY*sizeof(REAL) )); REAL *a, *b, *c, *aT, *bT, *cT; hipMalloc((void**)&a, outer*( numY*numX*sizeof(REAL) )); hipMalloc((void**)&b, outer*( numY*numX*sizeof(REAL) )); hipMalloc((void**)&c, outer*( numY*numX*sizeof(REAL) )); hipMalloc((void**)&aT, outer*( numX*numY*sizeof(REAL) )); hipMalloc((void**)&bT, outer*( numX*numY*sizeof(REAL) )); hipMalloc((void**)&cT, outer*( numX*numY*sizeof(REAL) )); const int x = max(numX, numY); //max(myXsize, numY), myXsize = numX int dimx = ceil( ((float)x) / TVAL ); int dimy = ceil( ((float)x) / TVAL ); int dimz = outer; dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); unsigned int sh_mem_size = TVAL*TVAL;//numY*numX*outer; REAL *myTimeline, *myVarX, *myVarY, *myResult, *myDxx, *myDyy; PrivGlobs glob = globs[0]; unsigned myTimelineSize = glob.myTimelineSize; unsigned myVarXRows = glob.myVarXRows; unsigned myVarXCols = glob.myVarXCols; unsigned myVarYRows = glob.myVarYRows; unsigned myVarYCols = glob.myVarYCols; unsigned myResultRows = glob.myResultRows; unsigned myResultCols = glob.myResultCols; unsigned myDxxRows = glob.myDxxRows; unsigned myDxxCols = glob.myDxxCols; unsigned myDyyRows = glob.myDyyRows; unsigned myDyyCols = glob.myDyyCols; globToDevice(globs, outer, myTimelineSize, &myTimeline, 3); globToDevice(globs, outer, myVarXRows*myVarXCols, &myVarX, 5); globToDevice(globs, outer, myVarYRows*myVarYCols, &myVarY, 6); globToDevice(globs, outer, myResultRows*myResultCols, &myResult, 4); globToDevice(globs, outer, myDxxRows*myDxxCols, &myDxx, 7); globToDevice(globs, outer, myDyyRows*myDyyCols, &myDyy, 8); //oh the humanity! hipLaunchKernelGGL(( kernelRollback1) , dim3(grid), dim3(block) , 0, 0, myTimeline, myVarX, myVarY, myResult, myDxx, myDyy, myTimelineSize, myVarXRows, myVarXCols, myVarYRows, myVarYCols, myResultRows, myResultCols, myDxxRows, myDxxCols, myDyyRows, myDyyCols, g, outer, u, uT, v, y, a, b, c, aT, bT, cT ); ////sequential part for(unsigned k = 0; k < outer; ++k){ unsigned i,j; REAL *us = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numX] REAL *uTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *vs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *ys = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *yys = (REAL*) malloc(numY*sizeof(REAL)); // [max(numX,numY)] REAL *as = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numY] REAL *bs = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numY] REAL *cs = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numY] REAL *aTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numY][numY] REAL *bTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numY][numY] REAL *cTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] PrivGlobs glob = globs[k]; REAL dtInv = 1.0/(glob.myTimeline[g+1]-glob.myTimeline[g]); //printf("\nbefore cpListSeq\n"); cpListSeq(&aTs, aT, numY*numX, outer, k); cpListSeq(&bTs, bT, numY*numX, outer, k); cpListSeq(&cTs, cT, numY*numX, outer, k); cpListSeq(&uTs, uT, numY*numX, outer, k); printMatrix(as, numY, numX); //printf("\nafter cpListSeq\n"); transpose2d(uTs, &us, numY, numX); transpose2d(aTs, &as, numY, numX); transpose2d(bTs, &bs, numY, numX); transpose2d(cTs, &cs, numY, numX); for(j=0;j<numY;j++) { // par // h ere yys should have size [numX] tridagPar(&as[idx2d(j,0,numX)], &bs[idx2d(j,0,numX)], &cs[idx2d(j,0,numX)] ,&us[idx2d(j,0,numX)],numX,&us[idx2d(j,0,numX)],&yys[0]); } for(i=0;i<numX;i++) { // par // parallelizable via loop distribution / array expansion. for(j=0;j<numY;j++) { // par // here as, bs, cs should have size [numY] aTs[idx2d(i,j,numY)] = - 0.5*(0.5*glob.myVarY[idx2d(i,j,glob.myVarYCols)]*glob.myDyy[idx2d(j,0,glob.myDyyCols)]); bTs[idx2d(i,j,numY)] = dtInv - 0.5*(0.5*glob.myVarY[idx2d(i,j,glob.myVarYCols)]*glob.myDyy[idx2d(j,1,glob.myDyyCols)]); cTs[idx2d(i,j,numY)] = - 0.5*(0.5*glob.myVarY[idx2d(i,j,glob.myVarYCols)]*glob.myDyy[idx2d(j,2,glob.myDyyCols)]); } } transpose2d(aTs, &as, numY, numX); transpose2d(bTs, &bs, numY, numX); transpose2d(cTs, &cs, numY, numX); transpose2d(us, &uTs, numX, numY); //Must retranspose to uTs because prev tridag // modified us. // Coalesced memory acces. for(i=0;i<numX;i++) { // par for(j=0;j<numY;j++) { // par ys[idx2d(i,j,numY)] = dtInv * uTs[idx2d(i,j,numY)] - 0.5*vs[idx2d(i,j,numY)]; } } for(i=0;i<numX;i++) { // par // here yys should have size [numX] tridagPar(&aTs[idx2d(i,0,numY)], &bTs[idx2d(i,0,numY)], &cTs[idx2d(i,0,numY)], &ys[idx2d(i,0,numY)], numY, &glob.myResult[idx2d(i,0,glob.myResultCols)],&yys[0]); } free(us); free(uTs); free(vs); free(ys); free(yys); free(as); free(bs); free(cs); free(aTs); free(bTs); free(cTs); } //////////////////////// // This code was supposed to be the rest of the CUDA implementation, but it is // Commented out because it does not work yet. /* { int dimx = ceil( ((float)numX) / TVAL ); int dimy = ceil( ((float)numY) / TVAL ); dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); //Tridag 1 //tridag1(outer, u, yy, a, b, c, numX, numY, numZ); kernelTridag1 <<< block, grid, sh_mem_size >>> (outer, u, yy, a, b, c, numX, numY); hipDeviceSynchronize(); } kernelRollback2 <<< grid, block>>> ( myTimeline, myVarX, myVarY, myDxx, myDyy, myTimelineSize, myVarXRows, myVarXCols, myVarYRows, myVarYCols, myDxxRows, myDxxCols, myDyyRows, myDyyCols, g, outer, u, uT, v, y, yy, a, b, c, aT, bT, cT); hipDeviceSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(aT, a, numY, numX); hipDeviceSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(bT, b, numY, numX); hipDeviceSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(cT, c, numY, numX); hipDeviceSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(u, uT, numX, numY); hipDeviceSynchronize(); kernelRollback3 <<< grid, block>>> (myTimeline, myTimelineSize, numX, numY, g, outer, uT, v, y); hipDeviceSynchronize(); //tridag2(globsList, outer, y, yy, aT, bT, cT, numX, numY, numZ); { unsigned myResultSize = myResultRows*myResultCols; dimx = ceil( ((float)numY) / TVAL ); dimy = ceil( ((float)numX) / TVAL ); dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); kernelTridag2 <<< block, grid, sh_mem_size >>> (myResult, myResultSize, outer, y, yy, aT, bT, cT, numX, numY); hipDeviceSynchronize(); globFromDevice(globs, outer, myResultSize, myResult, 4); } */ hipFree(u); hipFree(uT); hipFree(v); hipFree(y); hipFree(yy); hipFree(a); hipFree(b); hipFree(c); hipFree(aT); hipFree(bT); hipFree(cT); } void init(PrivGlobs* globs, const unsigned outer, const REAL s0, const REAL alpha, const REAL nu, const REAL t, const unsigned numX, const unsigned numY, const unsigned numT ){ { //init grid initGridWrapper(globs, outer, numX, numY, numT, t, alpha, s0, nu); //init op Dxx and Dyy initOperatorWrapper(globs, outer); setPayoffWrapper(globs, outer, numX, numY); } } //////////////////////// sequential //////////////////////// void updateParams(const unsigned g, const REAL alpha, const REAL beta, const REAL nu, PrivGlobs& globs) { // parallelizable directly since all reads and writes are independent. // Degree of parallelism: myX.size*myY.size // Access to myVarX and myVarY is already coalesced. for(unsigned i=0;i<globs.myXsize;++i) // par for(unsigned j=0;j<globs.myYsize;++j) { // par globs.myVarX[idx2d(i,j,globs.myVarXCols)] = exp(2.0*( beta*log(globs.myX[i]) + globs.myY[j] - 0.5*nu*nu*globs.myTimeline[g] ) ); globs.myVarY[idx2d(i,j,globs.myVarYCols)] = exp(2.0*( alpha*log(globs.myX[i]) + globs.myY[j] - 0.5*nu*nu*globs.myTimeline[g] ) ); // nu*nu } } void rollback( const unsigned g, PrivGlobs& globs ) { unsigned numX = globs.myXsize, numY = globs.myYsize; unsigned numZ = max(numX,numY); unsigned i, j; REAL dtInv = 1.0/(globs.myTimeline[g+1]-globs.myTimeline[g]); REAL *u = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numX] REAL *uT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *v = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *y = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numZ] REAL *yy = (REAL*) malloc(numY*sizeof(REAL)); // [max(numX,numY)] for(i=0;i<numX;i++) { //par for(j=0;j<numY;j++) { //par uT[idx2d(i,j,numY)] = dtInv*globs.myResult[idx2d(i,j,globs.myResultCols)]; if(i > 0) { uT[idx2d(i,j,numY)] += 0.5*( 0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,0,globs.myDxxCols)] ) * globs.myResult[idx2d(i-1,j,globs.myResultCols)]; } uT[idx2d(i,j,numY)] += 0.5*( 0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,1,globs.myDxxCols)] ) * globs.myResult[idx2d(i,j,globs.myResultCols)]; if(i < numX-1) { uT[idx2d(i,j,numY)] += 0.5*( 0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,2,globs.myDxxCols)] ) * globs.myResult[idx2d(i+1,j,globs.myResultCols)]; } } } for(i=0;i<numX;i++) { //par for(j=0;j<numY;j++) { //par v[idx2d(i,j,numY)] = 0.0; if(j > 0) { v[idx2d(i,j,numY)] += ( 0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,0,globs.myDyyCols)]) * globs.myResult[idx2d(i,j-1,globs.myResultCols)]; } v[idx2d(i,j,numY)] += ( 0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,1,globs.myDyyCols)]) * globs.myResult[idx2d(i,j,globs.myResultCols)]; if(j < numY-1) { v[idx2d(i,j,numY)] += ( 0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,2,globs.myDyyCols)]) * globs.myResult[idx2d(i,j+1,globs.myResultCols)]; } uT[idx2d(i,j,numY)] += v[idx2d(i,j,numY)]; } } transpose2d(uT, &u, numY, numX); REAL *a = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numZ] REAL *b = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numZ] REAL *c = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numZ] REAL *aT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] REAL *bT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] REAL *cT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] for(i=0;i<numX;i++) { // par // here a, b,c should have size [numX] for(j=0;j<numY;j++) { // par aT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,0,globs.myDxxCols)]); bT[idx2d(i,j,numY)] = dtInv - 0.5*(0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,1,globs.myDxxCols)]); cT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,2,globs.myDxxCols)]); } } transpose2d(aT, &a, numY, numX); transpose2d(bT, &b, numY, numX); transpose2d(cT, &c, numY, numX); for(j=0;j<numY;j++) { // par // here yy should have size [numX] tridagPar(&a[idx2d(j,0,numX)], &b[idx2d(j,0,numX)], &c[idx2d(j,0,numX)] ,&u[idx2d(j,0,numX)],numX,&u[idx2d(j,0,numX)],&yy[0]); } for(i=0;i<numX;i++) { // par // parallelizable via loop distribution / array expansion. for(j=0;j<numY;j++) { // par // here a, b, c should have size [numY] aT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,0,globs.myDyyCols)]); bT[idx2d(i,j,numY)] = dtInv - 0.5*(0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,1,globs.myDyyCols)]); cT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,2,globs.myDyyCols)]); } } transpose2d(aT, &a, numY, numX); transpose2d(bT, &b, numY, numX); transpose2d(cT, &c, numY, numX); transpose2d(u, &uT, numX, numY); //Must retranspose to uT because prev tridag // modified u. // Coalesced memory acces. for(i=0;i<numX;i++) { // par for(j=0;j<numY;j++) { // par y[idx2d(i,j,numY)] = dtInv * uT[idx2d(i,j,numY)] - 0.5*v[idx2d(i,j,numY)]; } } for(i=0;i<numX;i++) { // par // here yy should have size [numX] tridagPar(&aT[idx2d(i,0,numY)], &bT[idx2d(i,0,numY)], &cT[idx2d(i,0,numY)], &y[idx2d(i,0,numY)], numY, &globs.myResult[idx2d(i,0,globs.myResultCols)],&yy[0]); } free(u); free(uT); free(v); free(y); free(yy); free(a); free(b); free(c); free(aT); free(bT); free(cT); } void initGrid( const REAL s0, const REAL alpha, const REAL nu,const REAL t, const unsigned numX, const unsigned numY, const unsigned numT, PrivGlobs& globs ) { // Can be parallelized directly as each iteration writes to independent // globs.myTimeline indices for(unsigned i=0;i<numT;++i) // par globs.myTimeline[i] = t*i/(numT-1); const REAL stdX = 20.0*alpha*s0*sqrt(t); const REAL dx = stdX/numX; globs.myXindex = static_cast<unsigned>(s0/dx) % numX; // Can be parallelized directly as each iteration writes to independent // globs.myX indices. for(unsigned i=0;i<numX;++i) // par globs.myX[i] = i*dx - globs.myXindex*dx + s0; const REAL stdY = 10.0*nu*sqrt(t); const REAL dy = stdY/numY; const REAL logAlpha = log(alpha); globs.myYindex = static_cast<unsigned>(numY/2.0); // Can be parallelized directly as each iteration writes to independent // globs.myY indices. for(unsigned i=0;i<numY;++i) // par globs.myY[i] = i*dy - globs.myYindex*dy + logAlpha; } void initOperator( const REAL *x, unsigned xsize, REAL* &Dxx, unsigned DxxCols ) { const unsigned n = xsize; REAL dxl, dxu; // lower boundary dxl = 0.0; dxu = x[1] - x[0]; Dxx[idx2d(0,0,DxxCols)] = 0.0; Dxx[idx2d(0,1,DxxCols)] = 0.0; Dxx[idx2d(0,2,DxxCols)] = 0.0; Dxx[idx2d(0,3,DxxCols)] = 0.0; // standard case // Can be parallelized directly as each iteration writes to independent // Dxx indices. x is only read, so each iteration is independent. // x could be put in shared memory. for(unsigned i=1;i<n-1;i++) // par { dxl = x[i] - x[i-1]; dxu = x[i+1] - x[i]; Dxx[idx2d(i,0,DxxCols)] = 2.0/dxl/(dxl+dxu); Dxx[idx2d(i,1,DxxCols)] = -2.0*(1.0/dxl + 1.0/dxu)/(dxl+dxu); Dxx[idx2d(i,2,DxxCols)] = 2.0/dxu/(dxl+dxu); Dxx[idx2d(i,3,DxxCols)] = 0.0; } // upper boundary dxl = x[n-1] - x[n-2]; dxu = 0.0; Dxx[idx2d(n-1,0,DxxCols)] = 0.0; Dxx[idx2d(n-1,1,DxxCols)] = 0.0; Dxx[idx2d(n-1,2,DxxCols)] = 0.0; Dxx[idx2d(n-1,3,DxxCols)] = 0.0; } void setPayoff(const REAL strike, PrivGlobs& globs ) { // Assuming globs is local the loop can be parallelized since // - reads independent // - writes independent (not same as read array) // Problem in payoff. Can be put inline (scalar variable), but this results // in myX.size*myY.size mem accesses. // If array expansion, only myX.size+myY.size mem accesses. // TODO: To be determined based on myX.size and myY.size. // Small dataset= NUM_X = 32 ; NUM_Y = 256 // 8192 vs 288 -- array expansion is preferable. // Array expansion **DONE. REAL payoff[globs.myXsize]; for(unsigned i=0;i<globs.myXsize;++i) payoff[i] = max(globs.myX[i]-strike, (REAL)0.0); // Already coalesced. for(unsigned i=0;i<globs.myXsize;++i) { // par for(unsigned j=0;j<globs.myYsize;++j) // par globs.myResult[idx2d(i,j,globs.myResultCols)] = payoff[i]; } } //////////////////////////////////////////////////////////////////////// void run_GPU( const unsigned int& outer, const unsigned int& numX, const unsigned int& numY, const unsigned int& numT, const REAL& s0, const REAL& t, const REAL& alpha, const REAL& nu, const REAL& beta, REAL* res // [outer] RESULT ) { PrivGlobs *globs = (PrivGlobs*) malloc(outer*sizeof(struct PrivGlobs)); for(int i = 0 ; i < outer ; i++) { globs[i] = PrivGlobs(numX,numY,numT); } init(globs, outer, s0, alpha, nu, t, numX, numY, numT); for(int i = numT-2;i>=0;--i){ //seq updateWrapper(globs, i, outer, alpha, beta, nu); //rollbackWrapper(globs, i, outer, numX, numY); for( unsigned j = 0; j < outer; ++ j ) { //par // updateParams(i,alpha,beta,nu,globs[j]); rollback(i, globs[j]); } } // parallel assignment of results. for( unsigned j = 0; j < outer; ++ j ) { //par res[j] = globs[j].myResult[idx2d(globs[j].myXindex,globs[j].myYindex,globs[j].myResultCols)]; } }
3717e104c33dfea64e931536b6bd64e0962c733c.cu
//#include "ProjHelperFun.cu.h" #include "Constants.h" #include "InitKernels.cu.h" #include "CoreKernels.cu.h" #include "tridagpar.cu.h" //////////////////////////////////////////////////////////////////////////////// ////////////////////////////DEBUGGING////////////////////// void printMatrix(REAL* matrix, unsigned int rows, unsigned int cols){ printf("Matrix = \n[\n"); for(unsigned int i=0; i< rows; ++i){ printf("["); for(unsigned int j=0; j< cols; ++j){ printf("%.5f, ", matrix[i*cols+j]); } printf("]\n"); } printf("]\n"); } __global__ void getList(PrivGlobsCuda* globsList, REAL* res_out, const unsigned size, int g, REAL* mat ){ const unsigned int gid = threadIdx.x + blockIdx.x*blockDim.x; PrivGlobsCuda globs = globsList[8]; if(gid < size){ res_out[gid] = globs.myResult[gid]; } } void cpListSeq(REAL** h_out, REAL* d_in, const unsigned size, const unsigned outer, unsigned index){ unsigned mem_size = outer*size*sizeof(REAL); printf("cpListSeq1\n"); REAL* tmp = (REAL*) malloc(mem_size); printf("cpListSeq2\n"); cudaMemcpy(tmp, d_in, mem_size, cudaMemcpyDeviceToHost); tmp = &tmp[index*size]; printf("cpListSeq3\n"); for(unsigned i=0; i<size; i++){ (*h_out)[i] = tmp[i]; } free(tmp); } //////////////////////////////////////////////////////////////////////////////// //wrapper for the kernelUpdate void updateWrapper( PrivGlobs* globs, const unsigned g, const unsigned outer, const REAL alpha, const REAL beta, const REAL nu ){ PrivGlobs glob = globs[0]; unsigned myXsize = glob.myXsize; unsigned myYsize = glob.myYsize; unsigned myVarXCols = glob.myVarXCols; unsigned myVarXRows = glob.myVarXRows; unsigned myVarYCols = glob.myVarYCols; unsigned myVarYRows = glob.myVarYRows; unsigned myTimelineSize = glob.myTimelineSize; const int x = myXsize; const int y = myYsize; const int z = outer; const int dimx = ceil( ((float)x) / TVAL ); const int dimy = ceil( ((float)y) / TVAL ); const int dimz = z; dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); REAL *d_myVarX, *d_myX, *d_myVarY, *d_myY, *d_myTimeline; globToDevice(globs, outer, myXsize, &d_myX, 1); globToDevice(globs, outer, myYsize, &d_myY, 2); globToDevice(globs, outer, myVarXCols*myVarXRows, &d_myVarX, 5); globToDevice(globs, outer, myVarYCols*myVarYRows, &d_myVarY, 6); globToDevice(globs, outer, myTimelineSize, &d_myTimeline, 3); kernelUpdate <<< grid, block>>>(d_myVarX, d_myX, d_myVarY, d_myY, d_myTimeline, myXsize, myYsize, myVarXCols, myVarXRows, myVarYCols, myVarYRows, myTimelineSize, g, outer, alpha, beta, nu); cudaThreadSynchronize(); globFromDevice(globs, outer, myVarXCols*myVarXRows, d_myVarX, 5); globFromDevice(globs, outer, myVarYCols*myVarYRows, d_myVarY, 6); } void rollbackWrapper(PrivGlobs* globs, const unsigned g, const unsigned outer, const unsigned numX, const unsigned numY ){ // create all arrays as multidim arrays for rollback() REAL *u, *uT, *v, *y, *yy; cudaMalloc((void**)&u, outer*( numY*numX*sizeof(REAL) )); cudaMalloc((void**)&uT, outer*( numX*numY*sizeof(REAL) )); cudaMalloc((void**)&v, outer*( numX*numY*sizeof(REAL) )); cudaMalloc((void**)&y, outer*( numX*numY*sizeof(REAL) )); cudaMalloc((void**)&yy, outer*( numX*numY*sizeof(REAL) )); REAL *a, *b, *c, *aT, *bT, *cT; cudaMalloc((void**)&a, outer*( numY*numX*sizeof(REAL) )); cudaMalloc((void**)&b, outer*( numY*numX*sizeof(REAL) )); cudaMalloc((void**)&c, outer*( numY*numX*sizeof(REAL) )); cudaMalloc((void**)&aT, outer*( numX*numY*sizeof(REAL) )); cudaMalloc((void**)&bT, outer*( numX*numY*sizeof(REAL) )); cudaMalloc((void**)&cT, outer*( numX*numY*sizeof(REAL) )); const int x = max(numX, numY); //max(myXsize, numY), myXsize = numX int dimx = ceil( ((float)x) / TVAL ); int dimy = ceil( ((float)x) / TVAL ); int dimz = outer; dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); unsigned int sh_mem_size = TVAL*TVAL;//numY*numX*outer; REAL *myTimeline, *myVarX, *myVarY, *myResult, *myDxx, *myDyy; PrivGlobs glob = globs[0]; unsigned myTimelineSize = glob.myTimelineSize; unsigned myVarXRows = glob.myVarXRows; unsigned myVarXCols = glob.myVarXCols; unsigned myVarYRows = glob.myVarYRows; unsigned myVarYCols = glob.myVarYCols; unsigned myResultRows = glob.myResultRows; unsigned myResultCols = glob.myResultCols; unsigned myDxxRows = glob.myDxxRows; unsigned myDxxCols = glob.myDxxCols; unsigned myDyyRows = glob.myDyyRows; unsigned myDyyCols = glob.myDyyCols; globToDevice(globs, outer, myTimelineSize, &myTimeline, 3); globToDevice(globs, outer, myVarXRows*myVarXCols, &myVarX, 5); globToDevice(globs, outer, myVarYRows*myVarYCols, &myVarY, 6); globToDevice(globs, outer, myResultRows*myResultCols, &myResult, 4); globToDevice(globs, outer, myDxxRows*myDxxCols, &myDxx, 7); globToDevice(globs, outer, myDyyRows*myDyyCols, &myDyy, 8); //oh the humanity! kernelRollback1 <<< grid, block >>> (myTimeline, myVarX, myVarY, myResult, myDxx, myDyy, myTimelineSize, myVarXRows, myVarXCols, myVarYRows, myVarYCols, myResultRows, myResultCols, myDxxRows, myDxxCols, myDyyRows, myDyyCols, g, outer, u, uT, v, y, a, b, c, aT, bT, cT ); ////sequential part for(unsigned k = 0; k < outer; ++k){ unsigned i,j; REAL *us = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numX] REAL *uTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *vs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *ys = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *yys = (REAL*) malloc(numY*sizeof(REAL)); // [max(numX,numY)] REAL *as = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numY] REAL *bs = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numY] REAL *cs = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numY] REAL *aTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numY][numY] REAL *bTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numY][numY] REAL *cTs = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] PrivGlobs glob = globs[k]; REAL dtInv = 1.0/(glob.myTimeline[g+1]-glob.myTimeline[g]); //printf("\nbefore cpListSeq\n"); cpListSeq(&aTs, aT, numY*numX, outer, k); cpListSeq(&bTs, bT, numY*numX, outer, k); cpListSeq(&cTs, cT, numY*numX, outer, k); cpListSeq(&uTs, uT, numY*numX, outer, k); printMatrix(as, numY, numX); //printf("\nafter cpListSeq\n"); transpose2d(uTs, &us, numY, numX); transpose2d(aTs, &as, numY, numX); transpose2d(bTs, &bs, numY, numX); transpose2d(cTs, &cs, numY, numX); for(j=0;j<numY;j++) { // par // h ere yys should have size [numX] tridagPar(&as[idx2d(j,0,numX)], &bs[idx2d(j,0,numX)], &cs[idx2d(j,0,numX)] ,&us[idx2d(j,0,numX)],numX,&us[idx2d(j,0,numX)],&yys[0]); } for(i=0;i<numX;i++) { // par // parallelizable via loop distribution / array expansion. for(j=0;j<numY;j++) { // par // here as, bs, cs should have size [numY] aTs[idx2d(i,j,numY)] = - 0.5*(0.5*glob.myVarY[idx2d(i,j,glob.myVarYCols)]*glob.myDyy[idx2d(j,0,glob.myDyyCols)]); bTs[idx2d(i,j,numY)] = dtInv - 0.5*(0.5*glob.myVarY[idx2d(i,j,glob.myVarYCols)]*glob.myDyy[idx2d(j,1,glob.myDyyCols)]); cTs[idx2d(i,j,numY)] = - 0.5*(0.5*glob.myVarY[idx2d(i,j,glob.myVarYCols)]*glob.myDyy[idx2d(j,2,glob.myDyyCols)]); } } transpose2d(aTs, &as, numY, numX); transpose2d(bTs, &bs, numY, numX); transpose2d(cTs, &cs, numY, numX); transpose2d(us, &uTs, numX, numY); //Must retranspose to uTs because prev tridag // modified us. // Coalesced memory acces. for(i=0;i<numX;i++) { // par for(j=0;j<numY;j++) { // par ys[idx2d(i,j,numY)] = dtInv * uTs[idx2d(i,j,numY)] - 0.5*vs[idx2d(i,j,numY)]; } } for(i=0;i<numX;i++) { // par // here yys should have size [numX] tridagPar(&aTs[idx2d(i,0,numY)], &bTs[idx2d(i,0,numY)], &cTs[idx2d(i,0,numY)], &ys[idx2d(i,0,numY)], numY, &glob.myResult[idx2d(i,0,glob.myResultCols)],&yys[0]); } free(us); free(uTs); free(vs); free(ys); free(yys); free(as); free(bs); free(cs); free(aTs); free(bTs); free(cTs); } //////////////////////// // This code was supposed to be the rest of the CUDA implementation, but it is // Commented out because it does not work yet. /* { int dimx = ceil( ((float)numX) / TVAL ); int dimy = ceil( ((float)numY) / TVAL ); dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); //Tridag 1 //tridag1(outer, u, yy, a, b, c, numX, numY, numZ); kernelTridag1 <<< block, grid, sh_mem_size >>> (outer, u, yy, a, b, c, numX, numY); cudaThreadSynchronize(); } kernelRollback2 <<< grid, block>>> ( myTimeline, myVarX, myVarY, myDxx, myDyy, myTimelineSize, myVarXRows, myVarXCols, myVarYRows, myVarYCols, myDxxRows, myDxxCols, myDyyRows, myDyyCols, g, outer, u, uT, v, y, yy, a, b, c, aT, bT, cT); cudaThreadSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(aT, a, numY, numX); cudaThreadSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(bT, b, numY, numX); cudaThreadSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(cT, c, numY, numX); cudaThreadSynchronize(); transpose3dTiled<TVAL><<< grid, block >>>(u, uT, numX, numY); cudaThreadSynchronize(); kernelRollback3 <<< grid, block>>> (myTimeline, myTimelineSize, numX, numY, g, outer, uT, v, y); cudaThreadSynchronize(); //tridag2(globsList, outer, y, yy, aT, bT, cT, numX, numY, numZ); { unsigned myResultSize = myResultRows*myResultCols; dimx = ceil( ((float)numY) / TVAL ); dimy = ceil( ((float)numX) / TVAL ); dim3 block(TVAL,TVAL,1), grid(dimx,dimy,dimz); kernelTridag2 <<< block, grid, sh_mem_size >>> (myResult, myResultSize, outer, y, yy, aT, bT, cT, numX, numY); cudaThreadSynchronize(); globFromDevice(globs, outer, myResultSize, myResult, 4); } */ cudaFree(u); cudaFree(uT); cudaFree(v); cudaFree(y); cudaFree(yy); cudaFree(a); cudaFree(b); cudaFree(c); cudaFree(aT); cudaFree(bT); cudaFree(cT); } void init(PrivGlobs* globs, const unsigned outer, const REAL s0, const REAL alpha, const REAL nu, const REAL t, const unsigned numX, const unsigned numY, const unsigned numT ){ { //init grid initGridWrapper(globs, outer, numX, numY, numT, t, alpha, s0, nu); //init op Dxx and Dyy initOperatorWrapper(globs, outer); setPayoffWrapper(globs, outer, numX, numY); } } //////////////////////// sequential //////////////////////// void updateParams(const unsigned g, const REAL alpha, const REAL beta, const REAL nu, PrivGlobs& globs) { // parallelizable directly since all reads and writes are independent. // Degree of parallelism: myX.size*myY.size // Access to myVarX and myVarY is already coalesced. for(unsigned i=0;i<globs.myXsize;++i) // par for(unsigned j=0;j<globs.myYsize;++j) { // par globs.myVarX[idx2d(i,j,globs.myVarXCols)] = exp(2.0*( beta*log(globs.myX[i]) + globs.myY[j] - 0.5*nu*nu*globs.myTimeline[g] ) ); globs.myVarY[idx2d(i,j,globs.myVarYCols)] = exp(2.0*( alpha*log(globs.myX[i]) + globs.myY[j] - 0.5*nu*nu*globs.myTimeline[g] ) ); // nu*nu } } void rollback( const unsigned g, PrivGlobs& globs ) { unsigned numX = globs.myXsize, numY = globs.myYsize; unsigned numZ = max(numX,numY); unsigned i, j; REAL dtInv = 1.0/(globs.myTimeline[g+1]-globs.myTimeline[g]); REAL *u = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numX] REAL *uT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *v = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numY] REAL *y = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numX][numZ] REAL *yy = (REAL*) malloc(numY*sizeof(REAL)); // [max(numX,numY)] for(i=0;i<numX;i++) { //par for(j=0;j<numY;j++) { //par uT[idx2d(i,j,numY)] = dtInv*globs.myResult[idx2d(i,j,globs.myResultCols)]; if(i > 0) { uT[idx2d(i,j,numY)] += 0.5*( 0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,0,globs.myDxxCols)] ) * globs.myResult[idx2d(i-1,j,globs.myResultCols)]; } uT[idx2d(i,j,numY)] += 0.5*( 0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,1,globs.myDxxCols)] ) * globs.myResult[idx2d(i,j,globs.myResultCols)]; if(i < numX-1) { uT[idx2d(i,j,numY)] += 0.5*( 0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,2,globs.myDxxCols)] ) * globs.myResult[idx2d(i+1,j,globs.myResultCols)]; } } } for(i=0;i<numX;i++) { //par for(j=0;j<numY;j++) { //par v[idx2d(i,j,numY)] = 0.0; if(j > 0) { v[idx2d(i,j,numY)] += ( 0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,0,globs.myDyyCols)]) * globs.myResult[idx2d(i,j-1,globs.myResultCols)]; } v[idx2d(i,j,numY)] += ( 0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,1,globs.myDyyCols)]) * globs.myResult[idx2d(i,j,globs.myResultCols)]; if(j < numY-1) { v[idx2d(i,j,numY)] += ( 0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,2,globs.myDyyCols)]) * globs.myResult[idx2d(i,j+1,globs.myResultCols)]; } uT[idx2d(i,j,numY)] += v[idx2d(i,j,numY)]; } } transpose2d(uT, &u, numY, numX); REAL *a = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numZ] REAL *b = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numZ] REAL *c = (REAL*) malloc(numY*numX*sizeof(REAL)); // [numY][numZ] REAL *aT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] REAL *bT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] REAL *cT = (REAL*) malloc(numX*numY*sizeof(REAL)); // [numZ][numY] for(i=0;i<numX;i++) { // par // here a, b,c should have size [numX] for(j=0;j<numY;j++) { // par aT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,0,globs.myDxxCols)]); bT[idx2d(i,j,numY)] = dtInv - 0.5*(0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,1,globs.myDxxCols)]); cT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarX[idx2d(i,j,globs.myVarXCols)]*globs.myDxx[idx2d(i,2,globs.myDxxCols)]); } } transpose2d(aT, &a, numY, numX); transpose2d(bT, &b, numY, numX); transpose2d(cT, &c, numY, numX); for(j=0;j<numY;j++) { // par // here yy should have size [numX] tridagPar(&a[idx2d(j,0,numX)], &b[idx2d(j,0,numX)], &c[idx2d(j,0,numX)] ,&u[idx2d(j,0,numX)],numX,&u[idx2d(j,0,numX)],&yy[0]); } for(i=0;i<numX;i++) { // par // parallelizable via loop distribution / array expansion. for(j=0;j<numY;j++) { // par // here a, b, c should have size [numY] aT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,0,globs.myDyyCols)]); bT[idx2d(i,j,numY)] = dtInv - 0.5*(0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,1,globs.myDyyCols)]); cT[idx2d(i,j,numY)] = - 0.5*(0.5*globs.myVarY[idx2d(i,j,globs.myVarYCols)]*globs.myDyy[idx2d(j,2,globs.myDyyCols)]); } } transpose2d(aT, &a, numY, numX); transpose2d(bT, &b, numY, numX); transpose2d(cT, &c, numY, numX); transpose2d(u, &uT, numX, numY); //Must retranspose to uT because prev tridag // modified u. // Coalesced memory acces. for(i=0;i<numX;i++) { // par for(j=0;j<numY;j++) { // par y[idx2d(i,j,numY)] = dtInv * uT[idx2d(i,j,numY)] - 0.5*v[idx2d(i,j,numY)]; } } for(i=0;i<numX;i++) { // par // here yy should have size [numX] tridagPar(&aT[idx2d(i,0,numY)], &bT[idx2d(i,0,numY)], &cT[idx2d(i,0,numY)], &y[idx2d(i,0,numY)], numY, &globs.myResult[idx2d(i,0,globs.myResultCols)],&yy[0]); } free(u); free(uT); free(v); free(y); free(yy); free(a); free(b); free(c); free(aT); free(bT); free(cT); } void initGrid( const REAL s0, const REAL alpha, const REAL nu,const REAL t, const unsigned numX, const unsigned numY, const unsigned numT, PrivGlobs& globs ) { // Can be parallelized directly as each iteration writes to independent // globs.myTimeline indices for(unsigned i=0;i<numT;++i) // par globs.myTimeline[i] = t*i/(numT-1); const REAL stdX = 20.0*alpha*s0*sqrt(t); const REAL dx = stdX/numX; globs.myXindex = static_cast<unsigned>(s0/dx) % numX; // Can be parallelized directly as each iteration writes to independent // globs.myX indices. for(unsigned i=0;i<numX;++i) // par globs.myX[i] = i*dx - globs.myXindex*dx + s0; const REAL stdY = 10.0*nu*sqrt(t); const REAL dy = stdY/numY; const REAL logAlpha = log(alpha); globs.myYindex = static_cast<unsigned>(numY/2.0); // Can be parallelized directly as each iteration writes to independent // globs.myY indices. for(unsigned i=0;i<numY;++i) // par globs.myY[i] = i*dy - globs.myYindex*dy + logAlpha; } void initOperator( const REAL *x, unsigned xsize, REAL* &Dxx, unsigned DxxCols ) { const unsigned n = xsize; REAL dxl, dxu; // lower boundary dxl = 0.0; dxu = x[1] - x[0]; Dxx[idx2d(0,0,DxxCols)] = 0.0; Dxx[idx2d(0,1,DxxCols)] = 0.0; Dxx[idx2d(0,2,DxxCols)] = 0.0; Dxx[idx2d(0,3,DxxCols)] = 0.0; // standard case // Can be parallelized directly as each iteration writes to independent // Dxx indices. x is only read, so each iteration is independent. // x could be put in shared memory. for(unsigned i=1;i<n-1;i++) // par { dxl = x[i] - x[i-1]; dxu = x[i+1] - x[i]; Dxx[idx2d(i,0,DxxCols)] = 2.0/dxl/(dxl+dxu); Dxx[idx2d(i,1,DxxCols)] = -2.0*(1.0/dxl + 1.0/dxu)/(dxl+dxu); Dxx[idx2d(i,2,DxxCols)] = 2.0/dxu/(dxl+dxu); Dxx[idx2d(i,3,DxxCols)] = 0.0; } // upper boundary dxl = x[n-1] - x[n-2]; dxu = 0.0; Dxx[idx2d(n-1,0,DxxCols)] = 0.0; Dxx[idx2d(n-1,1,DxxCols)] = 0.0; Dxx[idx2d(n-1,2,DxxCols)] = 0.0; Dxx[idx2d(n-1,3,DxxCols)] = 0.0; } void setPayoff(const REAL strike, PrivGlobs& globs ) { // Assuming globs is local the loop can be parallelized since // - reads independent // - writes independent (not same as read array) // Problem in payoff. Can be put inline (scalar variable), but this results // in myX.size*myY.size mem accesses. // If array expansion, only myX.size+myY.size mem accesses. // TODO: To be determined based on myX.size and myY.size. // Small dataset= NUM_X = 32 ; NUM_Y = 256 // 8192 vs 288 -- array expansion is preferable. // Array expansion **DONE. REAL payoff[globs.myXsize]; for(unsigned i=0;i<globs.myXsize;++i) payoff[i] = max(globs.myX[i]-strike, (REAL)0.0); // Already coalesced. for(unsigned i=0;i<globs.myXsize;++i) { // par for(unsigned j=0;j<globs.myYsize;++j) // par globs.myResult[idx2d(i,j,globs.myResultCols)] = payoff[i]; } } //////////////////////////////////////////////////////////////////////// void run_GPU( const unsigned int& outer, const unsigned int& numX, const unsigned int& numY, const unsigned int& numT, const REAL& s0, const REAL& t, const REAL& alpha, const REAL& nu, const REAL& beta, REAL* res // [outer] RESULT ) { PrivGlobs *globs = (PrivGlobs*) malloc(outer*sizeof(struct PrivGlobs)); for(int i = 0 ; i < outer ; i++) { globs[i] = PrivGlobs(numX,numY,numT); } init(globs, outer, s0, alpha, nu, t, numX, numY, numT); for(int i = numT-2;i>=0;--i){ //seq updateWrapper(globs, i, outer, alpha, beta, nu); //rollbackWrapper(globs, i, outer, numX, numY); for( unsigned j = 0; j < outer; ++ j ) { //par // updateParams(i,alpha,beta,nu,globs[j]); rollback(i, globs[j]); } } // parallel assignment of results. for( unsigned j = 0; j < outer; ++ j ) { //par res[j] = globs[j].myResult[idx2d(globs[j].myXindex,globs[j].myYindex,globs[j].myResultCols)]; } }
af4399f368bf8febf1fa62556b24af421f93e9ee.hip
// !!! This is a file automatically generated by hipify!!! /* * Copyright 2020 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. * */ /* * This sample demonstrates stream ordered memory allocation on a GPU using * hipMallocAsync and cudaMemPool family of APIs. * * basicStreamOrderedAllocation(): demonstrates stream ordered allocation using * hipMallocAsync/hipFreeAsync APIs with default settings. * * streamOrderedAllocationPostSync(): demonstrates if there's a synchronization in between allocations, * then setting the release threshold on the pool will make sure the synchronize will not * free memory back to the OS. */ // System includes #include <stdio.h> #include <assert.h> #include <climits> // CUDA runtime #include <hip/hip_runtime.h> // helper functions and utilities to work with CUDA #include "common/helper_functions.h" #include "common/helper_cuda.h" #define MAX_ITER 20 /* Add two vectors on the GPU */ __global__ void vectorAddGPU(const float *a, const float *b, float *c, int N) { int idx = blockIdx.x*blockDim.x + threadIdx.x; if (idx < N) { c[idx] = a[idx] + b[idx]; } } int basicStreamOrderedAllocation(const int dev, const int nelem, const float *a, const float *b, float *c) { float *d_a, *d_b, *d_c; // Device buffers float errorNorm, refNorm, ref, diff; size_t bytes = nelem * sizeof(float); hipStream_t stream; printf("Starting basicStreamOrderedAllocation()\n"); checkCudaErrors(hipSetDevice(dev)); checkCudaErrors(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); checkCudaErrors(hipMallocAsync(&d_a, bytes, stream)); checkCudaErrors(hipMallocAsync(&d_b, bytes, stream)); checkCudaErrors(hipMallocAsync(&d_c, bytes, stream)); checkCudaErrors(hipMemcpyAsync(d_a, a, bytes, hipMemcpyHostToDevice, stream)); checkCudaErrors(hipMemcpyAsync(d_b, b, bytes, hipMemcpyHostToDevice, stream)); dim3 block(256); dim3 grid((unsigned int)ceil(nelem/(float)block.x)); hipLaunchKernelGGL(( vectorAddGPU), dim3(grid), dim3(block), 0, stream, d_a, d_b, d_c, nelem); checkCudaErrors(hipFreeAsync(d_a, stream)); checkCudaErrors(hipFreeAsync(d_b, stream)); checkCudaErrors(hipMemcpyAsync(c, d_c, bytes, hipMemcpyDeviceToHost, stream)); checkCudaErrors(hipFreeAsync(d_c, stream)); checkCudaErrors(hipStreamSynchronize(stream)); /* Compare the results */ printf("> Checking the results from vectorAddGPU() ...\n"); errorNorm = 0.f; refNorm = 0.f; for (int n = 0; n < nelem; n++) { ref = a[n] + b[n]; diff = c[n] - ref; errorNorm += diff*diff; refNorm += ref*ref; } errorNorm = (float)sqrt((double)errorNorm); refNorm = (float)sqrt((double)refNorm); if (errorNorm/refNorm < 1.e-6f) printf("basicStreamOrderedAllocation PASSED\n"); checkCudaErrors(hipStreamDestroy(stream)); return errorNorm/refNorm < 1.e-6f ? EXIT_SUCCESS : EXIT_FAILURE; } // streamOrderedAllocationPostSync(): // demonstrates If the application wants the memory to persist in the pool beyond synchronization, // then it sets the release threshold on the pool. // This way, when the application reaches the "steady state", // it is no longer allocating/freeing memory from the OS. int streamOrderedAllocationPostSync(const int dev, const int nelem, const float *a, const float *b, float *c) { float *d_a, *d_b, *d_c; // Device buffers float errorNorm, refNorm, ref, diff; size_t bytes = nelem * sizeof(float); hipStream_t stream; hipMemPool_t memPool; hipEvent_t start, end; printf("Starting streamOrderedAllocationPostSync()\n"); checkCudaErrors(hipSetDevice(dev)); checkCudaErrors(hipStreamCreateWithFlags(&stream, hipStreamNonBlocking)); checkCudaErrors(hipEventCreate(&start)); checkCudaErrors(hipEventCreate(&end)); checkCudaErrors(hipDeviceGetDefaultMemPool(&memPool, dev)); uint64_t thresholdVal = ULONG_MAX; // set high release threshold on the default pool so that hipFreeAsync will not actually release memory to the system. // By default, the release threshold for a memory pool is set to zero. This implies that the CUDA driver is // allowed to release a memory chunk back to the system as long as it does not contain any active suballocations. checkCudaErrors(hipMemPoolSetAttribute(memPool, hipMemPoolAttrReleaseThreshold, (void*)&thresholdVal)); // Record the start event checkCudaErrors(hipEventRecord(start, stream)); for (int i = 0; i < MAX_ITER; i++) { checkCudaErrors(hipMallocAsync(&d_a, bytes, stream)); checkCudaErrors(hipMallocAsync(&d_b, bytes, stream)); checkCudaErrors(hipMallocAsync(&d_c, bytes, stream)); checkCudaErrors(hipMemcpyAsync(d_a, a, bytes, hipMemcpyHostToDevice, stream)); checkCudaErrors(hipMemcpyAsync(d_b, b, bytes, hipMemcpyHostToDevice, stream)); dim3 block(256); dim3 grid((unsigned int)ceil(nelem/(float)block.x)); hipLaunchKernelGGL(( vectorAddGPU), dim3(grid), dim3(block), 0, stream, d_a, d_b, d_c, nelem); checkCudaErrors(hipFreeAsync(d_a, stream)); checkCudaErrors(hipFreeAsync(d_b, stream)); checkCudaErrors(hipMemcpyAsync(c, d_c, bytes, hipMemcpyDeviceToHost, stream)); checkCudaErrors(hipFreeAsync(d_c, stream)); checkCudaErrors(hipStreamSynchronize(stream)); } checkCudaErrors(hipEventRecord(end, stream)); // Wait for the end event to complete checkCudaErrors(hipEventSynchronize(end)); float msecTotal = 0.0f; checkCudaErrors(hipEventElapsedTime(&msecTotal, start, end)); printf("Total elapsed time = %f ms over %d iterations\n", msecTotal, MAX_ITER); /* Compare the results */ printf("> Checking the results from vectorAddGPU() ...\n"); errorNorm = 0.f; refNorm = 0.f; for (int n = 0; n < nelem; n++) { ref = a[n] + b[n]; diff = c[n] - ref; errorNorm += diff*diff; refNorm += ref*ref; } errorNorm = (float)sqrt((double)errorNorm); refNorm = (float)sqrt((double)refNorm); if (errorNorm/refNorm < 1.e-6f) printf("streamOrderedAllocationPostSync PASSED\n"); checkCudaErrors(hipStreamDestroy(stream)); return errorNorm/refNorm < 1.e-6f ? EXIT_SUCCESS : EXIT_FAILURE; } int main(int argc, char **argv) { int nelem; int dev = 0; // use default device 0 size_t bytes; float *a, *b, *c; // Host if (checkCmdLineFlag(argc, (const char **)argv, "help")) { printf("Usage: streamOrderedAllocation [OPTION]\n\n"); printf("Options:\n"); printf(" --device=[device #] Specify the device to be used\n"); return EXIT_SUCCESS; } dev = findCudaDevice(argc, (const char **)argv); int isMemPoolSupported = 0; checkCudaErrors(hipDeviceGetAttribute(&isMemPoolSupported, hipDeviceAttributeMemoryPoolsSupported, dev)); if (!isMemPoolSupported) { printf("Waiving execution as device does not support Memory Pools\n"); exit(EXIT_WAIVED); } // Allocate CPU memory. nelem = 1048576; bytes = nelem*sizeof(float); a = (float*) malloc(bytes); b = (float*) malloc(bytes); c = (float*) malloc(bytes); /* Initialize the vectors. */ for (int n = 0; n < nelem; n++) { a[n] = rand() / (float)RAND_MAX; b[n] = rand() / (float)RAND_MAX; } int ret1 = basicStreamOrderedAllocation(dev, nelem, a, b, c); int ret2 = streamOrderedAllocationPostSync(dev, nelem, a, b, c); /* Memory clean up */ free(a); free(b); free(c); return ((ret1 == EXIT_SUCCESS && ret2 == EXIT_SUCCESS) ? EXIT_SUCCESS : EXIT_FAILURE); }
af4399f368bf8febf1fa62556b24af421f93e9ee.cu
/* * Copyright 2020 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. * */ /* * This sample demonstrates stream ordered memory allocation on a GPU using * cudaMallocAsync and cudaMemPool family of APIs. * * basicStreamOrderedAllocation(): demonstrates stream ordered allocation using * cudaMallocAsync/cudaFreeAsync APIs with default settings. * * streamOrderedAllocationPostSync(): demonstrates if there's a synchronization in between allocations, * then setting the release threshold on the pool will make sure the synchronize will not * free memory back to the OS. */ // System includes #include <stdio.h> #include <assert.h> #include <climits> // CUDA runtime #include <cuda_runtime.h> // helper functions and utilities to work with CUDA #include "common/helper_functions.h" #include "common/helper_cuda.h" #define MAX_ITER 20 /* Add two vectors on the GPU */ __global__ void vectorAddGPU(const float *a, const float *b, float *c, int N) { int idx = blockIdx.x*blockDim.x + threadIdx.x; if (idx < N) { c[idx] = a[idx] + b[idx]; } } int basicStreamOrderedAllocation(const int dev, const int nelem, const float *a, const float *b, float *c) { float *d_a, *d_b, *d_c; // Device buffers float errorNorm, refNorm, ref, diff; size_t bytes = nelem * sizeof(float); cudaStream_t stream; printf("Starting basicStreamOrderedAllocation()\n"); checkCudaErrors(cudaSetDevice(dev)); checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking)); checkCudaErrors(cudaMallocAsync(&d_a, bytes, stream)); checkCudaErrors(cudaMallocAsync(&d_b, bytes, stream)); checkCudaErrors(cudaMallocAsync(&d_c, bytes, stream)); checkCudaErrors(cudaMemcpyAsync(d_a, a, bytes, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_b, b, bytes, cudaMemcpyHostToDevice, stream)); dim3 block(256); dim3 grid((unsigned int)ceil(nelem/(float)block.x)); vectorAddGPU<<<grid, block, 0, stream>>>(d_a, d_b, d_c, nelem); checkCudaErrors(cudaFreeAsync(d_a, stream)); checkCudaErrors(cudaFreeAsync(d_b, stream)); checkCudaErrors(cudaMemcpyAsync(c, d_c, bytes, cudaMemcpyDeviceToHost, stream)); checkCudaErrors(cudaFreeAsync(d_c, stream)); checkCudaErrors(cudaStreamSynchronize(stream)); /* Compare the results */ printf("> Checking the results from vectorAddGPU() ...\n"); errorNorm = 0.f; refNorm = 0.f; for (int n = 0; n < nelem; n++) { ref = a[n] + b[n]; diff = c[n] - ref; errorNorm += diff*diff; refNorm += ref*ref; } errorNorm = (float)sqrt((double)errorNorm); refNorm = (float)sqrt((double)refNorm); if (errorNorm/refNorm < 1.e-6f) printf("basicStreamOrderedAllocation PASSED\n"); checkCudaErrors(cudaStreamDestroy(stream)); return errorNorm/refNorm < 1.e-6f ? EXIT_SUCCESS : EXIT_FAILURE; } // streamOrderedAllocationPostSync(): // demonstrates If the application wants the memory to persist in the pool beyond synchronization, // then it sets the release threshold on the pool. // This way, when the application reaches the "steady state", // it is no longer allocating/freeing memory from the OS. int streamOrderedAllocationPostSync(const int dev, const int nelem, const float *a, const float *b, float *c) { float *d_a, *d_b, *d_c; // Device buffers float errorNorm, refNorm, ref, diff; size_t bytes = nelem * sizeof(float); cudaStream_t stream; cudaMemPool_t memPool; cudaEvent_t start, end; printf("Starting streamOrderedAllocationPostSync()\n"); checkCudaErrors(cudaSetDevice(dev)); checkCudaErrors(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking)); checkCudaErrors(cudaEventCreate(&start)); checkCudaErrors(cudaEventCreate(&end)); checkCudaErrors(cudaDeviceGetDefaultMemPool(&memPool, dev)); uint64_t thresholdVal = ULONG_MAX; // set high release threshold on the default pool so that cudaFreeAsync will not actually release memory to the system. // By default, the release threshold for a memory pool is set to zero. This implies that the CUDA driver is // allowed to release a memory chunk back to the system as long as it does not contain any active suballocations. checkCudaErrors(cudaMemPoolSetAttribute(memPool, cudaMemPoolAttrReleaseThreshold, (void*)&thresholdVal)); // Record the start event checkCudaErrors(cudaEventRecord(start, stream)); for (int i = 0; i < MAX_ITER; i++) { checkCudaErrors(cudaMallocAsync(&d_a, bytes, stream)); checkCudaErrors(cudaMallocAsync(&d_b, bytes, stream)); checkCudaErrors(cudaMallocAsync(&d_c, bytes, stream)); checkCudaErrors(cudaMemcpyAsync(d_a, a, bytes, cudaMemcpyHostToDevice, stream)); checkCudaErrors(cudaMemcpyAsync(d_b, b, bytes, cudaMemcpyHostToDevice, stream)); dim3 block(256); dim3 grid((unsigned int)ceil(nelem/(float)block.x)); vectorAddGPU<<<grid, block, 0, stream>>>(d_a, d_b, d_c, nelem); checkCudaErrors(cudaFreeAsync(d_a, stream)); checkCudaErrors(cudaFreeAsync(d_b, stream)); checkCudaErrors(cudaMemcpyAsync(c, d_c, bytes, cudaMemcpyDeviceToHost, stream)); checkCudaErrors(cudaFreeAsync(d_c, stream)); checkCudaErrors(cudaStreamSynchronize(stream)); } checkCudaErrors(cudaEventRecord(end, stream)); // Wait for the end event to complete checkCudaErrors(cudaEventSynchronize(end)); float msecTotal = 0.0f; checkCudaErrors(cudaEventElapsedTime(&msecTotal, start, end)); printf("Total elapsed time = %f ms over %d iterations\n", msecTotal, MAX_ITER); /* Compare the results */ printf("> Checking the results from vectorAddGPU() ...\n"); errorNorm = 0.f; refNorm = 0.f; for (int n = 0; n < nelem; n++) { ref = a[n] + b[n]; diff = c[n] - ref; errorNorm += diff*diff; refNorm += ref*ref; } errorNorm = (float)sqrt((double)errorNorm); refNorm = (float)sqrt((double)refNorm); if (errorNorm/refNorm < 1.e-6f) printf("streamOrderedAllocationPostSync PASSED\n"); checkCudaErrors(cudaStreamDestroy(stream)); return errorNorm/refNorm < 1.e-6f ? EXIT_SUCCESS : EXIT_FAILURE; } int main(int argc, char **argv) { int nelem; int dev = 0; // use default device 0 size_t bytes; float *a, *b, *c; // Host if (checkCmdLineFlag(argc, (const char **)argv, "help")) { printf("Usage: streamOrderedAllocation [OPTION]\n\n"); printf("Options:\n"); printf(" --device=[device #] Specify the device to be used\n"); return EXIT_SUCCESS; } dev = findCudaDevice(argc, (const char **)argv); int isMemPoolSupported = 0; checkCudaErrors(cudaDeviceGetAttribute(&isMemPoolSupported, cudaDevAttrMemoryPoolsSupported, dev)); if (!isMemPoolSupported) { printf("Waiving execution as device does not support Memory Pools\n"); exit(EXIT_WAIVED); } // Allocate CPU memory. nelem = 1048576; bytes = nelem*sizeof(float); a = (float*) malloc(bytes); b = (float*) malloc(bytes); c = (float*) malloc(bytes); /* Initialize the vectors. */ for (int n = 0; n < nelem; n++) { a[n] = rand() / (float)RAND_MAX; b[n] = rand() / (float)RAND_MAX; } int ret1 = basicStreamOrderedAllocation(dev, nelem, a, b, c); int ret2 = streamOrderedAllocationPostSync(dev, nelem, a, b, c); /* Memory clean up */ free(a); free(b); free(c); return ((ret1 == EXIT_SUCCESS && ret2 == EXIT_SUCCESS) ? EXIT_SUCCESS : EXIT_FAILURE); }
7965dad0a9b6d6ad53ae3f204ae7751886753f96.hip
// !!! This is a file automatically generated by hipify!!! /** * Copyright 1993-2015 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. * */ //////////////////////////////////////////////////////////////////////////////// // // simpleCUFFT_2d_MGPU.cu // // This sample code demonstrate the use of CUFFT library for 2D data on multiple GPU. // Example showing the use of CUFFT for solving 2D-POISSON equation using FFT on multiple GPU. // For reference we have used the equation given in http://www.bu.edu/pasi/files/2011/07/ // Lecture83.pdf // //////////////////////////////////////////////////////////////////////////////// // System includes #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // CUDA runtime #include <hip/hip_runtime.h> //CUFFT Header file #include <hipfftXt.h> // helper functions and utilities to work with CUDA #include <helper_functions.h> #include <helper_cuda.h> // Complex data type typedef float2 Complex; // Data configuration const int GPU_COUNT = 2; const int BSZ_Y = 4; const int BSZ_X = 4; // Forward Declaration void solvePoissonEquation(cudaLibXtDesc *, cudaLibXtDesc *, float **, int, int ); __global__ void solvePoisson(hipfftComplex *, hipfftComplex *, float *, int, int, int n_gpu); /////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { printf("\nPoisson equation using CUFFT library on Multiple GPU is starting...\n\n"); int GPU_N ; checkCudaErrors(hipGetDeviceCount(&GPU_N)); if (GPU_N < GPU_COUNT) { printf("No. of GPU on node %d\n", GPU_N); printf("Two GPUs are required to run simpleCUFFT_2d_MGPU sample code\n"); exit(EXIT_WAIVED); } int N = 64; float xMAX = 1.0f, xMIN = 0.0f, yMIN = 0.0f,h = (xMAX - xMIN)/((float)N), s = 0.1, s2 = s*s; float *x, *y, *f, *u_a, r2; x = (float*)malloc(sizeof(float) *N*N); y = (float*)malloc(sizeof(float) *N*N); f = (float*)malloc(sizeof(float) *N*N); u_a = (float*)malloc(sizeof(float) *N*N); for (int j=0; j<N; j++) for (int i=0; i<N; i++) { x[N*j+i] = xMIN + i*h; y[N*j+i] = yMIN + j*h; r2 = (x[N*j+i] - 0.5)*(x[N*j+i] - 0.5) + (y[N*j+i] - 0.5)*(y[N*j+i] - 0.5); f[N*j+i] = (r2-2*s2)/(s2*s2)*exp(-r2/(2*s2)); u_a[N*j+i] = exp(-r2/(2*s2)); // analytical solution } float *k, *d_k[GPU_COUNT]; k = (float*)malloc(sizeof(float) *N); for (int i=0; i<=N/2; i++) { k[i] = i * 2*M_PI; } for (int i=N/2+1; i<N; i++) { k[i] = (i - N) * 2*M_PI; } //Create a complex variable on host Complex *h_f = (Complex *)malloc(sizeof(Complex) * N * N); // Initalize the memory for the signal for ( int i = 0; i < (N * N); i++) { h_f[i].x = f[i]; h_f[i].y = 0.0f; } // hipfftCreate() - Create an empty plan hipfftResult result; hipfftHandle planComplex; result = hipfftCreate(&planComplex); if (result != HIPFFT_SUCCESS) { printf ("hipfftCreate failed\n"); exit (EXIT_FAILURE); } // cufftXtSetGPUs() - Define which GPUs to use int nGPUs = 2; int *whichGPUs ; whichGPUs = (int*) malloc(sizeof(int) * nGPUs); // Iterate all device combinations to see if a supported combo exists for (int i = 0; i < GPU_N; i++) { for (int j = i+1; j < GPU_N; j++) { whichGPUs[0] = i; whichGPUs[1] = j; result = cufftXtSetGPUs (planComplex, nGPUs, whichGPUs); if (result == HIPFFT_INVALID_DEVICE) { continue; } else if (result == HIPFFT_SUCCESS) { break; } else { printf ("cufftXtSetGPUs failed\n"); exit (EXIT_FAILURE); } } if (result == HIPFFT_SUCCESS) { break; } } if (result == HIPFFT_INVALID_DEVICE) { printf ("This sample requires two GPUs on the same board.\n"); printf ("No such board was found. Waiving sample.\n"); exit (EXIT_WAIVED); } //Print the device information to run the code for (int i = 0 ; i < 2 ; i++) { hipDeviceProp_t deviceProp; checkCudaErrors(hipGetDeviceProperties(&deviceProp, whichGPUs[i])); printf("GPU Device %d: \"%s\" with compute capability %d.%d\n", whichGPUs[i], deviceProp.name, deviceProp.major, deviceProp.minor); } result = cufftXtSetGPUs (planComplex, nGPUs, whichGPUs); if (result != HIPFFT_SUCCESS) { printf ("cufftXtSetGPUs failed\n"); exit (EXIT_FAILURE) ; } size_t* worksize; worksize =(size_t*)malloc(sizeof(size_t) * nGPUs); // hipfftMakePlan2d() - Create the plan result = hipfftMakePlan2d(planComplex, N, N, HIPFFT_C2C, worksize); if (result != HIPFFT_SUCCESS) { printf ("*MakePlan* failed\n"); exit (EXIT_FAILURE) ; } for(int i=0; i<nGPUs; i++) { hipSetDevice(whichGPUs[i]); hipMalloc ((void**)&d_k[i], sizeof(float)*N); hipMemcpy(d_k[i], k, sizeof(float)*N, hipMemcpyHostToDevice); } // Create a variable on device // d_f - variable on device to store the input data // d_d_f - variable that store the natural order of d_f data // d_out - device output cudaLibXtDesc *d_f,*d_d_f, *d_out ; // cufftXtMalloc() - Malloc data on multiple GPUs result = cufftXtMalloc (planComplex, (cudaLibXtDesc **)&d_f, CUFFT_XT_FORMAT_INPLACE); if (result != HIPFFT_SUCCESS) { printf ("*XtMalloc failed\n"); exit (EXIT_FAILURE) ; } result = cufftXtMalloc (planComplex, (cudaLibXtDesc **)&d_d_f, CUFFT_XT_FORMAT_INPLACE); if (result != HIPFFT_SUCCESS) { printf ("*XtMalloc failed\n"); exit (EXIT_FAILURE) ; } result = cufftXtMalloc (planComplex, (cudaLibXtDesc **)&d_out, CUFFT_XT_FORMAT_INPLACE); if (result != HIPFFT_SUCCESS) { printf ("*XtMalloc failed\n"); exit (EXIT_FAILURE) ; } // cufftXtMemcpy() - Copy the data from host to device result = cufftXtMemcpy (planComplex, d_f, h_f, CUFFT_COPY_HOST_TO_DEVICE); if (result != HIPFFT_SUCCESS) { printf ("*XtMemcpy failed\n"); exit (EXIT_FAILURE); } // cufftXtExecDescriptorC2C() - Execute FFT on data on multiple GPUs printf("Forward 2d FFT on multiple GPU\n"); result = cufftXtExecDescriptorC2C(planComplex, d_f, d_f, HIPFFT_FORWARD); if (result != HIPFFT_SUCCESS) { printf ("*XtExecC2C failed\n"); exit (EXIT_FAILURE); } //cufftXtMemcpy() - Copy the data to natural order on GPUs result = cufftXtMemcpy (planComplex, d_d_f, d_f, CUFFT_COPY_DEVICE_TO_DEVICE); if (result != HIPFFT_SUCCESS) { printf ("*XtMemcpy failed\n"); exit (EXIT_FAILURE); } printf("Solve Poisson Equation\n" ); solvePoissonEquation(d_d_f, d_out, d_k, N, nGPUs); printf("Inverse 2d FFT on multiple GPU\n"); // cufftXtExecDescriptorC2C() - Execute inverse FFT on data on multiple GPUs result = cufftXtExecDescriptorC2C(planComplex, d_out, d_out, HIPFFT_BACKWARD); if (result != HIPFFT_SUCCESS) { printf ("*XtExecC2C failed\n"); exit (EXIT_FAILURE); } //Create a variable on host to copy the data from device //h_d_out - variable store the output of device Complex *h_d_out = (Complex *)malloc(sizeof(Complex) * N * N); // cufftXtMemcpy() - Copy data from multiple GPUs to host result = cufftXtMemcpy (planComplex,h_d_out, d_out, CUFFT_COPY_DEVICE_TO_HOST); if (result != HIPFFT_SUCCESS) { printf ("*XtMemcpy failed\n"); exit (EXIT_FAILURE); } float *out = (float *)malloc(sizeof(float) * N * N); float constant = h_d_out[0].x / N* N ; for (int i=0; i<N*N; i++) { //substract u[0] to force the arbitrary constant to be 0 out[i] = (h_d_out[i].x / (N*N)) - constant; } // cleanup memory free(h_f); free(k); free(out); free(h_d_out); free(x); free(whichGPUs); free(y); free(f); free(u_a); free(worksize); // cudaXtFree() - Free GPU memory for (int i=0; i<GPU_COUNT; i++) { hipFree(d_k[i]); } result = cufftXtFree(d_out); if (result != HIPFFT_SUCCESS) { printf ("*XtFree failed\n"); exit (EXIT_FAILURE); } result = cufftXtFree(d_f); if (result != HIPFFT_SUCCESS) { printf ("*XtFree failed\n"); exit (EXIT_FAILURE); } result = cufftXtFree(d_d_f); if (result != HIPFFT_SUCCESS) { printf ("*XtFree failed\n"); exit (EXIT_FAILURE); } // hipfftDestroy() - Destroy FFT plan result = hipfftDestroy(planComplex); if (result != HIPFFT_SUCCESS) { printf ("hipfftDestroy failed: code %d\n",(int)result); exit (EXIT_FAILURE); } hipDeviceReset(); exit(EXIT_SUCCESS); } //////////////////////////////////////////////////////////////////////////////////// //Launch kernel on multiple GPU /////////////////////////////////////////////////////////////////////////////////// void solvePoissonEquation(cudaLibXtDesc *d_ft,cudaLibXtDesc *d_ft_k, float **k, int N, int nGPUs) { int device ; dim3 dimGrid (int(N/BSZ_X), int((N/2)/BSZ_Y)); dim3 dimBlock (BSZ_X, BSZ_Y); for(int i=0; i < nGPUs ; i++) { device = d_ft_k->descriptor->GPUs[i]; hipSetDevice(device) ; hipLaunchKernelGGL(( solvePoisson), dim3(dimGrid),dim3(dimBlock), 0, 0, (hipfftComplex*) d_ft->descriptor->data[i], (hipfftComplex*) d_ft_k->descriptor->data[i], k[i], N, i, nGPUs); } // Wait for device to finish all operation for(int i=0; i< nGPUs ; i++) { device = d_ft_k->descriptor->GPUs[i]; hipSetDevice( device ); hipDeviceSynchronize(); // Check if kernel execution generated and error getLastCudaError("Kernel execution failed [ so`lvePoisson ]"); } } //////////////////////////////////////////////////////////////////////////////// // Kernel for Solving Poisson equation on GPU //////////////////////////////////////////////////////////////////////////////// __global__ void solvePoisson(hipfftComplex *ft, hipfftComplex *ft_k, float *k, int N ,int gpu_id, int n_gpu) { int i = threadIdx.x + blockIdx.x*blockDim.x; int j = threadIdx.y + blockIdx.y*blockDim.y; int index = j*N+i; if (i<N && j<N/n_gpu) { float k2 = k[i]*k[i] + k[j + gpu_id*N/n_gpu]*k[j + gpu_id*N/n_gpu]; if (i==0 && j==0 && gpu_id == 0) { k2 = 1.0f; } ft_k[index].x = -ft[index].x*1/k2; ft_k[index].y = -ft[index].y*1/k2; } }
7965dad0a9b6d6ad53ae3f204ae7751886753f96.cu
/** * Copyright 1993-2015 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. * */ //////////////////////////////////////////////////////////////////////////////// // // simpleCUFFT_2d_MGPU.cu // // This sample code demonstrate the use of CUFFT library for 2D data on multiple GPU. // Example showing the use of CUFFT for solving 2D-POISSON equation using FFT on multiple GPU. // For reference we have used the equation given in http://www.bu.edu/pasi/files/2011/07/ // Lecture83.pdf // //////////////////////////////////////////////////////////////////////////////// // System includes #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> // CUDA runtime #include <cuda_runtime.h> //CUFFT Header file #include <cufftXt.h> // helper functions and utilities to work with CUDA #include <helper_functions.h> #include <helper_cuda.h> // Complex data type typedef float2 Complex; // Data configuration const int GPU_COUNT = 2; const int BSZ_Y = 4; const int BSZ_X = 4; // Forward Declaration void solvePoissonEquation(cudaLibXtDesc *, cudaLibXtDesc *, float **, int, int ); __global__ void solvePoisson(cufftComplex *, cufftComplex *, float *, int, int, int n_gpu); /////////////////////////////////////////////////////////////////////////////// // Program main //////////////////////////////////////////////////////////////////////////////// int main(int argc, char **argv) { printf("\nPoisson equation using CUFFT library on Multiple GPU is starting...\n\n"); int GPU_N ; checkCudaErrors(cudaGetDeviceCount(&GPU_N)); if (GPU_N < GPU_COUNT) { printf("No. of GPU on node %d\n", GPU_N); printf("Two GPUs are required to run simpleCUFFT_2d_MGPU sample code\n"); exit(EXIT_WAIVED); } int N = 64; float xMAX = 1.0f, xMIN = 0.0f, yMIN = 0.0f,h = (xMAX - xMIN)/((float)N), s = 0.1, s2 = s*s; float *x, *y, *f, *u_a, r2; x = (float*)malloc(sizeof(float) *N*N); y = (float*)malloc(sizeof(float) *N*N); f = (float*)malloc(sizeof(float) *N*N); u_a = (float*)malloc(sizeof(float) *N*N); for (int j=0; j<N; j++) for (int i=0; i<N; i++) { x[N*j+i] = xMIN + i*h; y[N*j+i] = yMIN + j*h; r2 = (x[N*j+i] - 0.5)*(x[N*j+i] - 0.5) + (y[N*j+i] - 0.5)*(y[N*j+i] - 0.5); f[N*j+i] = (r2-2*s2)/(s2*s2)*exp(-r2/(2*s2)); u_a[N*j+i] = exp(-r2/(2*s2)); // analytical solution } float *k, *d_k[GPU_COUNT]; k = (float*)malloc(sizeof(float) *N); for (int i=0; i<=N/2; i++) { k[i] = i * 2*M_PI; } for (int i=N/2+1; i<N; i++) { k[i] = (i - N) * 2*M_PI; } //Create a complex variable on host Complex *h_f = (Complex *)malloc(sizeof(Complex) * N * N); // Initalize the memory for the signal for ( int i = 0; i < (N * N); i++) { h_f[i].x = f[i]; h_f[i].y = 0.0f; } // cufftCreate() - Create an empty plan cufftResult result; cufftHandle planComplex; result = cufftCreate(&planComplex); if (result != CUFFT_SUCCESS) { printf ("cufftCreate failed\n"); exit (EXIT_FAILURE); } // cufftXtSetGPUs() - Define which GPUs to use int nGPUs = 2; int *whichGPUs ; whichGPUs = (int*) malloc(sizeof(int) * nGPUs); // Iterate all device combinations to see if a supported combo exists for (int i = 0; i < GPU_N; i++) { for (int j = i+1; j < GPU_N; j++) { whichGPUs[0] = i; whichGPUs[1] = j; result = cufftXtSetGPUs (planComplex, nGPUs, whichGPUs); if (result == CUFFT_INVALID_DEVICE) { continue; } else if (result == CUFFT_SUCCESS) { break; } else { printf ("cufftXtSetGPUs failed\n"); exit (EXIT_FAILURE); } } if (result == CUFFT_SUCCESS) { break; } } if (result == CUFFT_INVALID_DEVICE) { printf ("This sample requires two GPUs on the same board.\n"); printf ("No such board was found. Waiving sample.\n"); exit (EXIT_WAIVED); } //Print the device information to run the code for (int i = 0 ; i < 2 ; i++) { cudaDeviceProp deviceProp; checkCudaErrors(cudaGetDeviceProperties(&deviceProp, whichGPUs[i])); printf("GPU Device %d: \"%s\" with compute capability %d.%d\n", whichGPUs[i], deviceProp.name, deviceProp.major, deviceProp.minor); } result = cufftXtSetGPUs (planComplex, nGPUs, whichGPUs); if (result != CUFFT_SUCCESS) { printf ("cufftXtSetGPUs failed\n"); exit (EXIT_FAILURE) ; } size_t* worksize; worksize =(size_t*)malloc(sizeof(size_t) * nGPUs); // cufftMakePlan2d() - Create the plan result = cufftMakePlan2d(planComplex, N, N, CUFFT_C2C, worksize); if (result != CUFFT_SUCCESS) { printf ("*MakePlan* failed\n"); exit (EXIT_FAILURE) ; } for(int i=0; i<nGPUs; i++) { cudaSetDevice(whichGPUs[i]); cudaMalloc ((void**)&d_k[i], sizeof(float)*N); cudaMemcpy(d_k[i], k, sizeof(float)*N, cudaMemcpyHostToDevice); } // Create a variable on device // d_f - variable on device to store the input data // d_d_f - variable that store the natural order of d_f data // d_out - device output cudaLibXtDesc *d_f,*d_d_f, *d_out ; // cufftXtMalloc() - Malloc data on multiple GPUs result = cufftXtMalloc (planComplex, (cudaLibXtDesc **)&d_f, CUFFT_XT_FORMAT_INPLACE); if (result != CUFFT_SUCCESS) { printf ("*XtMalloc failed\n"); exit (EXIT_FAILURE) ; } result = cufftXtMalloc (planComplex, (cudaLibXtDesc **)&d_d_f, CUFFT_XT_FORMAT_INPLACE); if (result != CUFFT_SUCCESS) { printf ("*XtMalloc failed\n"); exit (EXIT_FAILURE) ; } result = cufftXtMalloc (planComplex, (cudaLibXtDesc **)&d_out, CUFFT_XT_FORMAT_INPLACE); if (result != CUFFT_SUCCESS) { printf ("*XtMalloc failed\n"); exit (EXIT_FAILURE) ; } // cufftXtMemcpy() - Copy the data from host to device result = cufftXtMemcpy (planComplex, d_f, h_f, CUFFT_COPY_HOST_TO_DEVICE); if (result != CUFFT_SUCCESS) { printf ("*XtMemcpy failed\n"); exit (EXIT_FAILURE); } // cufftXtExecDescriptorC2C() - Execute FFT on data on multiple GPUs printf("Forward 2d FFT on multiple GPU\n"); result = cufftXtExecDescriptorC2C(planComplex, d_f, d_f, CUFFT_FORWARD); if (result != CUFFT_SUCCESS) { printf ("*XtExecC2C failed\n"); exit (EXIT_FAILURE); } //cufftXtMemcpy() - Copy the data to natural order on GPUs result = cufftXtMemcpy (planComplex, d_d_f, d_f, CUFFT_COPY_DEVICE_TO_DEVICE); if (result != CUFFT_SUCCESS) { printf ("*XtMemcpy failed\n"); exit (EXIT_FAILURE); } printf("Solve Poisson Equation\n" ); solvePoissonEquation(d_d_f, d_out, d_k, N, nGPUs); printf("Inverse 2d FFT on multiple GPU\n"); // cufftXtExecDescriptorC2C() - Execute inverse FFT on data on multiple GPUs result = cufftXtExecDescriptorC2C(planComplex, d_out, d_out, CUFFT_INVERSE); if (result != CUFFT_SUCCESS) { printf ("*XtExecC2C failed\n"); exit (EXIT_FAILURE); } //Create a variable on host to copy the data from device //h_d_out - variable store the output of device Complex *h_d_out = (Complex *)malloc(sizeof(Complex) * N * N); // cufftXtMemcpy() - Copy data from multiple GPUs to host result = cufftXtMemcpy (planComplex,h_d_out, d_out, CUFFT_COPY_DEVICE_TO_HOST); if (result != CUFFT_SUCCESS) { printf ("*XtMemcpy failed\n"); exit (EXIT_FAILURE); } float *out = (float *)malloc(sizeof(float) * N * N); float constant = h_d_out[0].x / N* N ; for (int i=0; i<N*N; i++) { //substract u[0] to force the arbitrary constant to be 0 out[i] = (h_d_out[i].x / (N*N)) - constant; } // cleanup memory free(h_f); free(k); free(out); free(h_d_out); free(x); free(whichGPUs); free(y); free(f); free(u_a); free(worksize); // cudaXtFree() - Free GPU memory for (int i=0; i<GPU_COUNT; i++) { cudaFree(d_k[i]); } result = cufftXtFree(d_out); if (result != CUFFT_SUCCESS) { printf ("*XtFree failed\n"); exit (EXIT_FAILURE); } result = cufftXtFree(d_f); if (result != CUFFT_SUCCESS) { printf ("*XtFree failed\n"); exit (EXIT_FAILURE); } result = cufftXtFree(d_d_f); if (result != CUFFT_SUCCESS) { printf ("*XtFree failed\n"); exit (EXIT_FAILURE); } // cufftDestroy() - Destroy FFT plan result = cufftDestroy(planComplex); if (result != CUFFT_SUCCESS) { printf ("cufftDestroy failed: code %d\n",(int)result); exit (EXIT_FAILURE); } cudaDeviceReset(); exit(EXIT_SUCCESS); } //////////////////////////////////////////////////////////////////////////////////// //Launch kernel on multiple GPU /////////////////////////////////////////////////////////////////////////////////// void solvePoissonEquation(cudaLibXtDesc *d_ft,cudaLibXtDesc *d_ft_k, float **k, int N, int nGPUs) { int device ; dim3 dimGrid (int(N/BSZ_X), int((N/2)/BSZ_Y)); dim3 dimBlock (BSZ_X, BSZ_Y); for(int i=0; i < nGPUs ; i++) { device = d_ft_k->descriptor->GPUs[i]; cudaSetDevice(device) ; solvePoisson<<<dimGrid,dimBlock>>>((cufftComplex*) d_ft->descriptor->data[i], (cufftComplex*) d_ft_k->descriptor->data[i], k[i], N, i, nGPUs); } // Wait for device to finish all operation for(int i=0; i< nGPUs ; i++) { device = d_ft_k->descriptor->GPUs[i]; cudaSetDevice( device ); cudaDeviceSynchronize(); // Check if kernel execution generated and error getLastCudaError("Kernel execution failed [ so`lvePoisson ]"); } } //////////////////////////////////////////////////////////////////////////////// // Kernel for Solving Poisson equation on GPU //////////////////////////////////////////////////////////////////////////////// __global__ void solvePoisson(cufftComplex *ft, cufftComplex *ft_k, float *k, int N ,int gpu_id, int n_gpu) { int i = threadIdx.x + blockIdx.x*blockDim.x; int j = threadIdx.y + blockIdx.y*blockDim.y; int index = j*N+i; if (i<N && j<N/n_gpu) { float k2 = k[i]*k[i] + k[j + gpu_id*N/n_gpu]*k[j + gpu_id*N/n_gpu]; if (i==0 && j==0 && gpu_id == 0) { k2 = 1.0f; } ft_k[index].x = -ft[index].x*1/k2; ft_k[index].y = -ft[index].y*1/k2; } }
b301ef72f1eb078556f70de0cefbef7367f7cf25.hip
// !!! This is a file automatically generated by hipify!!! /* Baseline 1 : Thut ton Radix Sort tun t */ #include <stdio.h> #include <stdint.h> #define CHECK(call) \ { \ const hipError_t error = call; \ if (error != hipSuccess) \ { \ fprintf(stderr, "Error: %s:%d, ", __FILE__, __LINE__); \ fprintf(stderr, "code: %d, reason: %s\n", error, \ hipGetErrorString(error)); \ exit(1); \ } \ } struct GpuTimer { hipEvent_t start; hipEvent_t stop; GpuTimer() { hipEventCreate(&start); hipEventCreate(&stop); } ~GpuTimer() { hipEventDestroy(start); hipEventDestroy(stop); } void Start() { hipEventRecord(start, 0); hipEventSynchronize(start); } void Stop() { hipEventRecord(stop, 0); } float Elapsed() { float elapsed; hipEventSynchronize(stop); hipEventElapsedTime(&elapsed, start, stop); return elapsed; } }; // Base 1 void sortByHost(const uint32_t * in, int n, uint32_t * out) { int nBits = 1; // Assume: nBits in {1, 2, 4, 8, 16} int nBins = 1 << nBits; // 2^nBits int * hist = (int *)malloc(nBins * sizeof(int)); int * histScan = (int *)malloc(nBins * sizeof(int)); uint32_t * src = (uint32_t *)malloc(n * sizeof(uint32_t)); memcpy(src, in, n * sizeof(uint32_t)); uint32_t * dst = out; // Loop from LSD (Least Significant Digit) to MSD (Most Significant Digit) // (Each digit consists of nBits bit) // In each loop, sort elements according to the current digit from src to dst // (using STABLE counting sort) for (int bit = 0; bit < sizeof(uint32_t) * 8; bit += nBits) { // TODO: Compute histogram memset(hist, 0, nBins * sizeof(int)); for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); hist[bin]++; } // TODO: Scan histogram (exclusively) histScan[0] = 0; for (int bin = 1; bin < nBins; bin++) histScan[bin] = histScan[bin - 1] + hist[bin - 1]; // TODO: Scatter elements to correct locations for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); dst[histScan[bin]] = src[i]; histScan[bin]++; } // Swap src and dst uint32_t * temp = src; src = dst; dst = temp; } // Copy result to out memcpy(out, src, n * sizeof(uint32_t)); } // Parallel Radix Sort void sortByDevice(const uint32_t * in, int n, uint32_t * out, int blockSize) { // TODO int nBits = 1; // Assume: nBits in {1, 2, 4, 8, 16} int nBins = 1 << nBits; // 2^nBits int * hist = (int *)malloc(nBins * sizeof(int)); int * histScan = (int *)malloc(nBins * sizeof(int)); uint32_t * src = (uint32_t *)malloc(n * sizeof(uint32_t)); memcpy(src, in, n * sizeof(uint32_t)); uint32_t * dst = out; // Loop from LSD (Least Significant Digit) to MSD (Most Significant Digit) // (Each digit consists of nBits bit) // In each loop, sort elements according to the current digit from src to dst // (using STABLE counting sort) for (int bit = 0; bit < sizeof(uint32_t) * 8; bit += nBits) { // TODO: Compute histogram memset(hist, 0, nBins * sizeof(int)); for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); hist[bin]++; } // TODO: Scan histogram (exclusively) histScan[0] = 0; for (int bin = 1; bin < nBins; bin++) histScan[bin] = histScan[bin - 1] + hist[bin - 1]; // TODO: Scatter elements to correct locations for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); dst[histScan[bin]] = src[i]; histScan[bin]++; } // Swap src and dst uint32_t * temp = src; src = dst; dst = temp; } // Copy result to out memcpy(out, src, n * sizeof(uint32_t)); } // Radix Sort void sort(const uint32_t * in, int n, uint32_t * out, bool useDevice=false, int blockSize=1) { GpuTimer timer; timer.Start(); if (useDevice == false) { printf("\nRadix Sort by host\n"); sortByHost(in, n, out); } else // use device { printf("\nRadix Sort by device\n"); sortByDevice(in, n, out, blockSize); } timer.Stop(); printf("Time: %.3f ms\n", timer.Elapsed()); } void printDeviceInfo() { hipDeviceProp_t devProv; CHECK(hipGetDeviceProperties(&devProv, 0)); printf("**********GPU info**********\n"); printf("Name: %s\n", devProv.name); printf("Compute capability: %d.%d\n", devProv.major, devProv.minor); printf("Num SMs: %d\n", devProv.multiProcessorCount); printf("Max num threads per SM: %d\n", devProv.maxThreadsPerMultiProcessor); printf("Max num warps per SM: %d\n", devProv.maxThreadsPerMultiProcessor / devProv.warpSize); printf("GMEM: %zu byte\n", devProv.totalGlobalMem); printf("SMEM per SM: %zu byte\n", devProv.sharedMemPerMultiprocessor); printf("SMEM per block: %zu byte\n", devProv.sharedMemPerBlock); printf("****************************\n"); } void checkCorrectness(uint32_t * out, uint32_t * correctOut, int n) { for (int i = 0; i < n; i++) { if (out[i] != correctOut[i]) { printf("INCORRECT :(\n"); return; } } printf("CORRECT :)\n"); } void printArray(uint32_t * a, int n) { for (int i = 0; i < n; i++) printf("%i ", a[i]); printf("\n"); } int main(int argc, char ** argv) { // PRINT OUT DEVICE INFO printDeviceInfo(); // SET UP INPUT SIZE int n = (1 << 24) + 1; // For test by eye //int n = (1 << 24) + 1; printf("\nInput size: %d\n", n); // ALLOCATE MEMORIES size_t bytes = n * sizeof(uint32_t); uint32_t * in = (uint32_t *)malloc(bytes); uint32_t * out = (uint32_t *)malloc(bytes); // Device result uint32_t * correctOut = (uint32_t *)malloc(bytes); // Host result // SET UP INPUT DATA for (int i = 0; i < n; i++) { in[i] = rand() % 255; // For test by eye //in[i] = rand(); } //printArray(in, n); // For test by eye // DETERMINE BLOCK SIZE int blockSize = 512; // Default if (argc == 2) blockSize = atoi(argv[1]); // SORT BY HOST sort(in, n, correctOut); //printArray(correctOut, n); // SORT BY DEVICE sort(in, n, out, true, blockSize); checkCorrectness(out, correctOut, n); // FREE MEMORIES free(in); free(out); free(correctOut); return EXIT_SUCCESS; }
b301ef72f1eb078556f70de0cefbef7367f7cf25.cu
/* Baseline 1 : Thuật toán Radix Sort tuần tự */ #include <stdio.h> #include <stdint.h> #define CHECK(call) \ { \ const cudaError_t error = call; \ if (error != cudaSuccess) \ { \ fprintf(stderr, "Error: %s:%d, ", __FILE__, __LINE__); \ fprintf(stderr, "code: %d, reason: %s\n", error, \ cudaGetErrorString(error)); \ exit(1); \ } \ } struct GpuTimer { cudaEvent_t start; cudaEvent_t stop; GpuTimer() { cudaEventCreate(&start); cudaEventCreate(&stop); } ~GpuTimer() { cudaEventDestroy(start); cudaEventDestroy(stop); } void Start() { cudaEventRecord(start, 0); cudaEventSynchronize(start); } void Stop() { cudaEventRecord(stop, 0); } float Elapsed() { float elapsed; cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsed, start, stop); return elapsed; } }; // Base 1 void sortByHost(const uint32_t * in, int n, uint32_t * out) { int nBits = 1; // Assume: nBits in {1, 2, 4, 8, 16} int nBins = 1 << nBits; // 2^nBits int * hist = (int *)malloc(nBins * sizeof(int)); int * histScan = (int *)malloc(nBins * sizeof(int)); uint32_t * src = (uint32_t *)malloc(n * sizeof(uint32_t)); memcpy(src, in, n * sizeof(uint32_t)); uint32_t * dst = out; // Loop from LSD (Least Significant Digit) to MSD (Most Significant Digit) // (Each digit consists of nBits bit) // In each loop, sort elements according to the current digit from src to dst // (using STABLE counting sort) for (int bit = 0; bit < sizeof(uint32_t) * 8; bit += nBits) { // TODO: Compute histogram memset(hist, 0, nBins * sizeof(int)); for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); hist[bin]++; } // TODO: Scan histogram (exclusively) histScan[0] = 0; for (int bin = 1; bin < nBins; bin++) histScan[bin] = histScan[bin - 1] + hist[bin - 1]; // TODO: Scatter elements to correct locations for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); dst[histScan[bin]] = src[i]; histScan[bin]++; } // Swap src and dst uint32_t * temp = src; src = dst; dst = temp; } // Copy result to out memcpy(out, src, n * sizeof(uint32_t)); } // Parallel Radix Sort void sortByDevice(const uint32_t * in, int n, uint32_t * out, int blockSize) { // TODO int nBits = 1; // Assume: nBits in {1, 2, 4, 8, 16} int nBins = 1 << nBits; // 2^nBits int * hist = (int *)malloc(nBins * sizeof(int)); int * histScan = (int *)malloc(nBins * sizeof(int)); uint32_t * src = (uint32_t *)malloc(n * sizeof(uint32_t)); memcpy(src, in, n * sizeof(uint32_t)); uint32_t * dst = out; // Loop from LSD (Least Significant Digit) to MSD (Most Significant Digit) // (Each digit consists of nBits bit) // In each loop, sort elements according to the current digit from src to dst // (using STABLE counting sort) for (int bit = 0; bit < sizeof(uint32_t) * 8; bit += nBits) { // TODO: Compute histogram memset(hist, 0, nBins * sizeof(int)); for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); hist[bin]++; } // TODO: Scan histogram (exclusively) histScan[0] = 0; for (int bin = 1; bin < nBins; bin++) histScan[bin] = histScan[bin - 1] + hist[bin - 1]; // TODO: Scatter elements to correct locations for (int i = 0; i < n; i++) { int bin = (src[i] >> bit) & (nBins - 1); dst[histScan[bin]] = src[i]; histScan[bin]++; } // Swap src and dst uint32_t * temp = src; src = dst; dst = temp; } // Copy result to out memcpy(out, src, n * sizeof(uint32_t)); } // Radix Sort void sort(const uint32_t * in, int n, uint32_t * out, bool useDevice=false, int blockSize=1) { GpuTimer timer; timer.Start(); if (useDevice == false) { printf("\nRadix Sort by host\n"); sortByHost(in, n, out); } else // use device { printf("\nRadix Sort by device\n"); sortByDevice(in, n, out, blockSize); } timer.Stop(); printf("Time: %.3f ms\n", timer.Elapsed()); } void printDeviceInfo() { cudaDeviceProp devProv; CHECK(cudaGetDeviceProperties(&devProv, 0)); printf("**********GPU info**********\n"); printf("Name: %s\n", devProv.name); printf("Compute capability: %d.%d\n", devProv.major, devProv.minor); printf("Num SMs: %d\n", devProv.multiProcessorCount); printf("Max num threads per SM: %d\n", devProv.maxThreadsPerMultiProcessor); printf("Max num warps per SM: %d\n", devProv.maxThreadsPerMultiProcessor / devProv.warpSize); printf("GMEM: %zu byte\n", devProv.totalGlobalMem); printf("SMEM per SM: %zu byte\n", devProv.sharedMemPerMultiprocessor); printf("SMEM per block: %zu byte\n", devProv.sharedMemPerBlock); printf("****************************\n"); } void checkCorrectness(uint32_t * out, uint32_t * correctOut, int n) { for (int i = 0; i < n; i++) { if (out[i] != correctOut[i]) { printf("INCORRECT :(\n"); return; } } printf("CORRECT :)\n"); } void printArray(uint32_t * a, int n) { for (int i = 0; i < n; i++) printf("%i ", a[i]); printf("\n"); } int main(int argc, char ** argv) { // PRINT OUT DEVICE INFO printDeviceInfo(); // SET UP INPUT SIZE int n = (1 << 24) + 1; // For test by eye //int n = (1 << 24) + 1; printf("\nInput size: %d\n", n); // ALLOCATE MEMORIES size_t bytes = n * sizeof(uint32_t); uint32_t * in = (uint32_t *)malloc(bytes); uint32_t * out = (uint32_t *)malloc(bytes); // Device result uint32_t * correctOut = (uint32_t *)malloc(bytes); // Host result // SET UP INPUT DATA for (int i = 0; i < n; i++) { in[i] = rand() % 255; // For test by eye //in[i] = rand(); } //printArray(in, n); // For test by eye // DETERMINE BLOCK SIZE int blockSize = 512; // Default if (argc == 2) blockSize = atoi(argv[1]); // SORT BY HOST sort(in, n, correctOut); //printArray(correctOut, n); // SORT BY DEVICE sort(in, n, out, true, blockSize); checkCorrectness(out, correctOut, n); // FREE MEMORIES free(in); free(out); free(correctOut); return EXIT_SUCCESS; }
f8e6c80c3f68068987dd87ba4602aabca775041b.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" #include "caffe/sds_layers.hpp" #define ZEROD static_cast<Dtype>(0) #define ceilD(a) static_cast<Dtype>(ceil(a)) #define floorD(a) static_cast<Dtype>(floor(a)) using std::max; using std::min; namespace caffe { template <typename Dtype> __global__ void ProjForward(const int nthreads, const Dtype* sp, const Dtype* boxes, const Dtype* pred_masks, const Dtype* denom_data, Dtype* top_data, int width, int height, int maskw, int maskh, int numsp, int numrows) { CUDA_KERNEL_LOOP(index, nthreads) { Dtype W = static_cast<Dtype>(width); Dtype H = static_cast<Dtype>(height); int row = index % numrows; int n=index / numrows; Dtype* topdata_this = top_data+index*numsp; const Dtype* this_box = boxes+n*6; const Dtype* pred_masks_this = pred_masks+n*maskw*maskh; Dtype box_xmin = this_box[2]*W; Dtype box_ymin = this_box[3]*H; Dtype box_xmax = this_box[4]*W; Dtype box_ymax = this_box[5]*H; Dtype box_w = box_xmax-box_xmin+1; Dtype box_h = box_ymax-box_ymin+1; Dtype rounded_box_xmin = min(max(ceilD(box_xmin),ZEROD), (W-1)); Dtype rounded_box_ymin = min(max(ceilD(box_ymin),ZEROD), (H-1)); Dtype rounded_box_xmax = min(max(floorD(box_xmax),ZEROD), (W-1)); Dtype rounded_box_ymax = min(max(floorD(box_ymax),ZEROD), (H-1)); if(row>=rounded_box_ymin && row<=rounded_box_ymax){ Dtype y = static_cast<Dtype>(row); for(Dtype x=rounded_box_xmin; x<=rounded_box_xmax; x++) { Dtype X = (x-box_xmin)/box_w*static_cast<Dtype>(maskw); Dtype Y = (y-box_ymin)/box_h*static_cast<Dtype>(maskh); X = min(max(floorD(X),ZEROD),static_cast<Dtype>(maskw-1)); Y = min(max(floorD(Y),ZEROD), static_cast<Dtype>(maskh-1)); Dtype spid = sp[static_cast<int>(x+y*W)]-1; Dtype val =pred_masks_this[static_cast<int>(X+Y*static_cast<Dtype>(maskw))]; topdata_this[static_cast<int>(spid)]+=val/denom_data[static_cast<int>(spid)]; } } } } template <typename Dtype> __global__ void ReduceForward(const int nthreads, const Dtype* temp_data, Dtype* top_data, int numsp, int numrows) { CUDA_KERNEL_LOOP(index, nthreads) { int spid = index % numsp; int n=(index / numsp); Dtype* topdata_this = top_data+n*numsp + spid; const Dtype* tempdata_this = temp_data+n*numrows*numsp+spid; for(int i=0; i<numrows; i++) { topdata_this[0] += tempdata_this[0]; tempdata_this = tempdata_this + numsp; } } } template <typename Dtype> void SuperpixelProjectionLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int numboxes = bottom[1]->num(); int width = bottom[0]->width(); int height = bottom[0]->height(); int maskw = bottom[2]->width(); int maskh = bottom[2]->height(); Dtype W = static_cast<Dtype>(width); Dtype H = static_cast<Dtype>(height); const Dtype* sp = bottom[0]->gpu_data(); const Dtype* sp_cpu = bottom[0]->cpu_data(); const Dtype* boxes = bottom[1]->gpu_data(); const Dtype* pred_masks = bottom[2]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); Dtype* temp_data = temp->mutable_gpu_data(); Dtype* denom_data = denom->mutable_cpu_data(); caffe_gpu_set(top[0]->count(),ZEROD, top_data); caffe_gpu_set(temp->count(),ZEROD, temp_data); caffe_set(denom->count(),ZEROD, denom_data); for(int i=0; i<bottom[0]->count();i++) { Dtype spid = sp_cpu[i]-1; denom_data[static_cast<int>(spid)]++; } const Dtype* denom_data_gpu = denom->gpu_data(); hipLaunchKernelGGL(( ProjForward<Dtype>), dim3(CAFFE_GET_BLOCKS((bottom[1]->num())*(bottom[0]->height()))), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, (bottom[1]->num())*(bottom[0]->height()), sp, boxes, pred_masks, denom_data_gpu,temp_data,width, height, maskw, maskh, numsp, bottom[0]->height()); hipLaunchKernelGGL(( ReduceForward<Dtype>), dim3(CAFFE_GET_BLOCKS((bottom[1]->num())*numsp)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, (bottom[1]->num())*numsp, temp_data, top_data, numsp, bottom[0]->height()); } template <typename Dtype> void SuperpixelProjectionLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { } INSTANTIATE_LAYER_GPU_FUNCS(SuperpixelProjectionLayer); }
f8e6c80c3f68068987dd87ba4602aabca775041b.cu
#include <vector> #include "caffe/layer.hpp" #include "caffe/util/math_functions.hpp" #include "caffe/vision_layers.hpp" #include "caffe/sds_layers.hpp" #define ZEROD static_cast<Dtype>(0) #define ceilD(a) static_cast<Dtype>(ceil(a)) #define floorD(a) static_cast<Dtype>(floor(a)) using std::max; using std::min; namespace caffe { template <typename Dtype> __global__ void ProjForward(const int nthreads, const Dtype* sp, const Dtype* boxes, const Dtype* pred_masks, const Dtype* denom_data, Dtype* top_data, int width, int height, int maskw, int maskh, int numsp, int numrows) { CUDA_KERNEL_LOOP(index, nthreads) { Dtype W = static_cast<Dtype>(width); Dtype H = static_cast<Dtype>(height); int row = index % numrows; int n=index / numrows; Dtype* topdata_this = top_data+index*numsp; const Dtype* this_box = boxes+n*6; const Dtype* pred_masks_this = pred_masks+n*maskw*maskh; Dtype box_xmin = this_box[2]*W; Dtype box_ymin = this_box[3]*H; Dtype box_xmax = this_box[4]*W; Dtype box_ymax = this_box[5]*H; Dtype box_w = box_xmax-box_xmin+1; Dtype box_h = box_ymax-box_ymin+1; Dtype rounded_box_xmin = min(max(ceilD(box_xmin),ZEROD), (W-1)); Dtype rounded_box_ymin = min(max(ceilD(box_ymin),ZEROD), (H-1)); Dtype rounded_box_xmax = min(max(floorD(box_xmax),ZEROD), (W-1)); Dtype rounded_box_ymax = min(max(floorD(box_ymax),ZEROD), (H-1)); if(row>=rounded_box_ymin && row<=rounded_box_ymax){ Dtype y = static_cast<Dtype>(row); for(Dtype x=rounded_box_xmin; x<=rounded_box_xmax; x++) { Dtype X = (x-box_xmin)/box_w*static_cast<Dtype>(maskw); Dtype Y = (y-box_ymin)/box_h*static_cast<Dtype>(maskh); X = min(max(floorD(X),ZEROD),static_cast<Dtype>(maskw-1)); Y = min(max(floorD(Y),ZEROD), static_cast<Dtype>(maskh-1)); Dtype spid = sp[static_cast<int>(x+y*W)]-1; Dtype val =pred_masks_this[static_cast<int>(X+Y*static_cast<Dtype>(maskw))]; topdata_this[static_cast<int>(spid)]+=val/denom_data[static_cast<int>(spid)]; } } } } template <typename Dtype> __global__ void ReduceForward(const int nthreads, const Dtype* temp_data, Dtype* top_data, int numsp, int numrows) { CUDA_KERNEL_LOOP(index, nthreads) { int spid = index % numsp; int n=(index / numsp); Dtype* topdata_this = top_data+n*numsp + spid; const Dtype* tempdata_this = temp_data+n*numrows*numsp+spid; for(int i=0; i<numrows; i++) { topdata_this[0] += tempdata_this[0]; tempdata_this = tempdata_this + numsp; } } } template <typename Dtype> void SuperpixelProjectionLayer<Dtype>::Forward_gpu(const vector<Blob<Dtype>*>& bottom, const vector<Blob<Dtype>*>& top) { int numboxes = bottom[1]->num(); int width = bottom[0]->width(); int height = bottom[0]->height(); int maskw = bottom[2]->width(); int maskh = bottom[2]->height(); Dtype W = static_cast<Dtype>(width); Dtype H = static_cast<Dtype>(height); const Dtype* sp = bottom[0]->gpu_data(); const Dtype* sp_cpu = bottom[0]->cpu_data(); const Dtype* boxes = bottom[1]->gpu_data(); const Dtype* pred_masks = bottom[2]->gpu_data(); Dtype* top_data = top[0]->mutable_gpu_data(); Dtype* temp_data = temp->mutable_gpu_data(); Dtype* denom_data = denom->mutable_cpu_data(); caffe_gpu_set(top[0]->count(),ZEROD, top_data); caffe_gpu_set(temp->count(),ZEROD, temp_data); caffe_set(denom->count(),ZEROD, denom_data); for(int i=0; i<bottom[0]->count();i++) { Dtype spid = sp_cpu[i]-1; denom_data[static_cast<int>(spid)]++; } const Dtype* denom_data_gpu = denom->gpu_data(); ProjForward<Dtype><<<CAFFE_GET_BLOCKS((bottom[1]->num())*(bottom[0]->height())), CAFFE_CUDA_NUM_THREADS>>>((bottom[1]->num())*(bottom[0]->height()), sp, boxes, pred_masks, denom_data_gpu,temp_data,width, height, maskw, maskh, numsp, bottom[0]->height()); ReduceForward<Dtype><<<CAFFE_GET_BLOCKS((bottom[1]->num())*numsp), CAFFE_CUDA_NUM_THREADS>>>((bottom[1]->num())*numsp, temp_data, top_data, numsp, bottom[0]->height()); } template <typename Dtype> void SuperpixelProjectionLayer<Dtype>::Backward_gpu(const vector<Blob<Dtype>*>& top, const vector<bool>& propagate_down, const vector<Blob<Dtype>*>& bottom) { } INSTANTIATE_LAYER_GPU_FUNCS(SuperpixelProjectionLayer); }
4d64ee589dffe74570a2c8ab5a7d23e501e79553.hip
// !!! This is a file automatically generated by hipify!!! #include "initializers.h" #include "helpers.h" #include "kernels/kernels.h" #include <cmath> #include <hiprand/hiprand.h> namespace ad { static int i = 0; static hiprandGenerator_t* GetUniformGenerator() { static hiprandGenerator_t* gen = nullptr; if (!gen) { gen = new hiprandGenerator_t; hiprandCreateGenerator(gen, HIPRAND_RNG_PSEUDO_DEFAULT); hiprandSetPseudoRandomGeneratorSeed(*gen, 1234ULL); std::atexit([&]() { hiprandDestroyGenerator(*gen); }); } return gen; } void Gaussian::Init(Matrix& mat) const { hiprandGenerator_t* gen = GetUniformGenerator(); hiprandGenerateNormal(*gen, mat.data().Get(), mat.size(), mu_, sigma_); std::cout << "gaussian inited " << i << "\n"; ++i; } void Uniform::Init(Matrix& mat) const { hiprandGenerator_t* gen = GetUniformGenerator(); hiprandGenerateUniform(*gen, mat.data().Get(), mat.size()); auto x = cuda::Array(mat.data()); auto scale = cuda::Value(::fabs(from_) + ::fabs(to_)); auto from = cuda::Value(from_); cuda::RunKernel(cuda::Seq( x = x * scale + from), mat.size()); std::cout << "uniform inited " << i << "\n"; ++i; } } // ad
4d64ee589dffe74570a2c8ab5a7d23e501e79553.cu
#include "initializers.h" #include "helpers.h" #include "kernels/kernels.h" #include <cmath> #include <curand.h> namespace ad { static int i = 0; static curandGenerator_t* GetUniformGenerator() { static curandGenerator_t* gen = nullptr; if (!gen) { gen = new curandGenerator_t; curandCreateGenerator(gen, CURAND_RNG_PSEUDO_DEFAULT); curandSetPseudoRandomGeneratorSeed(*gen, 1234ULL); std::atexit([&]() { curandDestroyGenerator(*gen); }); } return gen; } void Gaussian::Init(Matrix& mat) const { curandGenerator_t* gen = GetUniformGenerator(); curandGenerateNormal(*gen, mat.data().Get(), mat.size(), mu_, sigma_); std::cout << "gaussian inited " << i << "\n"; ++i; } void Uniform::Init(Matrix& mat) const { curandGenerator_t* gen = GetUniformGenerator(); curandGenerateUniform(*gen, mat.data().Get(), mat.size()); auto x = cuda::Array(mat.data()); auto scale = cuda::Value(std::fabs(from_) + std::fabs(to_)); auto from = cuda::Value(from_); cuda::RunKernel(cuda::Seq( x = x * scale + from), mat.size()); std::cout << "uniform inited " << i << "\n"; ++i; } } // ad
df74231287d52baa404f8a0bd90b963185bd2a0a.hip
// !!! This is a file automatically generated by hipify!!! ///sta programa calcula la versin paralelizada del algoritmo FFT_DIF_DIT_TD ///(26/08/2016) ///sta versin sirve para graficar en matlab los errores absolutos y relativos (RADIX-2) 2^1 - 2^10. Los arreglos x_host y W_host se generan en el device y la funcin asign_rap se ejecuta en el device #include "hip/hip_runtime.h" #include "device_launch_parameters.h" #include <hipfft.h> #include <cufftw.h> #include <stdio.h> #include <stdlib.h> #include <hip/hip_complex.h> #include <math.h> #include <math_constants.h> #include <iostream> #include <time.h> #include <hiprand/hiprand.h> #include <hiprand/hiprand_kernel.h> ////////////////////////////////////////////////////////////////////////// ///////////////////////DECLARACIN DE FUNCIONES/////////////////////////// ////////////////////////////////////////////////////////////////////////// void vector_entrada_xn(int N_max); __global__ void init(unsigned int seed, hiprandState_t *states,int N_max); __global__ void entrada_xn_kernel(int N_max,float *alea_real,float *alea_imag,cuFloatComplex *x_device,FILE *dc,hiprandState_t *states); void arreglo_W(int N); __global__ void arreglo_W_kernel(int N,cuFloatComplex *W_device); void asign_rap(int N,int Li,int Lo); void factor(int N); void product(int vector_1[50],int vector_2[50],int valor); void etapa_entrada(void); __global__ void inputStage_kernel(int N, int Li,int Dip,int Dop,int P,cuFloatComplex *x,cuFloatComplex *W,cuFloatComplex *y,int *flag_inputstage_1_d,int *flag_inputstage_2_d,int *flag_inputstage_3_d); void etapa_intermedia(void); void etapa_salida(void); __global__ void outputStage_kernel(int N,int Lo,int Dip,int Dop,int P,cuFloatComplex *z,cuFloatComplex *W,cuFloatComplex *X,int *flag_outputstage_1_d,int *flag_outputstage_2_d,int *flag_outputstage_3_d); ////////////////////////////////////////////////////////////////////////// /////////////////////DECLARACIN DE VARIABLES GLOBALES//////////////////// ////////////////////////////////////////////////////////////////////////// //cuFloatComplex *x_host; //cuFloatComplex *W_host; //cuFloatComplex *y_host; //cuFloatComplex *z_host; cuFloatComplex *X_host; cuFloatComplex *x_device; float *alea_real,*alea_imag; cuFloatComplex *W_device; cuFloatComplex *y_device; cuFloatComplex *z_device; cuFloatComplex *X_device; hipfftComplex *in,*out; int *flag_inputstage_1,*flag_inputstage_2,*flag_inputstage_3,*flag_outputstage_1,*flag_outputstage_2,*flag_outputstage_3; int *flag_inputstage_1_d,*flag_inputstage_2_d,*flag_inputstage_3_d,*flag_outputstage_1_d,*flag_outputstage_2_d,*flag_outputstage_3_d; int Dip,Dop,P,N,Li,Lo; int vF[50]; //Almacena los factores de N int svF; //Almacena el numero de factores de N int Prod[50]; int a; FILE *dc; #define inf 99999 ////////////////////////////////////////////////////////////////////////// //////////////////////////DATOS DE ENTRADA//////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// N >>> Nmero de elementos del vector de entrada /// Li >>> Nmero de elementos de entrada diferentes de cero /// Lo >>> Nmero de elementos de salida requeridos /// loop >>> Nmero de iteraciones /// muestras >>> Nmero de muestras ////////////////////////////////////////////////////////////////////////// ///////////////////////////DATOS DE SALIDA//////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// X >>> Vector de salida ////////////////////////////////////////////////////////////////////////// /////////////////// SE INGRESAN LOS DATOS DE ENTRADA ///////////////////// ////////////////////////////////////////////////////////////////////////// ///Ingrese el nmero de iteraciones requeridas int loop = 1; ///Ingrese el nmero de muestras requeridas const int muestras = 1; ///Se ingresa la N mxima int N_max = 1024; ////////////////////////////////////////////////////////////////////////// //////////////////////////FUNCION PRINCIPAL/////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Funcin principal int main() { int i,j,i_N,l_res,j_res,k_res,incremento_j; //float suma; //float promedio[muestras]; ///Se crean los archivos binarios donde se guardarn los datos FILE *da; FILE *db; //FILE *dc; //FILE *dd; FILE *fi_1; FILE *fi_2; FILE *fi_3; FILE *fo_1; FILE *fo_2; FILE *fo_3; da = fopen("Resultados_radix_2_real_CUDA.bin","a+b"); //Crea o sobre escribe archivo db = fopen("Resultados_radix_2_imag_CUDA.bin","a+b"); //Crea o sobre escribe archivo dc = fopen("Entrada_radix_2_CUDA.txt","w+t"); //Crea o sobre escribe archivo //dd = fopen("TIEMPOS_FFT_DIF_DIT_TD_SECUENCIAL_CUDA.bin","a+b"); //Crea o sobre escribe archivo fi_1 = fopen("Flag_inputstage_1_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fi_2 = fopen("Flag_inputstage_2_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fi_3 = fopen("Flag_inputstage_3_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fo_1 = fopen("Flag_outputstage_1_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fo_2 = fopen("Flag_outputstage_2_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fo_3 = fopen("Flag_outputstage_3_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo //Se generan en el device los valores del vector de entrada x[n] vector_entrada_xn(N_max); fclose(dc); //Pausa printf("\n---PRESIONA UNA TECLA PARA CONTINUAR---\n\n"); getchar(); //Se reserva espacio para las flags flag_inputstage_1 = (int *)malloc(1*sizeof(int)); flag_inputstage_2 = (int *)malloc(1*sizeof(int)); flag_inputstage_3 = (int *)malloc(1*sizeof(int)); flag_outputstage_1 = (int *)malloc(1*sizeof(int)); flag_outputstage_2 = (int *)malloc(1*sizeof(int)); flag_outputstage_3 = (int *)malloc(1*sizeof(int)); hipMalloc((int**)&flag_inputstage_1_d,1*sizeof(int)); hipMalloc((int**)&flag_inputstage_2_d,1*sizeof(int)); hipMalloc((int**)&flag_inputstage_3_d,1*sizeof(int)); hipMalloc((int**)&flag_outputstage_1_d,1*sizeof(int)); hipMalloc((int**)&flag_outputstage_2_d,1*sizeof(int)); hipMalloc((int**)&flag_outputstage_3_d,1*sizeof(int)); //Inicializaciones incremento_j = 1; flag_inputstage_1[0] = 0; flag_inputstage_2[0] = 0; flag_inputstage_3[0] = 0; flag_outputstage_1[0] = 0; flag_outputstage_2[0] = 0; flag_outputstage_3[0] = 0; for(i_N = 1;i_N <= 10;i_N++) { N = (int )pow(2,i_N); printf("\n N = %d \n",N); //Se genera el arreglo W[N] en el device arreglo_W(N); for(j_res=incremento_j;j_res<=N;j_res=j_res+incremento_j) { Li=j_res; for(k_res=incremento_j;k_res<=N;k_res=k_res+incremento_j) { Lo=k_res; //printf("\n Li = %d Lo = %d",Li,Lo); for(i=1;i<=muestras;i++) { //suma=0.0; for(j=0;j<loop;j++) { //Comandos necesarios para medir el tiempo //float elapsedTime_app; //hipEvent_t start_app, stop_app; //hipEventCreate(&start_app); //hipEventCreate(&stop_app); //--------------------------------------------------------------------------------------------- //Se empieza a medir el tiempo de ejecucion de la aplicacion //hipEventRecord(start_app,0); //Se generan en el host los factores Dip y Dop asign_rap(N,Li,Lo); //Clculo en el host del factor P P = N/(Dip*Dop); //printf("\n\n FACTOR P:\n\n"); //printf("\n Dip = %d Dop = %d P = %d ",Dip,Dop,P); //Funcin auxiliar del host para ejecutar la etapa de entrada etapa_entrada(); //Funcin auxiliar del host para ejecutar la etapa intermedia etapa_intermedia(); //Funcin auxiliar del host para ejecutar la etapa de salida etapa_salida(); ///Se imprimen los resultados en los archivos binarios int m; float *parte_real; float *parte_imag; parte_real = (float*) malloc(Lo*sizeof(float)); parte_imag = (float*) malloc(Lo*sizeof(float)); for(m=0;m<=Lo-1;m++) { parte_real[m]=cuCrealf(X_host[m]); parte_imag[m]=cuCimagf(X_host[m]); //printf("\n X[%d] = %.4f + (%.4f)",m,creal(X[m]),cimag(X[m])); //fprintf(dc,"%f %f\n",creal(X[m]),cimag(X[m])); } fwrite(parte_real,sizeof(float),Lo,da); fwrite(parte_imag,sizeof(float),Lo,db); ///Se leen los valores de las flags desde el device hipMemcpy(flag_inputstage_1,flag_inputstage_1_d,1*sizeof(int),hipMemcpyDeviceToHost); hipMemcpy(flag_inputstage_2,flag_inputstage_2_d,1*sizeof(int),hipMemcpyDeviceToHost); hipMemcpy(flag_inputstage_3,flag_inputstage_3_d,1*sizeof(int),hipMemcpyDeviceToHost); hipMemcpy(flag_outputstage_1,flag_outputstage_1_d,1*sizeof(int),hipMemcpyDeviceToHost); hipMemcpy(flag_outputstage_2,flag_outputstage_2_d,1*sizeof(int),hipMemcpyDeviceToHost); hipMemcpy(flag_outputstage_3,flag_outputstage_3_d,1*sizeof(int),hipMemcpyDeviceToHost); ///Se imprimen el valor de las flags en sus respectivos archivos binarios fwrite(flag_inputstage_1,1*sizeof(int),1,fi_1); fwrite(flag_inputstage_2,1*sizeof(int),1,fi_2); fwrite(flag_inputstage_3,1*sizeof(int),1,fi_3); fwrite(flag_outputstage_1,1*sizeof(int),1,fo_1); fwrite(flag_outputstage_2,1*sizeof(int),1,fo_2); fwrite(flag_outputstage_3,1*sizeof(int),1,fo_3); /* printf("\n flag_inputstage_1 = %d \n",flag_inputstage_1[0]); printf("\n flag_inputstage_2 = %d \n",flag_inputstage_2[0]); printf("\n flag_inputstage_3 = %d \n",flag_inputstage_3[0]); printf("\n flag_outputstage_1 = %d \n",flag_outputstage_1[0]); printf("\n flag_outputstage_2 = %d \n",flag_outputstage_2[0]); printf("\n flag_outputstage_3 = %d \n",flag_outputstage_3[0]); */ //Se liberan memorias del Host y Device //free(x_host); //free(W_host); //free(y_host); //free(z_host); free(X_host); free(parte_real); free(parte_imag); //hipFree(x_device); //hipFree(W_device); hipFree(y_device); hipFree(z_device); hipFree(X_device); //--------------------------------------------------------------------------------------------- //Comandos necesarios para medir el tiempo de la aplicacion (app) //hipEventRecord(stop_app,0); //hipEventSynchronize(stop_app); //hipEventElapsedTime(&elapsedTime_app,start_app,stop_app); //Suma de todos los tiempos //suma = suma + elapsedTime_app; //Se destruyen los eventos que miden el tiempo de la aplicacion //hipEventDestroy(start_app); //hipEventDestroy(stop_app); ///Se resetean las flags flag_inputstage_1[0] = 0; flag_inputstage_2[0] = 0; flag_inputstage_3[0] = 0; flag_outputstage_1[0] = 0; flag_outputstage_2[0] = 0; flag_outputstage_3[0] = 0; } //promedio[i-1] = suma/(float)loop; //printf(" \n\n%d - Tiempo promedio para N = %ld >>> %f mS\n",i,N,promedio[i-1]); } //fwrite(promedio,sizeof(float),muestras,dd); //fclose(dd); } } //free(x_host); //free(W_host); hipFree(x_device); hipFree(W_device); } fclose(da); fclose(db); fclose(fi_1); fclose(fi_2); fclose(fi_3); fclose(fo_1); fclose(fo_2); fclose(fo_3); free(flag_inputstage_1); free(flag_inputstage_2); free(flag_inputstage_3); free(flag_outputstage_1); free(flag_outputstage_2); free(flag_outputstage_3); hipFree(flag_inputstage_1_d); hipFree(flag_inputstage_2_d); hipFree(flag_inputstage_3_d); hipFree(flag_outputstage_1_d); hipFree(flag_outputstage_2_d); hipFree(flag_outputstage_3_d); return EXIT_SUCCESS; } ////////////////////////////////////////////////////////////////////////// /////////////////////////FUNCIONES SECUNDARIAS//////////////////////////// ////////////////////////////////////////////////////////////////////////// //sta funcin genera el vector de entrada x[n] void vector_entrada_xn(int N_max) { //CUDA's random number library uses hiprandState_t to keep track of the seed value //we will stor3e a random state for every thread hiprandState_t *states; //Allocate space on the GPU for the random states hipMalloc((void**) &states,N_max*sizeof(hiprandState_t)); //Se reserva memoria para x_device hipMalloc((void**)&x_device,N_max*sizeof(cuFloatComplex)); hipMalloc((void**)&alea_real,N_max*sizeof(float)); hipMalloc((void**)&alea_imag,N_max*sizeof(float)); //Dimensionamiento del grid para la funcin kernel "inputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((N_max) < 1024) { blockDim.x = N_max; gridDim.x = 1; } else { blockDim.x = 1024; gridDim.x = (unsigned int) (ceilf((float)N_max/(float)blockDim.x)); } //Invoke the GPU to initialize all of the random states hipLaunchKernelGGL(( init), dim3(gridDim),dim3(blockDim), 0, 0, time(0),states,N_max); //Esperar que el kernel termine de ejecutarse totalmente hipDeviceSynchronize(); //Lanzamiento del kernel "entrada_xn_kernel" hipLaunchKernelGGL(( entrada_xn_kernel), dim3(gridDim),dim3(blockDim), 0, 0, N_max,alea_real,alea_imag,x_device,dc,states); //Esperar que el kernel termine de ejecutarse totalmente hipDeviceSynchronize(); hipFree(alea_real); hipFree(alea_imag); hipFree(states); } /* this GPU kernel function is used to initialize the random states */ __global__ void init(unsigned int seed, hiprandState_t *states,int N_max) { //Threads int i = blockDim.x *blockIdx.x + threadIdx.x; if(i < N_max) { /* 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 */ i, /* 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[i]); } } //Funcin kernel para xn_device __global__ void entrada_xn_kernel(int N_max,float *alea_real,float *alea_imag,cuFloatComplex *x_device,FILE *dc,hiprandState_t *states) { //Threads int i = blockDim.x *blockIdx.x + threadIdx.x; if(i < N_max) { alea_real[i]=hiprand(&states[i]) % 11; //alea_real[i]=i+1; alea_imag[i]=hiprand(&states[i]) % 11; //alea_imag[i]=0; fprintf(dc,"%d %d\n",alea_real[i],alea_imag[i]); x_device[i] = make_cuFloatComplex((float)alea_real[i],(float)alea_imag[i]); } } //sta funcin genera el arreglo W void arreglo_W(int N) { //Se reserva memoria para W_host hipMalloc((void**)&W_device,N*sizeof(cuFloatComplex)); //Dimensionamiento del grid para la funcin kernel "inputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((N) < 1024) { blockDim.x = N; gridDim.x = 1; } else { blockDim.x = 1024; gridDim.x = (unsigned int) (ceilf((float)N/(float)blockDim.x)); } //Lanzamiento del kernel "entrada_xn_kernel" hipLaunchKernelGGL(( arreglo_W_kernel), dim3(gridDim),dim3(blockDim), 0, 0, N,W_device); //Esperar que el kernel termine de ejecutarse totalmente hipDeviceSynchronize(); } //Funcin kernel para W_device __global__ void arreglo_W_kernel(int N,cuFloatComplex *W_device) { //Threads int n = blockDim.x *blockIdx.x + threadIdx.x; if(n < N) { W_device[n] = make_cuFloatComplex((float)cos((2*CUDART_PI*(n+1))/N),(float)(-1)*sin((2*CUDART_PI*(n+1))/N)); } } //sta funcin genera los factores Dip y Dop void asign_rap(int N,int Li,int Lo) { //Declaracin de variables locales float NLi,NLo,Diprapt,Doprapt; int Nh[50]; int k[50]; int G; int g,i,t,ta; int Dipt[50],Dopt[50]; float distrapt,distrap; int Pos,h,Poss; int nk[50]; int r; //Inicializaciones G = 0; svF = 0; //Factores Dip y Dop ideales NLi=(float)N/(float)Li; NLo=(float)N/(float)Lo; Diprapt=NLi; Doprapt=NLo; //Se encuentran los factores de "N" //vF almacena los factores de "N" //svF almacena el nmero de factores de "N" factor(N); /* Almacena en el vector Nh los factores que son diferentes de del vector vF En el vector k se almacena la cantidad de veces que se repite cada elemento almacenado en el vector Nh. */ Nh[0] = vF[0]; k[0]=1; for(g=1;g<=svF-1;g=g+1) { if(vF[g]!=vF[g-1]) { G=G+1; Nh[G]=vF[g]; k[G]=1; } else { k[G]=k[G]+1; } } /* Almacena en el vector Nh todas las posibles combinaciones que den como producto a N. t almacena el numero de elementos del vector Nh. */ product(Nh,k,G); t = a; for(i=0;i<t;i=i+1) { Dipt[i]=Prod[i]; } distrapt=inf; for(g=1;g<=t;g=g+1) { if(Dipt[g-1]<=NLi) { Pos=g-1; for(h=0;h<=G;h=h+1) { Poss=floor(Pos/(k[h]+1)); nk[h]=k[h]+Poss*(k[h]+1)-Pos; Pos=Poss; } product(Nh,nk,G); ta=a; for(i=0;i<ta;i=i+1) { Dopt[i]=Prod[i]; } //////////////////////////////////////////// //int j; //for(j=0;j<ta;j++) //{ // printf(" %d ",Dopt[j]); //} //printf("\n\n ta=%d\n\n",ta); /////////////////////////////////////////// for(r=0;r<ta;r=r+1) { distrap=sqrt(pow(Diprapt-(Dipt[g-1]),2)+pow(Doprapt-(Dopt[r]),2)); if(distrap<distrapt) { distrapt=distrap; Dip=Dipt[g-1]; Dop=Dopt[r]; } } } } /* printf("\n\n FACTOR Dip :\n\n"); printf(" %d ",Dip); printf("\n\n FACTOR Dop:\n\n"); printf(" %d ",Dop); */ } //sta funcin encuentra los factores de "N" void factor(int N) { //Se empieza a verificar los factores desde 2 int i=2; long N_factor; N_factor = N; while(i<=N_factor) { while((N_factor%i)==0) { vF[svF]=i; N_factor=N_factor/i; // printf("Factores: %d ",vF[svF]); svF++; } i++; } } //sta funcin encuentra todas las posibles combinaciones de factores que den como resultado "N" void product(int vector_1[50],int vector_2[50],int valor) { int d,e,s,pNh,i; int cont=0; Prod[0]=1; a=1; for(d=0;d<=valor;d=d+1) { s=a; pNh=1; for(e=1;e<=vector_2[d];e=e+1) { pNh=pNh*vector_1[d]; for(i=(s*e+1);i<=(s*e+s);i=i+1) { Prod[i-1]=pNh*Prod[cont]; cont=cont+1; } a=a+s; cont=0; } } } //Funcin auxiliar del host para calcular la etapa de entrada en el device void etapa_entrada(void) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////ETAPA DE ENTRADA////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Declaracin de variables locales int k1,n1,n2; //Asignacin de memoria en el device hipMalloc((void**)&y_device,P*Dip*Dop*sizeof(cuFloatComplex)); //Asignacin de memoria en el host para "y" //y_host = (cuFloatComplex*)malloc(sizeof(cuFloatComplex)*P*Dip*Dop); //Dimensionamiento del grid para la funcin kernel "inputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((P*Dop) < 32 && (Dip) < 32) { blockDim.x = (P*Dop); blockDim.y = (Dip); gridDim.x = 1; gridDim.y = 1; } else { blockDim.x = 32; blockDim.y = 32; gridDim.x = (unsigned int) (ceilf((float)(P*Dop)/(float)blockDim.x)); gridDim.y = (unsigned int) (ceilf((float)Dip/(float)blockDim.y)); } //Lanzamiento del kernel "inputStage_kernel" hipLaunchKernelGGL(( inputStage_kernel), dim3(gridDim),dim3(blockDim), 0, 0, N,Li,Dip,Dop,P,x_device,W_device,y_device,flag_inputstage_1_d,flag_inputstage_2_d,flag_inputstage_3_d); //Esperar que el kernel termine de ejecutarse totalmente hipDeviceSynchronize(); /* //Copia del arreglo "y" del device hacia el host hipMemcpy(y_host,y_device,sizeof(cuFloatComplex)*P*Dip*Dop,hipMemcpyDeviceToHost); //Se imprimen los valores de "y" printf("\n\n--- ARREGLO y(n1,n2,k1) ---\n\n"); for(k1 = 0;k1 < Dip;k1++) { for(n1 = 0;n1 < Dop;n1++) { for(n2 = 0;n2 < P;n2++) { printf(" (%f) + (%f) ",cuCrealf(y_host[(k1*Dop*P)+(n1*P)+n2]),cuCimagf(y_host[(k1*Dop*P)+(n1*P)+n2])); } printf("\n"); } printf("\n\n"); } printf("\n"); */ } //funcin kernel que ejecuta la etapa de entrada en el device __global__ void inputStage_kernel(int N, int Li,int Dip,int Dop,int P,cuFloatComplex *x,cuFloatComplex *W,cuFloatComplex *y,int *flag_inputstage_1_d,int *flag_inputstage_2_d,int *flag_inputstage_3_d) { int n1,n2; cuFloatComplex t1; //Threads int n = blockDim.x *blockIdx.x + threadIdx.x; int k1 = blockDim.y *blockIdx.y + threadIdx.y; //Se resetean las flags flag_inputstage_1_d[0] = 0; flag_inputstage_2_d[0] = 0; flag_inputstage_3_d[0] = 0; //printf("\n n = %d k1 = %d",n,k1); if( (n < (P*Dop)) && (k1 < Dip)) { n2 = floorf(n/Dop); n1 = n - (Dop*n2); //Generacin de los elementos que dependen de x[0] if(n == 0) { y[(k1*Dop*P)+(0*P)+ 0] = x[0]; ///Flag flag_inputstage_1_d[0] = 1; } //Mapeo de x[n] a las entradas del primer conjunto de Dop DFT's if((n >= 1) && (n <= (Li-1))) { t1 = x[n]; if(k1 == 0) { y[(0*Dop*P)+(n1*P)+ n2] = t1; } if(k1 >= 1) { y[(k1*Dop*P)+(n1*P)+ n2] = cuCmulf(W[((n*k1)%N)-1],t1); } ///Flag flag_inputstage_2_d[0] = 1; } //Rellenado de ceros para los elementos de "y" para Li <= n <= (P*Dop)-1 if((n >= Li) && (n <= (P*Dop)-1)) { y[(k1*Dop*P)+(n1*P)+ n2] = make_cuFloatComplex(0.0,0.0); ///Flag flag_inputstage_3_d[0] = 1; } //printf("\n (%f) + (%f)\n ",cuCrealf(y[(k1*Dop*P)+(n1*P)+ n2]),cuCimagf(y[(k1*Dop*P)+(n1*P)+ n2])); } } //Funcin auxiliar del host para calcular la etapa intermedia en el device void etapa_intermedia(void) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////ETAPA INTERMEDIA////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Declaracin de variables locales int k1,k2,n1; int n[1] = {P}; int inembed[1] = {P}; int onembed[1] = {P}; //Asignacin de memoria en el device para "z" hipMalloc((void**)&z_device,P*Dip*Dop*sizeof(cuFloatComplex)); //Asignacin de memoria en el host para "z" //z_host = (cuFloatComplex*)malloc(sizeof(cuFloatComplex)*P*Dip*Dop); //Asignacin de memoria en el device para "in" y "out" hipMalloc((void**)&in,sizeof(hipfftComplex)*P*Dip*Dop); hipMalloc((void**)&out,sizeof(hipfftComplex)*P*Dip*Dop); //Se copia el arreglo "y" al arreglo "in" hipMemcpy(in,y_device,sizeof(cuFloatComplex)*P*Dip*Dop,hipMemcpyDeviceToDevice); //Se crea un plan hipfftHandle plan; hipfftPlanMany(&plan,1,n,inembed,1,P,onembed,1,P,HIPFFT_C2C,Dip*Dop); //Ejecucin del plan hipfftExecC2C(plan,in,out,HIPFFT_FORWARD); //Esperar que el kernel termine de ejecutarse totalmente hipDeviceSynchronize(); //Se copian los datos del arreglo "out" al arreglo "z_device" hipMemcpy(z_device,out,sizeof(hipfftComplex)*P*Dip*Dop,hipMemcpyDeviceToDevice); //Se destruye el plan hipfftDestroy(plan); //Se liberan los arreglos "in" y "out" hipFree(in); hipFree(out); /* //Se copian los datos del arreglo "z_device" al arreglo "z_host" hipMemcpy(z_host,z_device,sizeof(cuFloatComplex)*P*Dip*Dop,hipMemcpyDeviceToHost); ///Se imprimen los valores de z(n1,k2,k1) printf("\n\n--- ARREGLO z(n1,k2,k1) ---\n\n"); for(k1 = 0;k1 < Dip;k1++) { for(n1 = 0;n1 < Dop;n1++) { for(k2 = 0;k2 < P;k2++) { printf(" (%f) + (%f) ",cuCrealf(z_host[(k1*Dop*P)+(n1*P)+k2]),cuCimagf(z_host[(k1*Dop*P)+(n1*P)+k2])); } printf("\n"); } printf("\n\n"); } printf("\n"); */ } //Funcin auxiliar del host para calcular la etapa de salida en el device void etapa_salida(void) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////ETAPA DE SALIDA/////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Declaracin de variables locales int m; //Asignacin de memoria en el device para "X" hipMalloc((void**)&X_device,Lo*sizeof(cuFloatComplex)); //Asignacin de memoria en el host para "X" X_host = (cuFloatComplex*)malloc(sizeof(cuFloatComplex)*Lo); //Dimensionamiento del grid para la funcin kernel "outputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((Lo) < 1024) { blockDim.x = Lo; gridDim.x = 1; } else { blockDim.x = 1024; gridDim.x = (unsigned int) (ceilf((float)Lo/(float)blockDim.x)); } //Lanzamiento del kernel "outputStage_kernel" hipLaunchKernelGGL(( outputStage_kernel), dim3(gridDim),dim3(blockDim), 0, 0, N,Lo,Dip,Dop,P,z_device,W_device,X_device,flag_outputstage_1_d,flag_outputstage_2_d,flag_outputstage_3_d); //Esperar que el kernel termine de ejecutarse totalmente hipDeviceSynchronize(); //Copia del arreglo "X" del device hacia el host hipMemcpy(X_host,X_device,sizeof(cuFloatComplex)*Lo,hipMemcpyDeviceToHost); /* //Se imprimen los valores de "X_host" ///Imprimir X[k] printf("\n\n--- ARREGLO X[k] ---\n\n"); for(m=0;m<=Lo-1;m++) { printf("\n X[%d] = %.4f + (%.4f)",m,cuCrealf(X_host[m]),cuCimagf(X_host[m])); //fprintf(da,"%.4f %.4f\n",creal(X[i]),cimag(X[i])); } */ } //funcin kernel que ejecuta la etapa de salida en el device __global__ void outputStage_kernel(int N,int Lo,int Dip,int Dop,int P,cuFloatComplex *z,cuFloatComplex *W,cuFloatComplex *X,int *flag_outputstage_1_d,int *flag_outputstage_2_d,int *flag_outputstage_3_d) { //Declaracin de variables locales int n1,k_aux,k1,k2,a,b; cuFloatComplex t1,t2,t3,t4,t5; //Threads int k = blockDim.x *blockIdx.x + threadIdx.x; //Se resetean las flags flag_outputstage_1_d[0] = 0; flag_outputstage_2_d[0] = 0; flag_outputstage_3_d[0] = 0; if(k < Lo) { for(n1 = 0; n1 <= (Dop-1); n1 = n1+1) { if(Lo <= Dip) { //Clculo de X(k) para 0<=k<=Lo-1. //printf("\n--- Caso (Lo <= Dip) ---\n"); //En la descomposicin k = k1 + Dipk2; k2 = 0, y por lo tanto, k = k1 if(n1 == 0) //Caso para lograr que por lo menos ingrese una vez { X[k] = z[(k*Dop*P)+(0*P) + 0]; ///Flag flag_outputstage_1_d[0] = 1; } else { if(n1 == 1) { X[k] = z[(k*Dop*P)+(0*P) + 0]; } X[k] = cuCaddf(z[(k*Dop*P)+(n1*P) + 0],X[k]); ///Flag flag_outputstage_1_d[0] = 1; } } else { if((k >= 0) && (k <= (Dip-1))) { //Clculo de X(k) para 0<=k<=Dip-1. //En la descomposicin k = k1 + Dipk2; k2 = 0, y por lo tanto, k = k1 if(n1 == 0) //Caso para lograr que por lo menos ingrese una vez { X[k] = z[(k*Dop*P)+(0*P) + 0]; } else { if(n1 == 1) { X[k] = z[(k*Dop*P)+(0*P) + 0]; } X[k] = cuCaddf(z[(k*Dop*P)+(n1*P) + 0],X[k]); } } else { if(Dop <= 4) { //Usando el mtodo directo //printf("\n--- Caso (Metodo directo) ---\n"); if(n1 == 0) //Caso para lograr que por lo menos ingrese una vez { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); X[k] = z[(k1*Dop*P)+(0*P)+ (k2%P)]; ///Flag flag_outputstage_2_d[0] = 1; } else { if(n1 == 1) { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); X[k] = z[(k1*Dop*P)+(0*P)+ (k2%P)]; } a = floorf(k/(Dip*P)); X[k] = cuCaddf(X[k],cuCmulf(z[(k1*Dop*P)+(n1*P)+ (k2%P)],W[((n1*(k2+P*(a))*Dip)%N)-1])); ///Flag flag_outputstage_2_d[0] = 1; } } else { //Usando el mtodo filtering 2BF //printf("\n--- Caso (Filtro 2BF) ---\n"); if((Dop-2) >= 1) { if(n1 == 0) { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); t1 = z[(k1*Dop*P)+((Dop-1)*P)+ (k2%P)]; b = floorf(k/(Dip*P)); t4 = cuCmulf(t1,make_cuFloatComplex(2*cuCrealf(W[(((k2+P*(b))*Dip)%N)-1]),0.0)); ///Flag flag_outputstage_3_d[0] = 1; } if((n1 >= 1) && (n1 <= (Dop-2))) { t2 = t1; t1 = cuCaddf(z[(k1*Dop*P)+((-(n1-(Dop-1)))*P)+ (k2%P)],t4); t3 = cuCmulf(t1,make_cuFloatComplex(2*cuCrealf(W[(((k2+P*(b))*Dip)%N)-1]),0.0)); t4 = cuCsubf(t3,t2); } if(n1 == (Dop-1)) { t5 = cuCaddf(z[(k1*Dop*P)+(0*P)+ (k2%P)],t4); X[k] = cuCsubf(t5,cuCmulf(t1,cuConjf(W[(((k2+P*(b))*Dip)%N)-1]))); } } else { if(Dop == 1) { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); t1 = z[(k1*Dop*P)+((Dop-1)*P)+ (k2%P)]; X[k] = t1; ///Flag flag_outputstage_3_d[0] = 1; } else { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); t1 = z[(k1*Dop*P)+((Dop-1)*P)+ (k2%P)]; b = floorf(k/(Dip*P)); t4 = cuCmulf(t1,make_cuFloatComplex(2*cuCrealf(W[(((k2+P*(b))*Dip)%N)-1]),0.0)); t5 = cuCaddf(z[(k1*Dop*P)+(0*P)+ (k2%P)],t4); X[k] = cuCsubf(t5,cuCmulf(t1,cuConjf(W[(((k2+P*(b))*Dip)%N)-1]))); ///Flag flag_outputstage_3_d[0] = 1; } } } } } } } }
df74231287d52baa404f8a0bd90b963185bd2a0a.cu
///Ésta programa calcula la versión paralelizada del algoritmo FFT_DIF_DIT_TD ///(26/08/2016) ///Ésta versión sirve para graficar en matlab los errores absolutos y relativos (RADIX-2) 2^1 - 2^10. Los arreglos x_host y W_host se generan en el device y la función asign_rap se ejecuta en el device #include "cuda_runtime.h" #include "device_launch_parameters.h" #include <cufft.h> #include <cufftw.h> #include <stdio.h> #include <stdlib.h> #include <cuComplex.h> #include <math.h> #include <math_constants.h> #include <iostream> #include <time.h> #include <curand.h> #include <curand_kernel.h> ////////////////////////////////////////////////////////////////////////// ///////////////////////DECLARACIÓN DE FUNCIONES/////////////////////////// ////////////////////////////////////////////////////////////////////////// void vector_entrada_xn(int N_max); __global__ void init(unsigned int seed, curandState_t *states,int N_max); __global__ void entrada_xn_kernel(int N_max,float *alea_real,float *alea_imag,cuFloatComplex *x_device,FILE *dc,curandState_t *states); void arreglo_W(int N); __global__ void arreglo_W_kernel(int N,cuFloatComplex *W_device); void asign_rap(int N,int Li,int Lo); void factor(int N); void product(int vector_1[50],int vector_2[50],int valor); void etapa_entrada(void); __global__ void inputStage_kernel(int N, int Li,int Dip,int Dop,int P,cuFloatComplex *x,cuFloatComplex *W,cuFloatComplex *y,int *flag_inputstage_1_d,int *flag_inputstage_2_d,int *flag_inputstage_3_d); void etapa_intermedia(void); void etapa_salida(void); __global__ void outputStage_kernel(int N,int Lo,int Dip,int Dop,int P,cuFloatComplex *z,cuFloatComplex *W,cuFloatComplex *X,int *flag_outputstage_1_d,int *flag_outputstage_2_d,int *flag_outputstage_3_d); ////////////////////////////////////////////////////////////////////////// /////////////////////DECLARACIÓN DE VARIABLES GLOBALES//////////////////// ////////////////////////////////////////////////////////////////////////// //cuFloatComplex *x_host; //cuFloatComplex *W_host; //cuFloatComplex *y_host; //cuFloatComplex *z_host; cuFloatComplex *X_host; cuFloatComplex *x_device; float *alea_real,*alea_imag; cuFloatComplex *W_device; cuFloatComplex *y_device; cuFloatComplex *z_device; cuFloatComplex *X_device; cufftComplex *in,*out; int *flag_inputstage_1,*flag_inputstage_2,*flag_inputstage_3,*flag_outputstage_1,*flag_outputstage_2,*flag_outputstage_3; int *flag_inputstage_1_d,*flag_inputstage_2_d,*flag_inputstage_3_d,*flag_outputstage_1_d,*flag_outputstage_2_d,*flag_outputstage_3_d; int Dip,Dop,P,N,Li,Lo; int vF[50]; //Almacena los factores de N int svF; //Almacena el numero de factores de N int Prod[50]; int a; FILE *dc; #define inf 99999 ////////////////////////////////////////////////////////////////////////// //////////////////////////DATOS DE ENTRADA//////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// N >>> Número de elementos del vector de entrada /// Li >>> Número de elementos de entrada diferentes de cero /// Lo >>> Número de elementos de salida requeridos /// loop >>> Número de iteraciones /// muestras >>> Número de muestras ////////////////////////////////////////////////////////////////////////// ///////////////////////////DATOS DE SALIDA//////////////////////////////// ////////////////////////////////////////////////////////////////////////// /// X >>> Vector de salida ////////////////////////////////////////////////////////////////////////// /////////////////// SE INGRESAN LOS DATOS DE ENTRADA ///////////////////// ////////////////////////////////////////////////////////////////////////// ///Ingrese el número de iteraciones requeridas int loop = 1; ///Ingrese el número de muestras requeridas const int muestras = 1; ///Se ingresa la N máxima int N_max = 1024; ////////////////////////////////////////////////////////////////////////// //////////////////////////FUNCION PRINCIPAL/////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Función principal int main() { int i,j,i_N,l_res,j_res,k_res,incremento_j; //float suma; //float promedio[muestras]; ///Se crean los archivos binarios donde se guardarán los datos FILE *da; FILE *db; //FILE *dc; //FILE *dd; FILE *fi_1; FILE *fi_2; FILE *fi_3; FILE *fo_1; FILE *fo_2; FILE *fo_3; da = fopen("Resultados_radix_2_real_CUDA.bin","a+b"); //Crea o sobre escribe archivo db = fopen("Resultados_radix_2_imag_CUDA.bin","a+b"); //Crea o sobre escribe archivo dc = fopen("Entrada_radix_2_CUDA.txt","w+t"); //Crea o sobre escribe archivo //dd = fopen("TIEMPOS_FFT_DIF_DIT_TD_SECUENCIAL_CUDA.bin","a+b"); //Crea o sobre escribe archivo fi_1 = fopen("Flag_inputstage_1_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fi_2 = fopen("Flag_inputstage_2_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fi_3 = fopen("Flag_inputstage_3_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fo_1 = fopen("Flag_outputstage_1_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fo_2 = fopen("Flag_outputstage_2_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo fo_3 = fopen("Flag_outputstage_3_radix_2_CUDA.bin","a+b"); //Crea o sobre escribe archivo //Se generan en el device los valores del vector de entrada x[n] vector_entrada_xn(N_max); fclose(dc); //Pausa printf("\n---PRESIONA UNA TECLA PARA CONTINUAR---\n\n"); getchar(); //Se reserva espacio para las flags flag_inputstage_1 = (int *)malloc(1*sizeof(int)); flag_inputstage_2 = (int *)malloc(1*sizeof(int)); flag_inputstage_3 = (int *)malloc(1*sizeof(int)); flag_outputstage_1 = (int *)malloc(1*sizeof(int)); flag_outputstage_2 = (int *)malloc(1*sizeof(int)); flag_outputstage_3 = (int *)malloc(1*sizeof(int)); cudaMalloc((int**)&flag_inputstage_1_d,1*sizeof(int)); cudaMalloc((int**)&flag_inputstage_2_d,1*sizeof(int)); cudaMalloc((int**)&flag_inputstage_3_d,1*sizeof(int)); cudaMalloc((int**)&flag_outputstage_1_d,1*sizeof(int)); cudaMalloc((int**)&flag_outputstage_2_d,1*sizeof(int)); cudaMalloc((int**)&flag_outputstage_3_d,1*sizeof(int)); //Inicializaciones incremento_j = 1; flag_inputstage_1[0] = 0; flag_inputstage_2[0] = 0; flag_inputstage_3[0] = 0; flag_outputstage_1[0] = 0; flag_outputstage_2[0] = 0; flag_outputstage_3[0] = 0; for(i_N = 1;i_N <= 10;i_N++) { N = (int )pow(2,i_N); printf("\n N = %d \n",N); //Se genera el arreglo W[N] en el device arreglo_W(N); for(j_res=incremento_j;j_res<=N;j_res=j_res+incremento_j) { Li=j_res; for(k_res=incremento_j;k_res<=N;k_res=k_res+incremento_j) { Lo=k_res; //printf("\n Li = %d Lo = %d",Li,Lo); for(i=1;i<=muestras;i++) { //suma=0.0; for(j=0;j<loop;j++) { //Comandos necesarios para medir el tiempo //float elapsedTime_app; //cudaEvent_t start_app, stop_app; //cudaEventCreate(&start_app); //cudaEventCreate(&stop_app); //--------------------------------------------------------------------------------------------- //Se empieza a medir el tiempo de ejecucion de la aplicacion //cudaEventRecord(start_app,0); //Se generan en el host los factores Dip y Dop asign_rap(N,Li,Lo); //Cálculo en el host del factor P P = N/(Dip*Dop); //printf("\n\n FACTOR P:\n\n"); //printf("\n Dip = %d Dop = %d P = %d ",Dip,Dop,P); //Función auxiliar del host para ejecutar la etapa de entrada etapa_entrada(); //Función auxiliar del host para ejecutar la etapa intermedia etapa_intermedia(); //Función auxiliar del host para ejecutar la etapa de salida etapa_salida(); ///Se imprimen los resultados en los archivos binarios int m; float *parte_real; float *parte_imag; parte_real = (float*) malloc(Lo*sizeof(float)); parte_imag = (float*) malloc(Lo*sizeof(float)); for(m=0;m<=Lo-1;m++) { parte_real[m]=cuCrealf(X_host[m]); parte_imag[m]=cuCimagf(X_host[m]); //printf("\n X[%d] = %.4f + (%.4f)",m,creal(X[m]),cimag(X[m])); //fprintf(dc,"%f %f\n",creal(X[m]),cimag(X[m])); } fwrite(parte_real,sizeof(float),Lo,da); fwrite(parte_imag,sizeof(float),Lo,db); ///Se leen los valores de las flags desde el device cudaMemcpy(flag_inputstage_1,flag_inputstage_1_d,1*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(flag_inputstage_2,flag_inputstage_2_d,1*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(flag_inputstage_3,flag_inputstage_3_d,1*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(flag_outputstage_1,flag_outputstage_1_d,1*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(flag_outputstage_2,flag_outputstage_2_d,1*sizeof(int),cudaMemcpyDeviceToHost); cudaMemcpy(flag_outputstage_3,flag_outputstage_3_d,1*sizeof(int),cudaMemcpyDeviceToHost); ///Se imprimen el valor de las flags en sus respectivos archivos binarios fwrite(flag_inputstage_1,1*sizeof(int),1,fi_1); fwrite(flag_inputstage_2,1*sizeof(int),1,fi_2); fwrite(flag_inputstage_3,1*sizeof(int),1,fi_3); fwrite(flag_outputstage_1,1*sizeof(int),1,fo_1); fwrite(flag_outputstage_2,1*sizeof(int),1,fo_2); fwrite(flag_outputstage_3,1*sizeof(int),1,fo_3); /* printf("\n flag_inputstage_1 = %d \n",flag_inputstage_1[0]); printf("\n flag_inputstage_2 = %d \n",flag_inputstage_2[0]); printf("\n flag_inputstage_3 = %d \n",flag_inputstage_3[0]); printf("\n flag_outputstage_1 = %d \n",flag_outputstage_1[0]); printf("\n flag_outputstage_2 = %d \n",flag_outputstage_2[0]); printf("\n flag_outputstage_3 = %d \n",flag_outputstage_3[0]); */ //Se liberan memorias del Host y Device //free(x_host); //free(W_host); //free(y_host); //free(z_host); free(X_host); free(parte_real); free(parte_imag); //cudaFree(x_device); //cudaFree(W_device); cudaFree(y_device); cudaFree(z_device); cudaFree(X_device); //--------------------------------------------------------------------------------------------- //Comandos necesarios para medir el tiempo de la aplicacion (app) //cudaEventRecord(stop_app,0); //cudaEventSynchronize(stop_app); //cudaEventElapsedTime(&elapsedTime_app,start_app,stop_app); //Suma de todos los tiempos //suma = suma + elapsedTime_app; //Se destruyen los eventos que miden el tiempo de la aplicacion //cudaEventDestroy(start_app); //cudaEventDestroy(stop_app); ///Se resetean las flags flag_inputstage_1[0] = 0; flag_inputstage_2[0] = 0; flag_inputstage_3[0] = 0; flag_outputstage_1[0] = 0; flag_outputstage_2[0] = 0; flag_outputstage_3[0] = 0; } //promedio[i-1] = suma/(float)loop; //printf(" \n\n%d - Tiempo promedio para N = %ld >>> %f mS\n",i,N,promedio[i-1]); } //fwrite(promedio,sizeof(float),muestras,dd); //fclose(dd); } } //free(x_host); //free(W_host); cudaFree(x_device); cudaFree(W_device); } fclose(da); fclose(db); fclose(fi_1); fclose(fi_2); fclose(fi_3); fclose(fo_1); fclose(fo_2); fclose(fo_3); free(flag_inputstage_1); free(flag_inputstage_2); free(flag_inputstage_3); free(flag_outputstage_1); free(flag_outputstage_2); free(flag_outputstage_3); cudaFree(flag_inputstage_1_d); cudaFree(flag_inputstage_2_d); cudaFree(flag_inputstage_3_d); cudaFree(flag_outputstage_1_d); cudaFree(flag_outputstage_2_d); cudaFree(flag_outputstage_3_d); return EXIT_SUCCESS; } ////////////////////////////////////////////////////////////////////////// /////////////////////////FUNCIONES SECUNDARIAS//////////////////////////// ////////////////////////////////////////////////////////////////////////// //Ésta función genera el vector de entrada x[n] void vector_entrada_xn(int N_max) { //CUDA's random number library uses curandState_t to keep track of the seed value //we will stor3e a random state for every thread curandState_t *states; //Allocate space on the GPU for the random states cudaMalloc((void**) &states,N_max*sizeof(curandState_t)); //Se reserva memoria para x_device cudaMalloc((void**)&x_device,N_max*sizeof(cuFloatComplex)); cudaMalloc((void**)&alea_real,N_max*sizeof(float)); cudaMalloc((void**)&alea_imag,N_max*sizeof(float)); //Dimensionamiento del grid para la función kernel "inputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((N_max) < 1024) { blockDim.x = N_max; gridDim.x = 1; } else { blockDim.x = 1024; gridDim.x = (unsigned int) (ceilf((float)N_max/(float)blockDim.x)); } //Invoke the GPU to initialize all of the random states init<<<gridDim,blockDim>>>(time(0),states,N_max); //Esperar que el kernel termine de ejecutarse totalmente cudaDeviceSynchronize(); //Lanzamiento del kernel "entrada_xn_kernel" entrada_xn_kernel<<<gridDim,blockDim>>>(N_max,alea_real,alea_imag,x_device,dc,states); //Esperar que el kernel termine de ejecutarse totalmente cudaDeviceSynchronize(); cudaFree(alea_real); cudaFree(alea_imag); cudaFree(states); } /* this GPU kernel function is used to initialize the random states */ __global__ void init(unsigned int seed, curandState_t *states,int N_max) { //Threads int i = blockDim.x *blockIdx.x + threadIdx.x; if(i < N_max) { /* 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 */ i, /* 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[i]); } } //Función kernel para xn_device __global__ void entrada_xn_kernel(int N_max,float *alea_real,float *alea_imag,cuFloatComplex *x_device,FILE *dc,curandState_t *states) { //Threads int i = blockDim.x *blockIdx.x + threadIdx.x; if(i < N_max) { alea_real[i]=curand(&states[i]) % 11; //alea_real[i]=i+1; alea_imag[i]=curand(&states[i]) % 11; //alea_imag[i]=0; fprintf(dc,"%d %d\n",alea_real[i],alea_imag[i]); x_device[i] = make_cuFloatComplex((float)alea_real[i],(float)alea_imag[i]); } } //Ésta función genera el arreglo W void arreglo_W(int N) { //Se reserva memoria para W_host cudaMalloc((void**)&W_device,N*sizeof(cuFloatComplex)); //Dimensionamiento del grid para la función kernel "inputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((N) < 1024) { blockDim.x = N; gridDim.x = 1; } else { blockDim.x = 1024; gridDim.x = (unsigned int) (ceilf((float)N/(float)blockDim.x)); } //Lanzamiento del kernel "entrada_xn_kernel" arreglo_W_kernel<<<gridDim,blockDim>>>(N,W_device); //Esperar que el kernel termine de ejecutarse totalmente cudaDeviceSynchronize(); } //Función kernel para W_device __global__ void arreglo_W_kernel(int N,cuFloatComplex *W_device) { //Threads int n = blockDim.x *blockIdx.x + threadIdx.x; if(n < N) { W_device[n] = make_cuFloatComplex((float)cos((2*CUDART_PI*(n+1))/N),(float)(-1)*sin((2*CUDART_PI*(n+1))/N)); } } //Ésta función genera los factores Dip y Dop void asign_rap(int N,int Li,int Lo) { //Declaración de variables locales float NLi,NLo,Diprapt,Doprapt; int Nh[50]; int k[50]; int G; int g,i,t,ta; int Dipt[50],Dopt[50]; float distrapt,distrap; int Pos,h,Poss; int nk[50]; int r; //Inicializaciones G = 0; svF = 0; //Factores Dip y Dop ideales NLi=(float)N/(float)Li; NLo=(float)N/(float)Lo; Diprapt=NLi; Doprapt=NLo; //Se encuentran los factores de "N" //vF almacena los factores de "N" //svF almacena el número de factores de "N" factor(N); /* Almacena en el vector Nh los factores que son diferentes de del vector vF En el vector k se almacena la cantidad de veces que se repite cada elemento almacenado en el vector Nh. */ Nh[0] = vF[0]; k[0]=1; for(g=1;g<=svF-1;g=g+1) { if(vF[g]!=vF[g-1]) { G=G+1; Nh[G]=vF[g]; k[G]=1; } else { k[G]=k[G]+1; } } /* Almacena en el vector Nh todas las posibles combinaciones que den como producto a N. t almacena el numero de elementos del vector Nh. */ product(Nh,k,G); t = a; for(i=0;i<t;i=i+1) { Dipt[i]=Prod[i]; } distrapt=inf; for(g=1;g<=t;g=g+1) { if(Dipt[g-1]<=NLi) { Pos=g-1; for(h=0;h<=G;h=h+1) { Poss=floor(Pos/(k[h]+1)); nk[h]=k[h]+Poss*(k[h]+1)-Pos; Pos=Poss; } product(Nh,nk,G); ta=a; for(i=0;i<ta;i=i+1) { Dopt[i]=Prod[i]; } //////////////////////////////////////////// //int j; //for(j=0;j<ta;j++) //{ // printf(" %d ",Dopt[j]); //} //printf("\n\n ta=%d\n\n",ta); /////////////////////////////////////////// for(r=0;r<ta;r=r+1) { distrap=sqrt(pow(Diprapt-(Dipt[g-1]),2)+pow(Doprapt-(Dopt[r]),2)); if(distrap<distrapt) { distrapt=distrap; Dip=Dipt[g-1]; Dop=Dopt[r]; } } } } /* printf("\n\n FACTOR Dip :\n\n"); printf(" %d ",Dip); printf("\n\n FACTOR Dop:\n\n"); printf(" %d ",Dop); */ } //Ésta función encuentra los factores de "N" void factor(int N) { //Se empieza a verificar los factores desde 2 int i=2; long N_factor; N_factor = N; while(i<=N_factor) { while((N_factor%i)==0) { vF[svF]=i; N_factor=N_factor/i; // printf("Factores: %d ",vF[svF]); svF++; } i++; } } //Ésta función encuentra todas las posibles combinaciones de factores que den como resultado "N" void product(int vector_1[50],int vector_2[50],int valor) { int d,e,s,pNh,i; int cont=0; Prod[0]=1; a=1; for(d=0;d<=valor;d=d+1) { s=a; pNh=1; for(e=1;e<=vector_2[d];e=e+1) { pNh=pNh*vector_1[d]; for(i=(s*e+1);i<=(s*e+s);i=i+1) { Prod[i-1]=pNh*Prod[cont]; cont=cont+1; } a=a+s; cont=0; } } } //Función auxiliar del host para calcular la etapa de entrada en el device void etapa_entrada(void) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////ETAPA DE ENTRADA////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Declaración de variables locales int k1,n1,n2; //Asignación de memoria en el device cudaMalloc((void**)&y_device,P*Dip*Dop*sizeof(cuFloatComplex)); //Asignación de memoria en el host para "y" //y_host = (cuFloatComplex*)malloc(sizeof(cuFloatComplex)*P*Dip*Dop); //Dimensionamiento del grid para la función kernel "inputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((P*Dop) < 32 && (Dip) < 32) { blockDim.x = (P*Dop); blockDim.y = (Dip); gridDim.x = 1; gridDim.y = 1; } else { blockDim.x = 32; blockDim.y = 32; gridDim.x = (unsigned int) (ceilf((float)(P*Dop)/(float)blockDim.x)); gridDim.y = (unsigned int) (ceilf((float)Dip/(float)blockDim.y)); } //Lanzamiento del kernel "inputStage_kernel" inputStage_kernel<<<gridDim,blockDim>>>(N,Li,Dip,Dop,P,x_device,W_device,y_device,flag_inputstage_1_d,flag_inputstage_2_d,flag_inputstage_3_d); //Esperar que el kernel termine de ejecutarse totalmente cudaDeviceSynchronize(); /* //Copia del arreglo "y" del device hacia el host cudaMemcpy(y_host,y_device,sizeof(cuFloatComplex)*P*Dip*Dop,cudaMemcpyDeviceToHost); //Se imprimen los valores de "y" printf("\n\n--- ARREGLO y(n1,n2,k1) ---\n\n"); for(k1 = 0;k1 < Dip;k1++) { for(n1 = 0;n1 < Dop;n1++) { for(n2 = 0;n2 < P;n2++) { printf(" (%f) + (%f) ",cuCrealf(y_host[(k1*Dop*P)+(n1*P)+n2]),cuCimagf(y_host[(k1*Dop*P)+(n1*P)+n2])); } printf("\n"); } printf("\n\n"); } printf("\n"); */ } //función kernel que ejecuta la etapa de entrada en el device __global__ void inputStage_kernel(int N, int Li,int Dip,int Dop,int P,cuFloatComplex *x,cuFloatComplex *W,cuFloatComplex *y,int *flag_inputstage_1_d,int *flag_inputstage_2_d,int *flag_inputstage_3_d) { int n1,n2; cuFloatComplex t1; //Threads int n = blockDim.x *blockIdx.x + threadIdx.x; int k1 = blockDim.y *blockIdx.y + threadIdx.y; //Se resetean las flags flag_inputstage_1_d[0] = 0; flag_inputstage_2_d[0] = 0; flag_inputstage_3_d[0] = 0; //printf("\n n = %d k1 = %d",n,k1); if( (n < (P*Dop)) && (k1 < Dip)) { n2 = floorf(n/Dop); n1 = n - (Dop*n2); //Generación de los elementos que dependen de x[0] if(n == 0) { y[(k1*Dop*P)+(0*P)+ 0] = x[0]; ///Flag flag_inputstage_1_d[0] = 1; } //Mapeo de x[n] a las entradas del primer conjunto de Dop DFT's if((n >= 1) && (n <= (Li-1))) { t1 = x[n]; if(k1 == 0) { y[(0*Dop*P)+(n1*P)+ n2] = t1; } if(k1 >= 1) { y[(k1*Dop*P)+(n1*P)+ n2] = cuCmulf(W[((n*k1)%N)-1],t1); } ///Flag flag_inputstage_2_d[0] = 1; } //Rellenado de ceros para los elementos de "y" para Li <= n <= (P*Dop)-1 if((n >= Li) && (n <= (P*Dop)-1)) { y[(k1*Dop*P)+(n1*P)+ n2] = make_cuFloatComplex(0.0,0.0); ///Flag flag_inputstage_3_d[0] = 1; } //printf("\n (%f) + (%f)\n ",cuCrealf(y[(k1*Dop*P)+(n1*P)+ n2]),cuCimagf(y[(k1*Dop*P)+(n1*P)+ n2])); } } //Función auxiliar del host para calcular la etapa intermedia en el device void etapa_intermedia(void) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////ETAPA INTERMEDIA////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Declaración de variables locales int k1,k2,n1; int n[1] = {P}; int inembed[1] = {P}; int onembed[1] = {P}; //Asignación de memoria en el device para "z" cudaMalloc((void**)&z_device,P*Dip*Dop*sizeof(cuFloatComplex)); //Asignación de memoria en el host para "z" //z_host = (cuFloatComplex*)malloc(sizeof(cuFloatComplex)*P*Dip*Dop); //Asignación de memoria en el device para "in" y "out" cudaMalloc((void**)&in,sizeof(cufftComplex)*P*Dip*Dop); cudaMalloc((void**)&out,sizeof(cufftComplex)*P*Dip*Dop); //Se copia el arreglo "y" al arreglo "in" cudaMemcpy(in,y_device,sizeof(cuFloatComplex)*P*Dip*Dop,cudaMemcpyDeviceToDevice); //Se crea un plan cufftHandle plan; cufftPlanMany(&plan,1,n,inembed,1,P,onembed,1,P,CUFFT_C2C,Dip*Dop); //Ejecución del plan cufftExecC2C(plan,in,out,CUFFT_FORWARD); //Esperar que el kernel termine de ejecutarse totalmente cudaDeviceSynchronize(); //Se copian los datos del arreglo "out" al arreglo "z_device" cudaMemcpy(z_device,out,sizeof(cufftComplex)*P*Dip*Dop,cudaMemcpyDeviceToDevice); //Se destruye el plan cufftDestroy(plan); //Se liberan los arreglos "in" y "out" cudaFree(in); cudaFree(out); /* //Se copian los datos del arreglo "z_device" al arreglo "z_host" cudaMemcpy(z_host,z_device,sizeof(cuFloatComplex)*P*Dip*Dop,cudaMemcpyDeviceToHost); ///Se imprimen los valores de z(n1,k2,k1) printf("\n\n--- ARREGLO z(n1,k2,k1) ---\n\n"); for(k1 = 0;k1 < Dip;k1++) { for(n1 = 0;n1 < Dop;n1++) { for(k2 = 0;k2 < P;k2++) { printf(" (%f) + (%f) ",cuCrealf(z_host[(k1*Dop*P)+(n1*P)+k2]),cuCimagf(z_host[(k1*Dop*P)+(n1*P)+k2])); } printf("\n"); } printf("\n\n"); } printf("\n"); */ } //Función auxiliar del host para calcular la etapa de salida en el device void etapa_salida(void) { ////////////////////////////////////////////////////////////////////////// ////////////////////////////ETAPA DE SALIDA/////////////////////////////// ////////////////////////////////////////////////////////////////////////// //Declaración de variables locales int m; //Asignación de memoria en el device para "X" cudaMalloc((void**)&X_device,Lo*sizeof(cuFloatComplex)); //Asignación de memoria en el host para "X" X_host = (cuFloatComplex*)malloc(sizeof(cuFloatComplex)*Lo); //Dimensionamiento del grid para la función kernel "outputStage" //Dimensionamiento del Grid dim3 gridDim(1,1,1); //Dimensionamiento del block dim3 blockDim(1,1,1); if((Lo) < 1024) { blockDim.x = Lo; gridDim.x = 1; } else { blockDim.x = 1024; gridDim.x = (unsigned int) (ceilf((float)Lo/(float)blockDim.x)); } //Lanzamiento del kernel "outputStage_kernel" outputStage_kernel<<<gridDim,blockDim>>>(N,Lo,Dip,Dop,P,z_device,W_device,X_device,flag_outputstage_1_d,flag_outputstage_2_d,flag_outputstage_3_d); //Esperar que el kernel termine de ejecutarse totalmente cudaDeviceSynchronize(); //Copia del arreglo "X" del device hacia el host cudaMemcpy(X_host,X_device,sizeof(cuFloatComplex)*Lo,cudaMemcpyDeviceToHost); /* //Se imprimen los valores de "X_host" ///Imprimir X[k] printf("\n\n--- ARREGLO X[k] ---\n\n"); for(m=0;m<=Lo-1;m++) { printf("\n X[%d] = %.4f + (%.4f)",m,cuCrealf(X_host[m]),cuCimagf(X_host[m])); //fprintf(da,"%.4f %.4f\n",creal(X[i]),cimag(X[i])); } */ } //función kernel que ejecuta la etapa de salida en el device __global__ void outputStage_kernel(int N,int Lo,int Dip,int Dop,int P,cuFloatComplex *z,cuFloatComplex *W,cuFloatComplex *X,int *flag_outputstage_1_d,int *flag_outputstage_2_d,int *flag_outputstage_3_d) { //Declaración de variables locales int n1,k_aux,k1,k2,a,b; cuFloatComplex t1,t2,t3,t4,t5; //Threads int k = blockDim.x *blockIdx.x + threadIdx.x; //Se resetean las flags flag_outputstage_1_d[0] = 0; flag_outputstage_2_d[0] = 0; flag_outputstage_3_d[0] = 0; if(k < Lo) { for(n1 = 0; n1 <= (Dop-1); n1 = n1+1) { if(Lo <= Dip) { //Cálculo de X(k) para 0<=k<=Lo-1. //printf("\n--- Caso (Lo <= Dip) ---\n"); //En la descomposición k = k1 + Dipk2; k2 = 0, y por lo tanto, k = k1 if(n1 == 0) //Caso para lograr que por lo menos ingrese una vez { X[k] = z[(k*Dop*P)+(0*P) + 0]; ///Flag flag_outputstage_1_d[0] = 1; } else { if(n1 == 1) { X[k] = z[(k*Dop*P)+(0*P) + 0]; } X[k] = cuCaddf(z[(k*Dop*P)+(n1*P) + 0],X[k]); ///Flag flag_outputstage_1_d[0] = 1; } } else { if((k >= 0) && (k <= (Dip-1))) { //Cálculo de X(k) para 0<=k<=Dip-1. //En la descomposición k = k1 + Dipk2; k2 = 0, y por lo tanto, k = k1 if(n1 == 0) //Caso para lograr que por lo menos ingrese una vez { X[k] = z[(k*Dop*P)+(0*P) + 0]; } else { if(n1 == 1) { X[k] = z[(k*Dop*P)+(0*P) + 0]; } X[k] = cuCaddf(z[(k*Dop*P)+(n1*P) + 0],X[k]); } } else { if(Dop <= 4) { //Usando el método directo //printf("\n--- Caso (Metodo directo) ---\n"); if(n1 == 0) //Caso para lograr que por lo menos ingrese una vez { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); X[k] = z[(k1*Dop*P)+(0*P)+ (k2%P)]; ///Flag flag_outputstage_2_d[0] = 1; } else { if(n1 == 1) { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); X[k] = z[(k1*Dop*P)+(0*P)+ (k2%P)]; } a = floorf(k/(Dip*P)); X[k] = cuCaddf(X[k],cuCmulf(z[(k1*Dop*P)+(n1*P)+ (k2%P)],W[((n1*(k2+P*(a))*Dip)%N)-1])); ///Flag flag_outputstage_2_d[0] = 1; } } else { //Usando el método filtering 2BF //printf("\n--- Caso (Filtro 2BF) ---\n"); if((Dop-2) >= 1) { if(n1 == 0) { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); t1 = z[(k1*Dop*P)+((Dop-1)*P)+ (k2%P)]; b = floorf(k/(Dip*P)); t4 = cuCmulf(t1,make_cuFloatComplex(2*cuCrealf(W[(((k2+P*(b))*Dip)%N)-1]),0.0)); ///Flag flag_outputstage_3_d[0] = 1; } if((n1 >= 1) && (n1 <= (Dop-2))) { t2 = t1; t1 = cuCaddf(z[(k1*Dop*P)+((-(n1-(Dop-1)))*P)+ (k2%P)],t4); t3 = cuCmulf(t1,make_cuFloatComplex(2*cuCrealf(W[(((k2+P*(b))*Dip)%N)-1]),0.0)); t4 = cuCsubf(t3,t2); } if(n1 == (Dop-1)) { t5 = cuCaddf(z[(k1*Dop*P)+(0*P)+ (k2%P)],t4); X[k] = cuCsubf(t5,cuCmulf(t1,cuConjf(W[(((k2+P*(b))*Dip)%N)-1]))); } } else { if(Dop == 1) { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); t1 = z[(k1*Dop*P)+((Dop-1)*P)+ (k2%P)]; X[k] = t1; ///Flag flag_outputstage_3_d[0] = 1; } else { k_aux = k-((Dip*P)*floorf(k/(Dip*P))); k2 = floorf(k_aux/Dip); k1 = k_aux-(Dip*k2); t1 = z[(k1*Dop*P)+((Dop-1)*P)+ (k2%P)]; b = floorf(k/(Dip*P)); t4 = cuCmulf(t1,make_cuFloatComplex(2*cuCrealf(W[(((k2+P*(b))*Dip)%N)-1]),0.0)); t5 = cuCaddf(z[(k1*Dop*P)+(0*P)+ (k2%P)],t4); X[k] = cuCsubf(t5,cuCmulf(t1,cuConjf(W[(((k2+P*(b))*Dip)%N)-1]))); ///Flag flag_outputstage_3_d[0] = 1; } } } } } } } }
e40040273426f1718781afe49b36ef9fd62829ad.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" extern "C" { typedef struct { double e0; double e1; double e2; } struct_vec_9645; typedef struct { double e0; struct_vec_9645 e1; struct_vec_9645 e2; int e3; } struct_Isect_9647; __device__ inline int threadIdx_x() { return threadIdx.x; } __device__ inline int threadIdx_y() { return threadIdx.y; } __device__ inline int threadIdx_z() { return threadIdx.z; } __device__ inline int blockIdx_x() { return blockIdx.x; } __device__ inline int blockIdx_y() { return blockIdx.y; } __device__ inline int blockIdx_z() { return blockIdx.z; } __device__ inline int blockDim_x() { return blockDim.x; } __device__ inline int blockDim_y() { return blockDim.y; } __device__ inline int blockDim_z() { return blockDim.z; } __device__ inline int gridDim_x() { return gridDim.x; } __device__ inline int gridDim_y() { return gridDim.y; } __device__ inline int gridDim_z() { return gridDim.z; } __global__ void lambda_71814(unsigned long*, unsigned char*); __global__ __launch_bounds__ (32 * 4 * 1) void lambda_71814(unsigned long* _71817_104835, unsigned char* _71818_104836) { int threadIdx_y_104842; int pthreadIdx_y_104842; int blockDim_y_104848; int pblockDim_y_104848; int blockIdx_y_104854; int pblockIdx_y_104854; int threadIdx_x_104860; int pthreadIdx_x_104860; int blockDim_x_104866; int pblockDim_x_104866; int blockIdx_x_104872; int pblockIdx_x_104872; int threadIdx_x_104886; int pthreadIdx_x_104886; int blockDim_x_104889; int pblockDim_x_104889; int blockIdx_x_104892; int pblockIdx_x_104892; int threadIdx_y_104895; int pthreadIdx_y_104895; int blockDim_y_104898; int pblockDim_y_104898; int blockIdx_y_104901; int pblockIdx_y_104901; int lower_104904; int plower_104904; int upper_104905; int pupper_104905; int step_104906; int pstep_104906; double r_104907; double pr_104907; double g_104908; double pg_104908; double b_104909; double pb_104909; unsigned long state_104910; unsigned long pstate_104910; int _107577; int p_107577; int _107582; int p_107582; int _107589; int p_107589; int _107593; int p_107593; int _107600; int p_107600; int _107604; int p_107604; int threadIdx_y_107607; int pthreadIdx_y_107607; int blockDim_y_107610; int pblockDim_y_107610; int blockIdx_y_107613; int pblockIdx_y_107613; int threadIdx_x_107616; int pthreadIdx_x_107616; int blockDim_x_107619; int pblockDim_x_107619; int blockIdx_x_107622; int pblockIdx_x_107622; int threadIdx_y_107636; int pthreadIdx_y_107636; int blockDim_y_107639; int pblockDim_y_107639; int blockIdx_y_107642; int pblockIdx_y_107642; int threadIdx_x_107645; int pthreadIdx_x_107645; int blockDim_x_107648; int pblockDim_x_107648; int blockIdx_x_107651; int pblockIdx_x_107651; int threadIdx_y_107665; int pthreadIdx_y_107665; int blockDim_y_107668; int pblockDim_y_107668; int blockIdx_y_107671; int pblockIdx_y_107671; int threadIdx_x_107674; int pthreadIdx_x_107674; int blockDim_x_107677; int pblockDim_x_107677; int blockIdx_x_107680; int pblockIdx_x_107680; int lower_104915; int plower_104915; int upper_104916; int pupper_104916; int step_104917; int pstep_104917; double r_104918; double pr_104918; double g_104919; double pg_104919; double b_104920; double pb_104920; unsigned long state_104921; unsigned long pstate_104921; double length_104955; double plength_104955; double _104962; double p_104962; struct_vec_9645 vnormalize_104968; struct_vec_9645 pvnormalize_104968; double _104988; double p_104988; double length_105014; double plength_105014; double _105017; double p_105017; struct_vec_9645 vnormalize_105022; struct_vec_9645 pvnormalize_105022; struct_Isect_9647 ray_sphere_intersect_105025; struct_Isect_9647 pray_sphere_intersect_105025; double _105039; double p_105039; double length_105065; double plength_105065; double _105068; double p_105068; struct_vec_9645 vnormalize_105073; struct_vec_9645 pvnormalize_105073; struct_Isect_9647 ray_sphere_intersect_105076; struct_Isect_9647 pray_sphere_intersect_105076; double _105090; double p_105090; double length_105115; double plength_105115; double _105118; double p_105118; struct_vec_9645 vnormalize_105123; struct_vec_9645 pvnormalize_105123; struct_Isect_9647 ray_sphere_intersect_105126; struct_Isect_9647 pray_sphere_intersect_105126; double _105134; double p_105134; struct_Isect_9647 ray_plane_intersect_105145; struct_Isect_9647 pray_plane_intersect_105145; double _105160; double p_105160; double _105161; double p_105161; double _105162; double p_105162; double length_105181; double plength_105181; double _105184; double p_105184; struct_vec_9645 vnormalize_105189; struct_vec_9645 pvnormalize_105189; double length_105209; double plength_105209; double _105212; double p_105212; struct_vec_9645 vnormalize_105217; struct_vec_9645 pvnormalize_105217; int lower_105220; int plower_105220; int upper_105221; int pupper_105221; int step_105222; int pstep_105222; double occlusion_105223; double pocclusion_105223; unsigned long state_105224; unsigned long pstate_105224; double r_107461; double pr_107461; double g_107462; double pg_107462; double b_107463; double pb_107463; unsigned long state_107464; unsigned long pstate_107464; double theta_105239; double ptheta_105239; double _105258; double p_105258; double _105265; double p_105265; double z_105270; double pz_105270; double _105323; double p_105323; double length_105346; double plength_105346; double _105349; double p_105349; struct_vec_9645 vnormalize_105354; struct_vec_9645 pvnormalize_105354; struct_Isect_9647 ray_sphere_intersect_105357; struct_Isect_9647 pray_sphere_intersect_105357; double _105375; double p_105375; double length_105399; double plength_105399; double _105402; double p_105402; struct_vec_9645 vnormalize_105407; struct_vec_9645 pvnormalize_105407; struct_Isect_9647 ray_sphere_intersect_105410; struct_Isect_9647 pray_sphere_intersect_105410; double _105428; double p_105428; double length_105452; double plength_105452; double _105455; double p_105455; struct_vec_9645 vnormalize_105460; struct_vec_9645 pvnormalize_105460; struct_Isect_9647 ray_sphere_intersect_105463; struct_Isect_9647 pray_sphere_intersect_105463; double _105471; double p_105471; struct_Isect_9647 ray_plane_intersect_105489; struct_Isect_9647 pray_plane_intersect_105489; double occlusion_105495; double pocclusion_105495; double theta_105507; double ptheta_105507; double _105520; double p_105520; double _105523; double p_105523; double z_105528; double pz_105528; double _105557; double p_105557; double length_105580; double plength_105580; double _105583; double p_105583; struct_vec_9645 vnormalize_105588; struct_vec_9645 pvnormalize_105588; struct_Isect_9647 ray_sphere_intersect_105591; struct_Isect_9647 pray_sphere_intersect_105591; double _105602; double p_105602; double length_105626; double plength_105626; double _105629; double p_105629; struct_vec_9645 vnormalize_105634; struct_vec_9645 pvnormalize_105634; struct_Isect_9647 ray_sphere_intersect_105637; struct_Isect_9647 pray_sphere_intersect_105637; double _105648; double p_105648; double length_105672; double plength_105672; double _105675; double p_105675; struct_vec_9645 vnormalize_105680; struct_vec_9645 pvnormalize_105680; struct_Isect_9647 ray_sphere_intersect_105683; struct_Isect_9647 pray_sphere_intersect_105683; double _105691; double p_105691; struct_Isect_9647 ray_plane_intersect_105702; struct_Isect_9647 pray_plane_intersect_105702; double occlusion_105708; double pocclusion_105708; double theta_105720; double ptheta_105720; double _105733; double p_105733; double _105736; double p_105736; double z_105741; double pz_105741; double _105770; double p_105770; double length_105793; double plength_105793; double _105796; double p_105796; struct_vec_9645 vnormalize_105801; struct_vec_9645 pvnormalize_105801; struct_Isect_9647 ray_sphere_intersect_105804; struct_Isect_9647 pray_sphere_intersect_105804; double _105815; double p_105815; double length_105839; double plength_105839; double _105842; double p_105842; struct_vec_9645 vnormalize_105847; struct_vec_9645 pvnormalize_105847; struct_Isect_9647 ray_sphere_intersect_105850; struct_Isect_9647 pray_sphere_intersect_105850; double _105861; double p_105861; double length_105885; double plength_105885; double _105888; double p_105888; struct_vec_9645 vnormalize_105893; struct_vec_9645 pvnormalize_105893; struct_Isect_9647 ray_sphere_intersect_105896; struct_Isect_9647 pray_sphere_intersect_105896; double _105904; double p_105904; struct_Isect_9647 ray_plane_intersect_105915; struct_Isect_9647 pray_plane_intersect_105915; double occlusion_105921; double pocclusion_105921; double theta_105933; double ptheta_105933; double _105946; double p_105946; double _105949; double p_105949; double z_105954; double pz_105954; double _105983; double p_105983; double length_106006; double plength_106006; double _106009; double p_106009; struct_vec_9645 vnormalize_106014; struct_vec_9645 pvnormalize_106014; struct_Isect_9647 ray_sphere_intersect_106017; struct_Isect_9647 pray_sphere_intersect_106017; double _106028; double p_106028; double length_106052; double plength_106052; double _106055; double p_106055; struct_vec_9645 vnormalize_106060; struct_vec_9645 pvnormalize_106060; struct_Isect_9647 ray_sphere_intersect_106063; struct_Isect_9647 pray_sphere_intersect_106063; double _106074; double p_106074; double length_106098; double plength_106098; double _106101; double p_106101; struct_vec_9645 vnormalize_106106; struct_vec_9645 pvnormalize_106106; struct_Isect_9647 ray_sphere_intersect_106109; struct_Isect_9647 pray_sphere_intersect_106109; double _106117; double p_106117; struct_Isect_9647 ray_plane_intersect_106128; struct_Isect_9647 pray_plane_intersect_106128; double occlusion_106134; double pocclusion_106134; double theta_106146; double ptheta_106146; double _106159; double p_106159; double _106162; double p_106162; double z_106167; double pz_106167; double _106196; double p_106196; double length_106219; double plength_106219; double _106222; double p_106222; struct_vec_9645 vnormalize_106227; struct_vec_9645 pvnormalize_106227; struct_Isect_9647 ray_sphere_intersect_106230; struct_Isect_9647 pray_sphere_intersect_106230; double _106241; double p_106241; double length_106265; double plength_106265; double _106268; double p_106268; struct_vec_9645 vnormalize_106273; struct_vec_9645 pvnormalize_106273; struct_Isect_9647 ray_sphere_intersect_106276; struct_Isect_9647 pray_sphere_intersect_106276; double _106287; double p_106287; double length_106311; double plength_106311; double _106314; double p_106314; struct_vec_9645 vnormalize_106319; struct_vec_9645 pvnormalize_106319; struct_Isect_9647 ray_sphere_intersect_106322; struct_Isect_9647 pray_sphere_intersect_106322; double _106330; double p_106330; struct_Isect_9647 ray_plane_intersect_106341; struct_Isect_9647 pray_plane_intersect_106341; double occlusion_106347; double pocclusion_106347; double theta_106359; double ptheta_106359; double _106372; double p_106372; double _106375; double p_106375; double z_106380; double pz_106380; double _106409; double p_106409; double length_106432; double plength_106432; double _106435; double p_106435; struct_vec_9645 vnormalize_106440; struct_vec_9645 pvnormalize_106440; struct_Isect_9647 ray_sphere_intersect_106443; struct_Isect_9647 pray_sphere_intersect_106443; double _106454; double p_106454; double length_106478; double plength_106478; double _106481; double p_106481; struct_vec_9645 vnormalize_106486; struct_vec_9645 pvnormalize_106486; struct_Isect_9647 ray_sphere_intersect_106489; struct_Isect_9647 pray_sphere_intersect_106489; double _106500; double p_106500; double length_106524; double plength_106524; double _106527; double p_106527; struct_vec_9645 vnormalize_106532; struct_vec_9645 pvnormalize_106532; struct_Isect_9647 ray_sphere_intersect_106535; struct_Isect_9647 pray_sphere_intersect_106535; double _106543; double p_106543; struct_Isect_9647 ray_plane_intersect_106554; struct_Isect_9647 pray_plane_intersect_106554; double occlusion_106560; double pocclusion_106560; double theta_106572; double ptheta_106572; double _106585; double p_106585; double _106588; double p_106588; double z_106593; double pz_106593; double _106622; double p_106622; double length_106645; double plength_106645; double _106648; double p_106648; struct_vec_9645 vnormalize_106653; struct_vec_9645 pvnormalize_106653; struct_Isect_9647 ray_sphere_intersect_106656; struct_Isect_9647 pray_sphere_intersect_106656; double _106667; double p_106667; double length_106691; double plength_106691; double _106694; double p_106694; struct_vec_9645 vnormalize_106699; struct_vec_9645 pvnormalize_106699; struct_Isect_9647 ray_sphere_intersect_106702; struct_Isect_9647 pray_sphere_intersect_106702; double _106713; double p_106713; double length_106737; double plength_106737; double _106740; double p_106740; struct_vec_9645 vnormalize_106745; struct_vec_9645 pvnormalize_106745; struct_Isect_9647 ray_sphere_intersect_106748; struct_Isect_9647 pray_sphere_intersect_106748; double _106756; double p_106756; struct_Isect_9647 ray_plane_intersect_106767; struct_Isect_9647 pray_plane_intersect_106767; double occlusion_106773; double pocclusion_106773; double theta_106785; double ptheta_106785; double _106798; double p_106798; double _106801; double p_106801; double z_106806; double pz_106806; double _106835; double p_106835; double length_106858; double plength_106858; double _106861; double p_106861; struct_vec_9645 vnormalize_106866; struct_vec_9645 pvnormalize_106866; struct_Isect_9647 ray_sphere_intersect_106869; struct_Isect_9647 pray_sphere_intersect_106869; double _106880; double p_106880; double length_106904; double plength_106904; double _106907; double p_106907; struct_vec_9645 vnormalize_106912; struct_vec_9645 pvnormalize_106912; struct_Isect_9647 ray_sphere_intersect_106915; struct_Isect_9647 pray_sphere_intersect_106915; double _106926; double p_106926; double length_106950; double plength_106950; double _106953; double p_106953; struct_vec_9645 vnormalize_106958; struct_vec_9645 pvnormalize_106958; struct_Isect_9647 ray_sphere_intersect_106961; struct_Isect_9647 pray_sphere_intersect_106961; double _106969; double p_106969; struct_Isect_9647 ray_plane_intersect_106980; struct_Isect_9647 pray_plane_intersect_106980; double occlusion_106986; double pocclusion_106986; threadIdx_y_104842 = threadIdx_y(); pthreadIdx_y_104842 = threadIdx_y_104842; l104840: ; threadIdx_y_104842 = pthreadIdx_y_104842; blockDim_y_104848 = blockDim_y(); pblockDim_y_104848 = blockDim_y_104848; l104846: ; blockDim_y_104848 = pblockDim_y_104848; blockIdx_y_104854 = blockIdx_y(); pblockIdx_y_104854 = blockIdx_y_104854; l104852: ; blockIdx_y_104854 = pblockIdx_y_104854; threadIdx_x_104860 = threadIdx_x(); pthreadIdx_x_104860 = threadIdx_x_104860; l104858: ; threadIdx_x_104860 = pthreadIdx_x_104860; blockDim_x_104866 = blockDim_x(); pblockDim_x_104866 = blockDim_x_104866; l104864: ; blockDim_x_104866 = pblockDim_x_104866; blockIdx_x_104872 = blockIdx_x(); pblockIdx_x_104872 = blockIdx_x_104872; l104870: ; blockIdx_x_104872 = pblockIdx_x_104872; int _104877; _104877 = blockDim_x_104866 * blockIdx_x_104872; int _104874; _104874 = blockDim_y_104848 * blockIdx_y_104854; int _104875; _104875 = threadIdx_y_104842 + _104874; int _104878; _104878 = threadIdx_x_104860 + _104877; int _104876; _104876 = 256 * _104875; int _104879; _104879 = _104876 + _104878; unsigned long* _104880; _104880 = _71817_104835 + _104879; unsigned long _104881; _104881 = *_104880; threadIdx_x_104886 = threadIdx_x(); pthreadIdx_x_104886 = threadIdx_x_104886; l104884: ; threadIdx_x_104886 = pthreadIdx_x_104886; blockDim_x_104889 = blockDim_x(); pblockDim_x_104889 = blockDim_x_104889; l104887: ; blockDim_x_104889 = pblockDim_x_104889; blockIdx_x_104892 = blockIdx_x(); pblockIdx_x_104892 = blockIdx_x_104892; l104890: ; blockIdx_x_104892 = pblockIdx_x_104892; threadIdx_y_104895 = threadIdx_y(); pthreadIdx_y_104895 = threadIdx_y_104895; l104893: ; threadIdx_y_104895 = pthreadIdx_y_104895; blockDim_y_104898 = blockDim_y(); pblockDim_y_104898 = blockDim_y_104898; l104896: ; blockDim_y_104898 = pblockDim_y_104898; blockIdx_y_104901 = blockIdx_y(); pblockIdx_y_104901 = blockIdx_y_104901; l104899: ; blockIdx_y_104901 = pblockIdx_y_104901; int _104929; _104929 = blockDim_x_104889 * blockIdx_x_104892; unsigned long state_107698; state_107698 = _104881; int _104930; _104930 = threadIdx_x_104886 + _104929; int _104941; _104941 = blockDim_y_104898 * blockIdx_y_104901; double _104931; _104931 = (double)_104930; int _104942; _104942 = threadIdx_y_104895 + _104941; double _104943; _104943 = (double)_104942; plower_104904 = 0; pupper_104905 = 2; pstep_104906 = 1; pr_104907 = 0.000000e+00; pg_104908 = 0.000000e+00; pb_104909 = 0.000000e+00; pstate_104910 = state_107698; goto l104902; l104902: ; lower_104904 = plower_104904; upper_104905 = pupper_104905; step_104906 = pstep_104906; r_104907 = pr_104907; g_104908 = pg_104908; b_104909 = pb_104909; state_104910 = pstate_104910; bool _104911; _104911 = lower_104904 < upper_104905; if (_104911) goto l104912; else goto l107568; l107568: ; double _107571; _107571 = r_104907 / 4.000000e+00; double _107572; _107572 = 2.555000e+02 * _107571; int i_107573; i_107573 = (int)_107572; bool _107574; _107574 = i_107573 < 0; if (_107574) goto l107575; else goto l107697; l107697: ; p_107577 = i_107573; goto l107576; l107575: ; p_107577 = 0; goto l107576; l107576: ; _107577 = p_107577; bool _107579; _107579 = 255 < _107577; if (_107579) goto l107580; else goto l107696; l107696: ; p_107582 = _107577; goto l107581; l107580: ; p_107582 = 255; goto l107581; l107581: ; _107582 = p_107582; double _107583; _107583 = g_104908 / 4.000000e+00; double _107584; _107584 = 2.555000e+02 * _107583; int i_107585; i_107585 = (int)_107584; bool _107586; _107586 = i_107585 < 0; if (_107586) goto l107587; else goto l107695; l107695: ; p_107589 = i_107585; goto l107588; l107587: ; p_107589 = 0; goto l107588; l107588: ; _107589 = p_107589; bool _107590; _107590 = 255 < _107589; if (_107590) goto l107591; else goto l107694; l107694: ; p_107593 = _107589; goto l107592; l107591: ; p_107593 = 255; goto l107592; l107592: ; _107593 = p_107593; double _107594; _107594 = b_104909 / 4.000000e+00; double _107595; _107595 = 2.555000e+02 * _107594; int i_107596; i_107596 = (int)_107595; bool _107597; _107597 = i_107596 < 0; if (_107597) goto l107598; else goto l107693; l107693: ; p_107600 = i_107596; goto l107599; l107598: ; p_107600 = 0; goto l107599; l107599: ; _107600 = p_107600; bool _107601; _107601 = 255 < _107600; if (_107601) goto l107602; else goto l107692; l107692: ; p_107604 = _107600; goto l107603; l107602: ; p_107604 = 255; goto l107603; l107603: ; _107604 = p_107604; threadIdx_y_107607 = threadIdx_y(); pthreadIdx_y_107607 = threadIdx_y_107607; l107605: ; threadIdx_y_107607 = pthreadIdx_y_107607; blockDim_y_107610 = blockDim_y(); pblockDim_y_107610 = blockDim_y_107610; l107608: ; blockDim_y_107610 = pblockDim_y_107610; blockIdx_y_107613 = blockIdx_y(); pblockIdx_y_107613 = blockIdx_y_107613; l107611: ; blockIdx_y_107613 = pblockIdx_y_107613; threadIdx_x_107616 = threadIdx_x(); pthreadIdx_x_107616 = threadIdx_x_107616; l107614: ; threadIdx_x_107616 = pthreadIdx_x_107616; blockDim_x_107619 = blockDim_x(); pblockDim_x_107619 = blockDim_x_107619; l107617: ; blockDim_x_107619 = pblockDim_x_107619; blockIdx_x_107622 = blockIdx_x(); pblockIdx_x_107622 = blockIdx_x_107622; l107620: ; blockIdx_x_107622 = pblockIdx_x_107622; int _107624; _107624 = blockDim_y_107610 * blockIdx_y_107613; int _107627; _107627 = blockDim_x_107619 * blockIdx_x_107622; int _107628; _107628 = threadIdx_x_107616 + _107627; unsigned char _107632; _107632 = (unsigned char)_107582; int _107625; _107625 = threadIdx_y_107607 + _107624; int _107626; _107626 = 256 * _107625; int _107629; _107629 = _107626 + _107628; int _107630; _107630 = 3 * _107629; unsigned char* _107631; _107631 = _71818_104836 + _107630; *_107631 = _107632; threadIdx_y_107636 = threadIdx_y(); pthreadIdx_y_107636 = threadIdx_y_107636; l107634: ; threadIdx_y_107636 = pthreadIdx_y_107636; blockDim_y_107639 = blockDim_y(); pblockDim_y_107639 = blockDim_y_107639; l107637: ; blockDim_y_107639 = pblockDim_y_107639; blockIdx_y_107642 = blockIdx_y(); pblockIdx_y_107642 = blockIdx_y_107642; l107640: ; blockIdx_y_107642 = pblockIdx_y_107642; threadIdx_x_107645 = threadIdx_x(); pthreadIdx_x_107645 = threadIdx_x_107645; l107643: ; threadIdx_x_107645 = pthreadIdx_x_107645; blockDim_x_107648 = blockDim_x(); pblockDim_x_107648 = blockDim_x_107648; l107646: ; blockDim_x_107648 = pblockDim_x_107648; blockIdx_x_107651 = blockIdx_x(); pblockIdx_x_107651 = blockIdx_x_107651; l107649: ; blockIdx_x_107651 = pblockIdx_x_107651; int _107652; _107652 = blockDim_y_107639 * blockIdx_y_107642; int _107655; _107655 = blockDim_x_107648 * blockIdx_x_107651; int _107656; _107656 = threadIdx_x_107645 + _107655; unsigned char _107661; _107661 = (unsigned char)_107593; int _107653; _107653 = threadIdx_y_107636 + _107652; int _107654; _107654 = 256 * _107653; int _107657; _107657 = _107654 + _107656; int _107658; _107658 = 3 * _107657; int _107659; _107659 = 1 + _107658; unsigned char* _107660; _107660 = _71818_104836 + _107659; *_107660 = _107661; threadIdx_y_107665 = threadIdx_y(); pthreadIdx_y_107665 = threadIdx_y_107665; l107663: ; threadIdx_y_107665 = pthreadIdx_y_107665; blockDim_y_107668 = blockDim_y(); pblockDim_y_107668 = blockDim_y_107668; l107666: ; blockDim_y_107668 = pblockDim_y_107668; blockIdx_y_107671 = blockIdx_y(); pblockIdx_y_107671 = blockIdx_y_107671; l107669: ; blockIdx_y_107671 = pblockIdx_y_107671; threadIdx_x_107674 = threadIdx_x(); pthreadIdx_x_107674 = threadIdx_x_107674; l107672: ; threadIdx_x_107674 = pthreadIdx_x_107674; blockDim_x_107677 = blockDim_x(); pblockDim_x_107677 = blockDim_x_107677; l107675: ; blockDim_x_107677 = pblockDim_x_107677; blockIdx_x_107680 = blockIdx_x(); pblockIdx_x_107680 = blockIdx_x_107680; l107678: ; blockIdx_x_107680 = pblockIdx_x_107680; int _107684; _107684 = blockDim_x_107677 * blockIdx_x_107680; int _107681; _107681 = blockDim_y_107668 * blockIdx_y_107671; unsigned char _107690; _107690 = (unsigned char)_107604; int _107685; _107685 = threadIdx_x_107674 + _107684; int _107682; _107682 = threadIdx_y_107665 + _107681; int _107683; _107683 = 256 * _107682; int _107686; _107686 = _107683 + _107685; int _107687; _107687 = 3 * _107686; int _107688; _107688 = 2 + _107687; unsigned char* _107689; _107689 = _71818_104836 + _107688; *_107689 = _107690; return ; l104912: ; double _104944; _104944 = (double)lower_104904; double _104945; _104945 = _104944 / 2.000000e+00; double _104946; _104946 = _104943 + _104945; double _104947; _104947 = _104946 - 1.280000e+02; double _104948; _104948 = -0.000000e+00 - _104947; double py_104949; py_104949 = _104948 / 1.280000e+02; double _104950; _104950 = py_104949 * py_104949; plower_104915 = 0; pupper_104916 = 2; pstep_104917 = 1; pr_104918 = r_104907; pg_104919 = g_104908; pb_104920 = b_104909; pstate_104921 = state_104910; goto l104913; l104913: ; lower_104915 = plower_104915; upper_104916 = pupper_104916; step_104917 = pstep_104917; r_104918 = pr_104918; g_104919 = pg_104919; b_104920 = pb_104920; state_104921 = pstate_104921; bool _104922; _104922 = lower_104915 < upper_104916; if (_104922) goto l104923; else goto l107565; l107565: ; int _107566; _107566 = lower_104904 + step_104906; plower_104904 = _107566; pupper_104905 = upper_104905; pstep_104906 = step_104906; pr_104907 = r_104918; pg_104908 = g_104919; pb_104909 = b_104920; pstate_104910 = state_104921; goto l104902; l104923: ; double _104932; _104932 = (double)lower_104915; double _104934; _104934 = _104932 / 2.000000e+00; double _104935; _104935 = _104931 + _104934; double _104937; _104937 = _104935 - 1.280000e+02; double px_104938; px_104938 = _104937 / 1.280000e+02; double _104939; _104939 = px_104938 * px_104938; double _104951; _104951 = _104939 + _104950; double _104952; _104952 = 1.000000e+00 + _104951; length_104955 = sqrt(_104952); plength_104955 = length_104955; l104953: ; length_104955 = plength_104955; _104962 = fabs(length_104955); p_104962 = _104962; l104960: ; _104962 = p_104962; bool _104964; _104964 = 1.000000e-17 < _104962; if (_104964) goto l104965; else goto l107563; l107563: ; struct_vec_9645 _107564; _107564.e0 = px_104938; _107564.e1 = py_104949; _107564.e2 = -1.000000e+00; pvnormalize_104968 = _107564; goto l104966; l104965: ; double _107561; _107561 = -1.000000e+00 / length_104955; double _107559; _107559 = px_104938 / length_104955; double _107560; _107560 = py_104949 / length_104955; struct_vec_9645 _107562; _107562.e0 = _107559; _107562.e1 = _107560; _107562.e2 = _107561; pvnormalize_104968 = _107562; goto l104966; l104966: ; vnormalize_104968 = pvnormalize_104968; double _104970; _104970 = vnormalize_104968.e0; double _104978; _104978 = vnormalize_104968.e2; double _104973; _104973 = vnormalize_104968.e1; double _104971; _104971 = 2.000000e+00 * _104970; double _104979; _104979 = 3.500000e+00 * _104978; double _104974; _104974 = 0.000000e+00 * _104973; double _104975; _104975 = _104971 + _104974; double _104980; _104980 = _104975 + _104979; double _104981; _104981 = _104980 * _104980; double D_104983; D_104983 = _104981 - 1.600000e+01; bool _104984; _104984 = 0.000000e+00 < D_104983; if (_104984) goto l104985; else goto l107558; l107558: ; goto l107555; l104985: ; _104988 = sqrt(D_104983); p_104988 = _104988; l104986: ; _104988 = p_104988; double _104989; _104989 = -0.000000e+00 - _104980; double t_104990; t_104990 = _104989 - _104988; bool _104991; _104991 = 0.000000e+00 < t_104990; if (_104991) goto l104992; else goto l107557; l107557: ; goto l107554; l104992: ; bool _104994; _104994 = t_104990 < 1.000000e+17; if (_104994) goto l104995; else goto l107553; l107553: ; goto l107554; l107554: ; goto l107555; l107555: ; struct_Isect_9647 _107049_64; _107049_64.e0 = 1.000000e+17; // bottom: _107049_64.e1 = // bottom: struct_vec_9645 _107047_68;; // bottom: _107049_64.e2 = _107047_68; _107049_64.e3 = 0; pray_sphere_intersect_105025 = _107049_64; goto l105023; l104995: ; double _104996; _104996 = _104970 * t_104990; double _105001; _105001 = _104973 * t_104990; double _105006; _105006 = _104978 * t_104990; double _104997; _104997 = 0.000000e+00 + _104996; double _105002; _105002 = 0.000000e+00 + _105001; double _105007; _105007 = 0.000000e+00 + _105006; double _104999; _104999 = _104997 - -2.000000e+00; double _105003; _105003 = _105002 - 0.000000e+00; double _105009; _105009 = _105007 - -3.500000e+00; double _105000; _105000 = _104999 * _104999; double _105004; _105004 = _105003 * _105003; double _105010; _105010 = _105009 * _105009; double _105005; _105005 = _105000 + _105004; double _105011; _105011 = _105005 + _105010; length_105014 = sqrt(_105011); plength_105014 = length_105014; l105012: ; length_105014 = plength_105014; _105017 = fabs(length_105014); p_105017 = _105017; l105015: ; _105017 = p_105017; bool _105018; _105018 = 1.000000e-17 < _105017; if (_105018) goto l105019; else goto l107551; l107551: ; struct_vec_9645 n_107552; n_107552.e0 = _104999; n_107552.e1 = _105003; n_107552.e2 = _105009; pvnormalize_105022 = n_107552; goto l105020; l105019: ; double _107548; _107548 = _105003 / length_105014; double _107547; _107547 = _104999 / length_105014; double _107549; _107549 = _105009 / length_105014; struct_vec_9645 _107550; _107550.e0 = _107547; _107550.e1 = _107548; _107550.e2 = _107549; pvnormalize_105022 = _107550; goto l105020; l105020: ; vnormalize_105022 = pvnormalize_105022; struct_vec_9645 p_107545; p_107545.e0 = _104997; p_107545.e1 = _105002; p_107545.e2 = _105007; struct_Isect_9647 isect_107546; isect_107546.e0 = t_104990; isect_107546.e1 = p_107545; isect_107546.e2 = vnormalize_105022; isect_107546.e3 = 1; pray_sphere_intersect_105025 = isect_107546; goto l105023; l105023: ; ray_sphere_intersect_105025 = pray_sphere_intersect_105025; double _105030; _105030 = 3.000000e+00 * _104978; double _105027; _105027 = 5.000000e-01 * _104970; double _105028; _105028 = _105027 + _104974; double _105031; _105031 = _105028 + _105030; double _105032; _105032 = _105031 * _105031; double D_105034; D_105034 = _105032 - 9.000000e+00; bool _105035; _105035 = 0.000000e+00 < D_105034; if (_105035) goto l105036; else goto l107544; l107544: ; goto l107541; l105036: ; _105039 = sqrt(D_105034); p_105039 = _105039; l105037: ; _105039 = p_105039; double _105040; _105040 = -0.000000e+00 - _105031; double t_105041; t_105041 = _105040 - _105039; bool _105042; _105042 = 0.000000e+00 < t_105041; if (_105042) goto l105043; else goto l107543; l107543: ; goto l107540; l105043: ; double _105044; _105044 = ray_sphere_intersect_105025.e0; bool _105045; _105045 = t_105041 < _105044; if (_105045) goto l105046; else goto l107539; l107539: ; goto l107540; l107540: ; goto l107541; l107541: ; pray_sphere_intersect_105076 = ray_sphere_intersect_105025; goto l105074; l105046: ; double _105047; _105047 = _104970 * t_105041; double _105052; _105052 = _104973 * t_105041; double _105057; _105057 = _104978 * t_105041; double _105053; _105053 = 0.000000e+00 + _105052; double _105054; _105054 = _105053 - 0.000000e+00; double _105048; _105048 = 0.000000e+00 + _105047; double _105058; _105058 = 0.000000e+00 + _105057; double _105055; _105055 = _105054 * _105054; double _105050; _105050 = _105048 - -5.000000e-01; double _105060; _105060 = _105058 - -3.000000e+00; double _105051; _105051 = _105050 * _105050; double _105061; _105061 = _105060 * _105060; double _105056; _105056 = _105051 + _105055; double _105062; _105062 = _105056 + _105061; length_105065 = sqrt(_105062); plength_105065 = length_105065; l105063: ; length_105065 = plength_105065; _105068 = fabs(length_105065); p_105068 = _105068; l105066: ; _105068 = p_105068; bool _105069; _105069 = 1.000000e-17 < _105068; if (_105069) goto l105070; else goto l107537; l107537: ; struct_vec_9645 n_107538; n_107538.e0 = _105050; n_107538.e1 = _105054; n_107538.e2 = _105060; pvnormalize_105073 = n_107538; goto l105071; l105070: ; double _107533; _107533 = _105050 / length_105065; double _107534; _107534 = _105054 / length_105065; double _107535; _107535 = _105060 / length_105065; struct_vec_9645 _107536; _107536.e0 = _107533; _107536.e1 = _107534; _107536.e2 = _107535; pvnormalize_105073 = _107536; goto l105071; l105071: ; vnormalize_105073 = pvnormalize_105073; struct_vec_9645 p_107531; p_107531.e0 = _105048; p_107531.e1 = _105053; p_107531.e2 = _105058; struct_Isect_9647 isect_107532; isect_107532.e0 = t_105041; isect_107532.e1 = p_107531; isect_107532.e2 = vnormalize_105073; isect_107532.e3 = 1; pray_sphere_intersect_105076 = isect_107532; goto l105074; l105074: ; ray_sphere_intersect_105076 = pray_sphere_intersect_105076; double _105081; _105081 = 2.200000e+00 * _104978; double _105078; _105078 = -1.000000e+00 * _104970; double _105079; _105079 = _105078 + _104974; double _105082; _105082 = _105079 + _105081; double _105083; _105083 = _105082 * _105082; double D_105085; D_105085 = _105083 - 5.590000e+00; bool _105086; _105086 = 0.000000e+00 < D_105085; if (_105086) goto l105087; else goto l107530; l107530: ; goto l107527; l105087: ; _105090 = sqrt(D_105085); p_105090 = _105090; l105088: ; _105090 = p_105090; double _105091; _105091 = -0.000000e+00 - _105082; double t_105092; t_105092 = _105091 - _105090; bool _105093; _105093 = 0.000000e+00 < t_105092; if (_105093) goto l105094; else goto l107529; l107529: ; goto l107526; l105094: ; double _105095; _105095 = ray_sphere_intersect_105076.e0; bool _105096; _105096 = t_105092 < _105095; if (_105096) goto l105097; else goto l107525; l107525: ; goto l107526; l107526: ; goto l107527; l107527: ; pray_sphere_intersect_105126 = ray_sphere_intersect_105076; goto l105124; l105097: ; double _105107; _105107 = _104978 * t_105092; double _105098; _105098 = _104970 * t_105092; double _105108; _105108 = 0.000000e+00 + _105107; double _105102; _105102 = _104973 * t_105092; double _105099; _105099 = 0.000000e+00 + _105098; double _105110; _105110 = _105108 - -2.200000e+00; double _105103; _105103 = 0.000000e+00 + _105102; double _105100; _105100 = _105099 - 1.000000e+00; double _105111; _105111 = _105110 * _105110; double _105104; _105104 = _105103 - 0.000000e+00; double _105101; _105101 = _105100 * _105100; double _105105; _105105 = _105104 * _105104; double _105106; _105106 = _105101 + _105105; double _105112; _105112 = _105106 + _105111; length_105115 = sqrt(_105112); plength_105115 = length_105115; l105113: ; length_105115 = plength_105115; _105118 = fabs(length_105115); p_105118 = _105118; l105116: ; _105118 = p_105118; bool _105119; _105119 = 1.000000e-17 < _105118; if (_105119) goto l105120; else goto l107523; l107523: ; struct_vec_9645 n_107524; n_107524.e0 = _105100; n_107524.e1 = _105104; n_107524.e2 = _105110; pvnormalize_105123 = n_107524; goto l105121; l105120: ; double _107520; _107520 = _105104 / length_105115; double _107521; _107521 = _105110 / length_105115; double _107519; _107519 = _105100 / length_105115; struct_vec_9645 _107522; _107522.e0 = _107519; _107522.e1 = _107520; _107522.e2 = _107521; pvnormalize_105123 = _107522; goto l105121; l105121: ; vnormalize_105123 = pvnormalize_105123; struct_vec_9645 p_107517; p_107517.e0 = _105099; p_107517.e1 = _105103; p_107517.e2 = _105108; struct_Isect_9647 isect_107518; isect_107518.e0 = t_105092; isect_107518.e1 = p_107517; isect_107518.e2 = vnormalize_105123; isect_107518.e3 = 1; pray_sphere_intersect_105126 = isect_107518; goto l105124; l105124: ; ray_sphere_intersect_105126 = pray_sphere_intersect_105126; double _105128; _105128 = 1.000000e+00 * _104973; double _105127; _105127 = 0.000000e+00 * _104970; double _105130; _105130 = 0.000000e+00 * _104978; double _105129; _105129 = _105127 + _105128; double _105131; _105131 = _105129 + _105130; _105134 = fabs(_105131); p_105134 = _105134; l105132: ; _105134 = p_105134; bool _105135; _105135 = 1.000000e-17 <= _105134; if (_105135) goto l105136; else goto l107516; l107516: ; goto l107513; l105136: ; double t_105137; t_105137 = -5.000000e-01 / _105131; bool _105138; _105138 = 0.000000e+00 < t_105137; if (_105138) goto l105139; else goto l107515; l107515: ; goto l107512; l105139: ; double _105140; _105140 = ray_sphere_intersect_105126.e0; bool _105141; _105141 = t_105137 < _105140; if (_105141) goto l105142; else goto l107511; l107511: ; goto l107512; l107512: ; goto l107513; l107513: ; pray_plane_intersect_105145 = ray_sphere_intersect_105126; goto l105143; l105142: ; double _107505; _107505 = _104973 * t_105137; double _107506; _107506 = 0.000000e+00 + _107505; double _107507; _107507 = _104978 * t_105137; double _107503; _107503 = _104970 * t_105137; double _107508; _107508 = 0.000000e+00 + _107507; double _107504; _107504 = 0.000000e+00 + _107503; struct_vec_9645 p_107509; p_107509.e0 = _107504; p_107509.e1 = _107506; p_107509.e2 = _107508; struct_vec_9645 _106999_162; _106999_162.e0 = 0.000000e+00; _106999_162.e1 = 1.000000e+00; _106999_162.e2 = 0.000000e+00; struct_Isect_9647 isect_107510; isect_107510.e0 = t_105137; isect_107510.e1 = p_107509; isect_107510.e2 = _106999_162; isect_107510.e3 = 1; pray_plane_intersect_105145 = isect_107510; goto l105143; l105143: ; ray_plane_intersect_105145 = pray_plane_intersect_105145; int _105147; _105147 = ray_plane_intersect_105145.e3; bool _105149; _105149 = _105147 == 1; if (_105149) goto l105150; else goto l107502; l107502: ; pr_107461 = r_104918; pg_107462 = g_104919; pb_107463 = b_104920; pstate_107464 = state_104921; goto l107459; l105150: ; struct_vec_9645 _105151; _105151 = ray_plane_intersect_105145.e2; double _105152; _105152 = _105151.e0; double _105165; _105165 = _105151.e1; double _105163; _105163 = _105151.e2; bool _105154; _105154 = _105152 < 6.000000e-01; if (_105154) goto l105155; else goto l107501; l107501: ; goto l107486; l105155: ; bool _105157; _105157 = -6.000000e-01 < _105152; if (_105157) goto l105158; else goto l107485; l107485: ; goto l107486; l107486: ; bool _107487; _107487 = _105165 < 6.000000e-01; if (_107487) goto l107488; else goto l107500; l107500: ; goto l107492; l107488: ; bool _107489; _107489 = -6.000000e-01 < _105165; if (_107489) goto l107490; else goto l107491; l107491: ; goto l107492; l107492: ; bool _107493; _107493 = _105163 < 6.000000e-01; if (_107493) goto l107494; else goto l107499; l107499: ; goto l107498; l107494: ; bool _107495; _107495 = -6.000000e-01 < _105163; if (_107495) goto l107496; else goto l107497; l107497: ; goto l107498; l107498: ; p_105160 = 1.000000e+00; p_105161 = 0.000000e+00; p_105162 = 0.000000e+00; goto l105159; l107496: ; p_105160 = 0.000000e+00; p_105161 = 0.000000e+00; p_105162 = 1.000000e+00; goto l105159; l107490: ; p_105160 = 0.000000e+00; p_105161 = 1.000000e+00; p_105162 = 0.000000e+00; goto l105159; l105158: ; p_105160 = 1.000000e+00; p_105161 = 0.000000e+00; p_105162 = 0.000000e+00; goto l105159; l105159: ; _105160 = p_105160; _105161 = p_105161; _105162 = p_105162; double _105169; _105169 = _105162 * _105152; double _105164; _105164 = _105161 * _105163; double _105174; _105174 = _105160 * _105165; double _105170; _105170 = _105160 * _105163; double _105166; _105166 = _105162 * _105165; double _105175; _105175 = _105161 * _105152; double _105171; _105171 = _105169 - _105170; double _105167; _105167 = _105164 - _105166; double _105176; _105176 = _105174 - _105175; double _105172; _105172 = _105171 * _105171; double _105168; _105168 = _105167 * _105167; double _105177; _105177 = _105176 * _105176; double _105173; _105173 = _105168 + _105172; double _105178; _105178 = _105173 + _105177; length_105181 = sqrt(_105178); plength_105181 = length_105181; l105179: ; length_105181 = plength_105181; _105184 = fabs(length_105181); p_105184 = _105184; l105182: ; _105184 = p_105184; bool _105185; _105185 = 1.000000e-17 < _105184; if (_105185) goto l105186; else goto l107483; l107483: ; struct_vec_9645 _107484; _107484.e0 = _105167; _107484.e1 = _105171; _107484.e2 = _105176; pvnormalize_105189 = _107484; goto l105187; l105186: ; double _107481; _107481 = _105176 / length_105181; double _107479; _107479 = _105167 / length_105181; double _107480; _107480 = _105171 / length_105181; struct_vec_9645 _107482; _107482.e0 = _107479; _107482.e1 = _107480; _107482.e2 = _107481; pvnormalize_105189 = _107482; goto l105187; l105187: ; vnormalize_105189 = pvnormalize_105189; double _105190; _105190 = vnormalize_105189.e2; double _105196; _105196 = vnormalize_105189.e0; double _105192; _105192 = vnormalize_105189.e1; double _105191; _105191 = _105165 * _105190; double _105198; _105198 = _105152 * _105190; double _105203; _105203 = _105165 * _105196; double _105197; _105197 = _105163 * _105196; double _105202; _105202 = _105152 * _105192; double _105193; _105193 = _105163 * _105192; double _105194; _105194 = _105191 - _105193; double _105199; _105199 = _105197 - _105198; double _105204; _105204 = _105202 - _105203; double _105195; _105195 = _105194 * _105194; double _105200; _105200 = _105199 * _105199; double _105205; _105205 = _105204 * _105204; double _105201; _105201 = _105195 + _105200; double _105206; _105206 = _105201 + _105205; length_105209 = sqrt(_105206); plength_105209 = length_105209; l105207: ; length_105209 = plength_105209; _105212 = fabs(length_105209); p_105212 = _105212; l105210: ; _105212 = p_105212; bool _105213; _105213 = 1.000000e-17 < _105212; if (_105213) goto l105214; else goto l107477; l107477: ; struct_vec_9645 _107478; _107478.e0 = _105194; _107478.e1 = _105199; _107478.e2 = _105204; pvnormalize_105217 = _107478; goto l105215; l105214: ; double _107475; _107475 = _105204 / length_105209; double _107473; _107473 = _105194 / length_105209; double _107474; _107474 = _105199 / length_105209; struct_vec_9645 _107476; _107476.e0 = _107473; _107476.e1 = _107474; _107476.e2 = _107475; pvnormalize_105217 = _107476; goto l105215; l105215: ; vnormalize_105217 = pvnormalize_105217; double _105299; _105299 = 1.000000e-04 * _105163; struct_vec_9645 _105271; _105271 = ray_plane_intersect_105145.e1; double _105298; _105298 = _105271.e2; double _105274; _105274 = 1.000000e-04 * _105152; double _105300; _105300 = _105298 + _105299; double _105303; _105303 = vnormalize_105217.e2; double _105291; _105291 = vnormalize_105217.e1; double _105272; _105272 = _105271.e0; double _105286; _105286 = _105271.e1; double _105414; _105414 = _105300 - -2.200000e+00; double _105361; _105361 = _105300 - -3.000000e+00; double _105280; _105280 = vnormalize_105217.e0; double _105287; _105287 = 1.000000e-04 * _105165; double _105275; _105275 = _105272 + _105274; double _105477; _105477 = 0.000000e+00 * _105300; double _105301; _105301 = _105300 - -3.500000e+00; double _105288; _105288 = _105286 + _105287; double _105420; _105420 = _105414 * _105414; double _105367; _105367 = _105361 * _105361; double _105358; _105358 = _105275 - -5.000000e-01; double _105276; _105276 = _105275 - -2.000000e+00; double _105474; _105474 = 0.000000e+00 * _105275; double _105411; _105411 = _105275 - 1.000000e+00; double _105314; _105314 = _105301 * _105301; double _105475; _105475 = 1.000000e+00 * _105288; double _105289; _105289 = _105288 - 0.000000e+00; double _105365; _105365 = _105358 * _105358; double _105311; _105311 = _105276 * _105276; double _105476; _105476 = _105474 + _105475; double _105418; _105418 = _105411 * _105411; double _105312; _105312 = _105289 * _105289; double _105366; _105366 = _105365 + _105312; double _105313; _105313 = _105311 + _105312; double _105478; _105478 = _105476 + _105477; double _105419; _105419 = _105418 + _105312; double _105368; _105368 = _105366 + _105367; double _105315; _105315 = _105313 + _105314; double _105479; _105479 = 5.000000e-01 + _105478; double _105421; _105421 = _105419 + _105420; double C_105369; C_105369 = _105368 - 2.500000e-01; double C_105317; C_105317 = _105315 - 2.500000e-01; double _105480; _105480 = -0.000000e+00 - _105479; double C_105422; C_105422 = _105421 - 2.500000e-01; plower_105220 = 0; pupper_105221 = 8; pstep_105222 = 1; pocclusion_105223 = 0.000000e+00; pstate_105224 = state_104921; goto l105218; l105218: ; lower_105220 = plower_105220; upper_105221 = pupper_105221; step_105222 = pstep_105222; occlusion_105223 = pocclusion_105223; state_105224 = pstate_105224; bool _105225; _105225 = lower_105220 < upper_105221; if (_105225) goto l105226; else goto l107458; l107458: ; double _107467; _107467 = 6.400000e+01 - occlusion_105223; double _107468; _107468 = _107467 / 6.400000e+01; double _107469; _107469 = r_104918 + _107468; double _107471; _107471 = b_104920 + _107468; double _107470; _107470 = g_104919 + _107468; pr_107461 = _107469; pg_107462 = _107470; pb_107463 = _107471; pstate_107464 = state_105224; goto l107459; l107459: ; r_107461 = pr_107461; g_107462 = pg_107462; b_107463 = pb_107463; state_107464 = pstate_107464; int _107465; _107465 = lower_104915 + step_104917; plower_104915 = _107465; pupper_104916 = upper_104916; pstep_104917 = step_104917; pr_104918 = r_107461; pg_104919 = g_107462; pb_104920 = b_107463; pstate_104921 = state_107464; goto l104913; l105226: ; unsigned long hi_105232; hi_105232 = state_105224 >> 32; unsigned long lo_105229; lo_105229 = 4294967295 & state_105224; unsigned int _105230; _105230 = (unsigned int)lo_105229; unsigned int _105233; _105233 = (unsigned int)hi_105232; unsigned int _105234; _105234 = _105230 ^ _105233; double _105235; _105235 = (double)_105234; double _105236; _105236 = 2.328306e-10 * _105235; theta_105239 = sqrt(_105236); ptheta_105239 = theta_105239; l105237: ; theta_105239 = ptheta_105239; unsigned long _105246; _105246 = 4294883355 * lo_105229; unsigned long _105247; _105247 = _105246 + hi_105232; unsigned long lo_105248; lo_105248 = 4294967295 & _105247; unsigned long hi_105250; hi_105250 = _105247 >> 32; unsigned int _105249; _105249 = (unsigned int)lo_105248; unsigned int _105251; _105251 = (unsigned int)hi_105250; unsigned int _105252; _105252 = _105249 ^ _105251; double _105253; _105253 = (double)_105252; double _105254; _105254 = 2.328306e-10 * _105253; double phi_105255; phi_105255 = 6.283185e+00 * _105254; _105258 = cos(phi_105255); p_105258 = _105258; l105256: ; _105258 = p_105258; _105265 = sin(phi_105255); p_105265 = _105265; l105263: ; _105265 = p_105265; double _105266; _105266 = theta_105239 * theta_105239; double _105267; _105267 = 1.000000e+00 - _105266; z_105270 = sqrt(_105267); pz_105270 = z_105270; l105268: ; z_105270 = pz_105270; double _105294; _105294 = z_105270 * _105165; double _105283; _105283 = z_105270 * _105152; double y_105279; y_105279 = _105265 * theta_105239; double _105292; _105292 = y_105279 * _105291; double _105281; _105281 = y_105279 * _105280; double x_105277; x_105277 = _105258 * theta_105239; double _105306; _105306 = z_105270 * _105163; double _105304; _105304 = y_105279 * _105303; double _105278; _105278 = x_105277 * _105196; double _105290; _105290 = x_105277 * _105192; double _105293; _105293 = _105290 + _105292; double _105282; _105282 = _105278 + _105281; double _105302; _105302 = x_105277 * _105190; double _105305; _105305 = _105302 + _105304; double ry_105295; ry_105295 = _105293 + _105294; double rx_105284; rx_105284 = _105282 + _105283; double rz_105307; rz_105307 = _105305 + _105306; double _105296; _105296 = _105289 * ry_105295; double _105285; _105285 = _105276 * rx_105284; double _105308; _105308 = _105301 * rz_105307; double _105297; _105297 = _105285 + _105296; double _105309; _105309 = _105297 + _105308; double _105310; _105310 = _105309 * _105309; double D_105318; D_105318 = _105310 - C_105317; bool _105319; _105319 = 0.000000e+00 < D_105318; if (_105319) goto l105320; else goto l107457; l107457: ; goto l107454; l105320: ; _105323 = sqrt(D_105318); p_105323 = _105323; l105321: ; _105323 = p_105323; double _105324; _105324 = -0.000000e+00 - _105309; double t_105325; t_105325 = _105324 - _105323; bool _105326; _105326 = 0.000000e+00 < t_105325; if (_105326) goto l105327; else goto l107456; l107456: ; goto l107453; l105327: ; bool _105328; _105328 = t_105325 < 1.000000e+17; if (_105328) goto l105329; else goto l107452; l107452: ; goto l107453; l107453: ; goto l107454; l107454: ; struct_Isect_9647 _107049_259; _107049_259.e0 = 1.000000e+17; // bottom: _107049_259.e1 = // bottom: struct_vec_9645 _107047_263;; // bottom: _107049_259.e2 = _107047_263; _107049_259.e3 = 0; pray_sphere_intersect_105357 = _107049_259; goto l105355; l105329: ; double _105334; _105334 = ry_105295 * t_105325; double _105339; _105339 = rz_105307 * t_105325; double _105330; _105330 = rx_105284 * t_105325; double _105335; _105335 = _105288 + _105334; double _105340; _105340 = _105300 + _105339; double _105331; _105331 = _105275 + _105330; double _105336; _105336 = _105335 - 0.000000e+00; double _105341; _105341 = _105340 - -3.500000e+00; double _105332; _105332 = _105331 - -2.000000e+00; double _105337; _105337 = _105336 * _105336; double _105342; _105342 = _105341 * _105341; double _105333; _105333 = _105332 * _105332; double _105338; _105338 = _105333 + _105337; double _105343; _105343 = _105338 + _105342; length_105346 = sqrt(_105343); plength_105346 = length_105346; l105344: ; length_105346 = plength_105346; _105349 = fabs(length_105346); p_105349 = _105349; l105347: ; _105349 = p_105349; bool _105350; _105350 = 1.000000e-17 < _105349; if (_105350) goto l105351; else goto l107450; l107450: ; struct_vec_9645 n_107451; n_107451.e0 = _105332; n_107451.e1 = _105336; n_107451.e2 = _105341; pvnormalize_105354 = n_107451; goto l105352; l105351: ; double _107448; _107448 = _105341 / length_105346; double _107447; _107447 = _105336 / length_105346; double _107446; _107446 = _105332 / length_105346; struct_vec_9645 _107449; _107449.e0 = _107446; _107449.e1 = _107447; _107449.e2 = _107448; pvnormalize_105354 = _107449; goto l105352; l105352: ; vnormalize_105354 = pvnormalize_105354; struct_vec_9645 p_107444; p_107444.e0 = _105331; p_107444.e1 = _105335; p_107444.e2 = _105340; struct_Isect_9647 isect_107445; isect_107445.e0 = t_105325; isect_107445.e1 = p_107444; isect_107445.e2 = vnormalize_105354; isect_107445.e3 = 1; pray_sphere_intersect_105357 = isect_107445; goto l105355; l105355: ; ray_sphere_intersect_105357 = pray_sphere_intersect_105357; double _105359; _105359 = _105358 * rx_105284; double _105360; _105360 = _105359 + _105296; double _105362; _105362 = _105361 * rz_105307; double _105363; _105363 = _105360 + _105362; double _105364; _105364 = _105363 * _105363; double D_105370; D_105370 = _105364 - C_105369; bool _105371; _105371 = 0.000000e+00 < D_105370; if (_105371) goto l105372; else goto l107443; l107443: ; goto l107440; l105372: ; _105375 = sqrt(D_105370); p_105375 = _105375; l105373: ; _105375 = p_105375; double _105376; _105376 = -0.000000e+00 - _105363; double t_105377; t_105377 = _105376 - _105375; bool _105378; _105378 = 0.000000e+00 < t_105377; if (_105378) goto l105379; else goto l107442; l107442: ; goto l107439; l105379: ; double _105380; _105380 = ray_sphere_intersect_105357.e0; bool _105381; _105381 = t_105377 < _105380; if (_105381) goto l105382; else goto l107438; l107438: ; goto l107439; l107439: ; goto l107440; l107440: ; pray_sphere_intersect_105410 = ray_sphere_intersect_105357; goto l105408; l105382: ; double _105383; _105383 = rx_105284 * t_105377; double _105387; _105387 = ry_105295 * t_105377; double _105384; _105384 = _105275 + _105383; double _105392; _105392 = rz_105307 * t_105377; double _105388; _105388 = _105288 + _105387; double _105385; _105385 = _105384 - -5.000000e-01; double _105393; _105393 = _105300 + _105392; double _105389; _105389 = _105388 - 0.000000e+00; double _105386; _105386 = _105385 * _105385; double _105394; _105394 = _105393 - -3.000000e+00; double _105390; _105390 = _105389 * _105389; double _105391; _105391 = _105386 + _105390; double _105395; _105395 = _105394 * _105394; double _105396; _105396 = _105391 + _105395; length_105399 = sqrt(_105396); plength_105399 = length_105399; l105397: ; length_105399 = plength_105399; _105402 = fabs(length_105399); p_105402 = _105402; l105400: ; _105402 = p_105402; bool _105403; _105403 = 1.000000e-17 < _105402; if (_105403) goto l105404; else goto l107436; l107436: ; struct_vec_9645 n_107437; n_107437.e0 = _105385; n_107437.e1 = _105389; n_107437.e2 = _105394; pvnormalize_105407 = n_107437; goto l105405; l105404: ; double _107434; _107434 = _105394 / length_105399; double _107433; _107433 = _105389 / length_105399; double _107432; _107432 = _105385 / length_105399; struct_vec_9645 _107435; _107435.e0 = _107432; _107435.e1 = _107433; _107435.e2 = _107434; pvnormalize_105407 = _107435; goto l105405; l105405: ; vnormalize_105407 = pvnormalize_105407; struct_vec_9645 p_107430; p_107430.e0 = _105384; p_107430.e1 = _105388; p_107430.e2 = _105393; struct_Isect_9647 isect_107431; isect_107431.e0 = t_105377; isect_107431.e1 = p_107430; isect_107431.e2 = vnormalize_105407; isect_107431.e3 = 1; pray_sphere_intersect_105410 = isect_107431; goto l105408; l105408: ; ray_sphere_intersect_105410 = pray_sphere_intersect_105410; double _105412; _105412 = _105411 * rx_105284; double _105415; _105415 = _105414 * rz_105307; double _105413; _105413 = _105412 + _105296; double _105416; _105416 = _105413 + _105415; double _105417; _105417 = _105416 * _105416; double D_105423; D_105423 = _105417 - C_105422; bool _105424; _105424 = 0.000000e+00 < D_105423; if (_105424) goto l105425; else goto l107429; l107429: ; goto l107426; l105425: ; _105428 = sqrt(D_105423); p_105428 = _105428; l105426: ; _105428 = p_105428; double _105429; _105429 = -0.000000e+00 - _105416; double t_105430; t_105430 = _105429 - _105428; bool _105431; _105431 = 0.000000e+00 < t_105430; if (_105431) goto l105432; else goto l107428; l107428: ; goto l107425; l105432: ; double _105433; _105433 = ray_sphere_intersect_105410.e0; bool _105434; _105434 = t_105430 < _105433; if (_105434) goto l105435; else goto l107424; l107424: ; goto l107425; l107425: ; goto l107426; l107426: ; pray_sphere_intersect_105463 = ray_sphere_intersect_105410; goto l105461; l105435: ; double _105436; _105436 = rx_105284 * t_105430; double _105445; _105445 = rz_105307 * t_105430; double _105440; _105440 = ry_105295 * t_105430; double _105437; _105437 = _105275 + _105436; double _105438; _105438 = _105437 - 1.000000e+00; double _105446; _105446 = _105300 + _105445; double _105441; _105441 = _105288 + _105440; double _105439; _105439 = _105438 * _105438; double _105447; _105447 = _105446 - -2.200000e+00; double _105442; _105442 = _105441 - 0.000000e+00; double _105448; _105448 = _105447 * _105447; double _105443; _105443 = _105442 * _105442; double _105444; _105444 = _105439 + _105443; double _105449; _105449 = _105444 + _105448; length_105452 = sqrt(_105449); plength_105452 = length_105452; l105450: ; length_105452 = plength_105452; _105455 = fabs(length_105452); p_105455 = _105455; l105453: ; _105455 = p_105455; bool _105456; _105456 = 1.000000e-17 < _105455; if (_105456) goto l105457; else goto l107422; l107422: ; struct_vec_9645 n_107423; n_107423.e0 = _105438; n_107423.e1 = _105442; n_107423.e2 = _105447; pvnormalize_105460 = n_107423; goto l105458; l105457: ; double _107418; _107418 = _105438 / length_105452; double _107419; _107419 = _105442 / length_105452; double _107420; _107420 = _105447 / length_105452; struct_vec_9645 _107421; _107421.e0 = _107418; _107421.e1 = _107419; _107421.e2 = _107420; pvnormalize_105460 = _107421; goto l105458; l105458: ; vnormalize_105460 = pvnormalize_105460; struct_vec_9645 p_107416; p_107416.e0 = _105437; p_107416.e1 = _105441; p_107416.e2 = _105446; struct_Isect_9647 isect_107417; isect_107417.e0 = t_105430; isect_107417.e1 = p_107416; isect_107417.e2 = vnormalize_105460; isect_107417.e3 = 1; pray_sphere_intersect_105463 = isect_107417; goto l105461; l105461: ; ray_sphere_intersect_105463 = pray_sphere_intersect_105463; double _105464; _105464 = 0.000000e+00 * rx_105284; double _105465; _105465 = 1.000000e+00 * ry_105295; double _105467; _105467 = 0.000000e+00 * rz_105307; double _105466; _105466 = _105464 + _105465; double _105468; _105468 = _105466 + _105467; _105471 = fabs(_105468); p_105471 = _105471; l105469: ; _105471 = p_105471; bool _105472; _105472 = 1.000000e-17 <= _105471; if (_105472) goto l105473; else goto l107415; l107415: ; goto l107412; l105473: ; double t_105481; t_105481 = _105480 / _105468; bool _105482; _105482 = 0.000000e+00 < t_105481; if (_105482) goto l105483; else goto l107414; l107414: ; goto l107411; l105483: ; double _105484; _105484 = ray_sphere_intersect_105463.e0; bool _105485; _105485 = t_105481 < _105484; if (_105485) goto l105486; else goto l107410; l107410: ; goto l107411; l107411: ; goto l107412; l107412: ; pray_plane_intersect_105489 = ray_sphere_intersect_105463; goto l105487; l105486: ; double _107406; _107406 = rz_105307 * t_105481; double _107407; _107407 = _105300 + _107406; double _107402; _107402 = rx_105284 * t_105481; double _107403; _107403 = _105275 + _107402; double _107404; _107404 = ry_105295 * t_105481; double _107405; _107405 = _105288 + _107404; struct_vec_9645 p_107408; p_107408.e0 = _107403; p_107408.e1 = _107405; p_107408.e2 = _107407; struct_vec_9645 _106999_338; _106999_338.e0 = 0.000000e+00; _106999_338.e1 = 1.000000e+00; _106999_338.e2 = 0.000000e+00; struct_Isect_9647 isect_107409; isect_107409.e0 = t_105481; isect_107409.e1 = p_107408; isect_107409.e2 = _106999_338; isect_107409.e3 = 1; pray_plane_intersect_105489 = isect_107409; goto l105487; l105487: ; ray_plane_intersect_105489 = pray_plane_intersect_105489; int _105490; _105490 = ray_plane_intersect_105489.e3; bool _105491; _105491 = _105490 == 1; if (_105491) goto l105492; else goto l107401; l107401: ; pocclusion_105495 = occlusion_105223; goto l105493; l105492: ; double _107400; _107400 = 1.000000e+00 + occlusion_105223; pocclusion_105495 = _107400; goto l105493; l105493: ; occlusion_105495 = pocclusion_105495; unsigned long _105496; _105496 = 4294883355 * lo_105248; unsigned long _105497; _105497 = _105496 + hi_105250; unsigned long lo_105498; lo_105498 = 4294967295 & _105497; unsigned long hi_105500; hi_105500 = _105497 >> 32; unsigned int _105499; _105499 = (unsigned int)lo_105498; unsigned int _105501; _105501 = (unsigned int)hi_105500; unsigned int _105502; _105502 = _105499 ^ _105501; double _105503; _105503 = (double)_105502; double _105504; _105504 = 2.328306e-10 * _105503; theta_105507 = sqrt(_105504); ptheta_105507 = theta_105507; l105505: ; theta_105507 = ptheta_105507; unsigned long _105508; _105508 = 4294883355 * lo_105498; unsigned long _105509; _105509 = _105508 + hi_105500; unsigned long lo_105510; lo_105510 = 4294967295 & _105509; unsigned long hi_105512; hi_105512 = _105509 >> 32; unsigned int _105511; _105511 = (unsigned int)lo_105510; unsigned int _105513; _105513 = (unsigned int)hi_105512; unsigned int _105514; _105514 = _105511 ^ _105513; double _105515; _105515 = (double)_105514; double _105516; _105516 = 2.328306e-10 * _105515; double phi_105517; phi_105517 = 6.283185e+00 * _105516; _105520 = cos(phi_105517); p_105520 = _105520; l105518: ; _105520 = p_105520; _105523 = sin(phi_105517); p_105523 = _105523; l105521: ; _105523 = p_105523; double _105524; _105524 = theta_105507 * theta_105507; double _105525; _105525 = 1.000000e+00 - _105524; z_105528 = sqrt(_105525); pz_105528 = z_105528; l105526: ; z_105528 = pz_105528; double _105540; _105540 = z_105528 * _105165; double _105547; _105547 = z_105528 * _105163; double x_105529; x_105529 = _105520 * theta_105507; double y_105531; y_105531 = _105523 * theta_105507; double _105530; _105530 = x_105529 * _105196; double _105537; _105537 = x_105529 * _105192; double _105538; _105538 = y_105531 * _105291; double _105534; _105534 = z_105528 * _105152; double _105532; _105532 = y_105531 * _105280; double _105544; _105544 = x_105529 * _105190; double _105545; _105545 = y_105531 * _105303; double _105533; _105533 = _105530 + _105532; double _105539; _105539 = _105537 + _105538; double rx_105535; rx_105535 = _105533 + _105534; double _105546; _105546 = _105544 + _105545; double ry_105541; ry_105541 = _105539 + _105540; double _105536; _105536 = _105276 * rx_105535; double rz_105548; rz_105548 = _105546 + _105547; double _105542; _105542 = _105289 * ry_105541; double _105543; _105543 = _105536 + _105542; double _105549; _105549 = _105301 * rz_105548; double _105550; _105550 = _105543 + _105549; double _105551; _105551 = _105550 * _105550; double D_105552; D_105552 = _105551 - C_105317; bool _105553; _105553 = 0.000000e+00 < D_105552; if (_105553) goto l105554; else goto l107399; l107399: ; goto l107396; l105554: ; _105557 = sqrt(D_105552); p_105557 = _105557; l105555: ; _105557 = p_105557; double _105558; _105558 = -0.000000e+00 - _105550; double t_105559; t_105559 = _105558 - _105557; bool _105560; _105560 = 0.000000e+00 < t_105559; if (_105560) goto l105561; else goto l107398; l107398: ; goto l107395; l105561: ; bool _105562; _105562 = t_105559 < 1.000000e+17; if (_105562) goto l105563; else goto l107394; l107394: ; goto l107395; l107395: ; goto l107396; l107396: ; struct_Isect_9647 _107049_367; _107049_367.e0 = 1.000000e+17; // bottom: _107049_367.e1 = // bottom: struct_vec_9645 _107047_371;; // bottom: _107049_367.e2 = _107047_371; _107049_367.e3 = 0; pray_sphere_intersect_105591 = _107049_367; goto l105589; l105563: ; double _105573; _105573 = rz_105548 * t_105559; double _105564; _105564 = rx_105535 * t_105559; double _105568; _105568 = ry_105541 * t_105559; double _105569; _105569 = _105288 + _105568; double _105574; _105574 = _105300 + _105573; double _105565; _105565 = _105275 + _105564; double _105570; _105570 = _105569 - 0.000000e+00; double _105575; _105575 = _105574 - -3.500000e+00; double _105566; _105566 = _105565 - -2.000000e+00; double _105571; _105571 = _105570 * _105570; double _105576; _105576 = _105575 * _105575; double _105567; _105567 = _105566 * _105566; double _105572; _105572 = _105567 + _105571; double _105577; _105577 = _105572 + _105576; length_105580 = sqrt(_105577); plength_105580 = length_105580; l105578: ; length_105580 = plength_105580; _105583 = fabs(length_105580); p_105583 = _105583; l105581: ; _105583 = p_105583; bool _105584; _105584 = 1.000000e-17 < _105583; if (_105584) goto l105585; else goto l107392; l107392: ; struct_vec_9645 n_107393; n_107393.e0 = _105566; n_107393.e1 = _105570; n_107393.e2 = _105575; pvnormalize_105588 = n_107393; goto l105586; l105585: ; double _107389; _107389 = _105570 / length_105580; double _107388; _107388 = _105566 / length_105580; double _107390; _107390 = _105575 / length_105580; struct_vec_9645 _107391; _107391.e0 = _107388; _107391.e1 = _107389; _107391.e2 = _107390; pvnormalize_105588 = _107391; goto l105586; l105586: ; vnormalize_105588 = pvnormalize_105588; struct_vec_9645 p_107386; p_107386.e0 = _105565; p_107386.e1 = _105569; p_107386.e2 = _105574; struct_Isect_9647 isect_107387; isect_107387.e0 = t_105559; isect_107387.e1 = p_107386; isect_107387.e2 = vnormalize_105588; isect_107387.e3 = 1; pray_sphere_intersect_105591 = isect_107387; goto l105589; l105589: ; ray_sphere_intersect_105591 = pray_sphere_intersect_105591; double _105592; _105592 = _105358 * rx_105535; double _105594; _105594 = _105361 * rz_105548; double _105593; _105593 = _105592 + _105542; double _105595; _105595 = _105593 + _105594; double _105596; _105596 = _105595 * _105595; double D_105597; D_105597 = _105596 - C_105369; bool _105598; _105598 = 0.000000e+00 < D_105597; if (_105598) goto l105599; else goto l107385; l107385: ; goto l107382; l105599: ; _105602 = sqrt(D_105597); p_105602 = _105602; l105600: ; _105602 = p_105602; double _105603; _105603 = -0.000000e+00 - _105595; double t_105604; t_105604 = _105603 - _105602; bool _105605; _105605 = 0.000000e+00 < t_105604; if (_105605) goto l105606; else goto l107384; l107384: ; goto l107381; l105606: ; double _105607; _105607 = ray_sphere_intersect_105591.e0; bool _105608; _105608 = t_105604 < _105607; if (_105608) goto l105609; else goto l107380; l107380: ; goto l107381; l107381: ; goto l107382; l107382: ; pray_sphere_intersect_105637 = ray_sphere_intersect_105591; goto l105635; l105609: ; double _105614; _105614 = ry_105541 * t_105604; double _105619; _105619 = rz_105548 * t_105604; double _105615; _105615 = _105288 + _105614; double _105610; _105610 = rx_105535 * t_105604; double _105611; _105611 = _105275 + _105610; double _105620; _105620 = _105300 + _105619; double _105616; _105616 = _105615 - 0.000000e+00; double _105612; _105612 = _105611 - -5.000000e-01; double _105621; _105621 = _105620 - -3.000000e+00; double _105617; _105617 = _105616 * _105616; double _105613; _105613 = _105612 * _105612; double _105622; _105622 = _105621 * _105621; double _105618; _105618 = _105613 + _105617; double _105623; _105623 = _105618 + _105622; length_105626 = sqrt(_105623); plength_105626 = length_105626; l105624: ; length_105626 = plength_105626; _105629 = fabs(length_105626); p_105629 = _105629; l105627: ; _105629 = p_105629; bool _105630; _105630 = 1.000000e-17 < _105629; if (_105630) goto l105631; else goto l107378; l107378: ; struct_vec_9645 n_107379; n_107379.e0 = _105612; n_107379.e1 = _105616; n_107379.e2 = _105621; pvnormalize_105634 = n_107379; goto l105632; l105631: ; double _107375; _107375 = _105616 / length_105626; double _107374; _107374 = _105612 / length_105626; double _107376; _107376 = _105621 / length_105626; struct_vec_9645 _107377; _107377.e0 = _107374; _107377.e1 = _107375; _107377.e2 = _107376; pvnormalize_105634 = _107377; goto l105632; l105632: ; vnormalize_105634 = pvnormalize_105634; struct_vec_9645 p_107372; p_107372.e0 = _105611; p_107372.e1 = _105615; p_107372.e2 = _105620; struct_Isect_9647 isect_107373; isect_107373.e0 = t_105604; isect_107373.e1 = p_107372; isect_107373.e2 = vnormalize_105634; isect_107373.e3 = 1; pray_sphere_intersect_105637 = isect_107373; goto l105635; l105635: ; ray_sphere_intersect_105637 = pray_sphere_intersect_105637; double _105638; _105638 = _105411 * rx_105535; double _105640; _105640 = _105414 * rz_105548; double _105639; _105639 = _105638 + _105542; double _105641; _105641 = _105639 + _105640; double _105642; _105642 = _105641 * _105641; double D_105643; D_105643 = _105642 - C_105422; bool _105644; _105644 = 0.000000e+00 < D_105643; if (_105644) goto l105645; else goto l107371; l107371: ; goto l107368; l105645: ; _105648 = sqrt(D_105643); p_105648 = _105648; l105646: ; _105648 = p_105648; double _105649; _105649 = -0.000000e+00 - _105641; double t_105650; t_105650 = _105649 - _105648; bool _105651; _105651 = 0.000000e+00 < t_105650; if (_105651) goto l105652; else goto l107370; l107370: ; goto l107367; l105652: ; double _105653; _105653 = ray_sphere_intersect_105637.e0; bool _105654; _105654 = t_105650 < _105653; if (_105654) goto l105655; else goto l107366; l107366: ; goto l107367; l107367: ; goto l107368; l107368: ; pray_sphere_intersect_105683 = ray_sphere_intersect_105637; goto l105681; l105655: ; double _105660; _105660 = ry_105541 * t_105650; double _105661; _105661 = _105288 + _105660; double _105665; _105665 = rz_105548 * t_105650; double _105656; _105656 = rx_105535 * t_105650; double _105657; _105657 = _105275 + _105656; double _105662; _105662 = _105661 - 0.000000e+00; double _105666; _105666 = _105300 + _105665; double _105658; _105658 = _105657 - 1.000000e+00; double _105663; _105663 = _105662 * _105662; double _105667; _105667 = _105666 - -2.200000e+00; double _105659; _105659 = _105658 * _105658; double _105664; _105664 = _105659 + _105663; double _105668; _105668 = _105667 * _105667; double _105669; _105669 = _105664 + _105668; length_105672 = sqrt(_105669); plength_105672 = length_105672; l105670: ; length_105672 = plength_105672; _105675 = fabs(length_105672); p_105675 = _105675; l105673: ; _105675 = p_105675; bool _105676; _105676 = 1.000000e-17 < _105675; if (_105676) goto l105677; else goto l107364; l107364: ; struct_vec_9645 n_107365; n_107365.e0 = _105658; n_107365.e1 = _105662; n_107365.e2 = _105667; pvnormalize_105680 = n_107365; goto l105678; l105677: ; double _107360; _107360 = _105658 / length_105672; double _107362; _107362 = _105667 / length_105672; double _107361; _107361 = _105662 / length_105672; struct_vec_9645 _107363; _107363.e0 = _107360; _107363.e1 = _107361; _107363.e2 = _107362; pvnormalize_105680 = _107363; goto l105678; l105678: ; vnormalize_105680 = pvnormalize_105680; struct_vec_9645 p_107358; p_107358.e0 = _105657; p_107358.e1 = _105661; p_107358.e2 = _105666; struct_Isect_9647 isect_107359; isect_107359.e0 = t_105650; isect_107359.e1 = p_107358; isect_107359.e2 = vnormalize_105680; isect_107359.e3 = 1; pray_sphere_intersect_105683 = isect_107359; goto l105681; l105681: ; ray_sphere_intersect_105683 = pray_sphere_intersect_105683; double _105687; _105687 = 0.000000e+00 * rz_105548; double _105684; _105684 = 0.000000e+00 * rx_105535; double _105685; _105685 = 1.000000e+00 * ry_105541; double _105686; _105686 = _105684 + _105685; double _105688; _105688 = _105686 + _105687; _105691 = fabs(_105688); p_105691 = _105691; l105689: ; _105691 = p_105691; bool _105692; _105692 = 1.000000e-17 <= _105691; if (_105692) goto l105693; else goto l107357; l107357: ; goto l107354; l105693: ; double t_105694; t_105694 = _105480 / _105688; bool _105695; _105695 = 0.000000e+00 < t_105694; if (_105695) goto l105696; else goto l107356; l107356: ; goto l107353; l105696: ; double _105697; _105697 = ray_sphere_intersect_105683.e0; bool _105698; _105698 = t_105694 < _105697; if (_105698) goto l105699; else goto l107352; l107352: ; goto l107353; l107353: ; goto l107354; l107354: ; pray_plane_intersect_105702 = ray_sphere_intersect_105683; goto l105700; l105699: ; double _107348; _107348 = rz_105548 * t_105694; double _107349; _107349 = _105300 + _107348; double _107346; _107346 = ry_105541 * t_105694; double _107344; _107344 = rx_105535 * t_105694; double _107345; _107345 = _105275 + _107344; double _107347; _107347 = _105288 + _107346; struct_vec_9645 p_107350; p_107350.e0 = _107345; p_107350.e1 = _107347; p_107350.e2 = _107349; struct_vec_9645 _106999_446; _106999_446.e0 = 0.000000e+00; _106999_446.e1 = 1.000000e+00; _106999_446.e2 = 0.000000e+00; struct_Isect_9647 isect_107351; isect_107351.e0 = t_105694; isect_107351.e1 = p_107350; isect_107351.e2 = _106999_446; isect_107351.e3 = 1; pray_plane_intersect_105702 = isect_107351; goto l105700; l105700: ; ray_plane_intersect_105702 = pray_plane_intersect_105702; int _105703; _105703 = ray_plane_intersect_105702.e3; bool _105704; _105704 = _105703 == 1; if (_105704) goto l105705; else goto l107343; l107343: ; pocclusion_105708 = occlusion_105495; goto l105706; l105705: ; double _107342; _107342 = 1.000000e+00 + occlusion_105495; pocclusion_105708 = _107342; goto l105706; l105706: ; occlusion_105708 = pocclusion_105708; unsigned long _105709; _105709 = 4294883355 * lo_105510; unsigned long _105710; _105710 = _105709 + hi_105512; unsigned long lo_105711; lo_105711 = 4294967295 & _105710; unsigned long hi_105713; hi_105713 = _105710 >> 32; unsigned int _105712; _105712 = (unsigned int)lo_105711; unsigned int _105714; _105714 = (unsigned int)hi_105713; unsigned int _105715; _105715 = _105712 ^ _105714; double _105716; _105716 = (double)_105715; double _105717; _105717 = 2.328306e-10 * _105716; theta_105720 = sqrt(_105717); ptheta_105720 = theta_105720; l105718: ; theta_105720 = ptheta_105720; unsigned long _105721; _105721 = 4294883355 * lo_105711; unsigned long _105722; _105722 = _105721 + hi_105713; unsigned long lo_105723; lo_105723 = 4294967295 & _105722; unsigned long hi_105725; hi_105725 = _105722 >> 32; unsigned int _105724; _105724 = (unsigned int)lo_105723; unsigned int _105726; _105726 = (unsigned int)hi_105725; unsigned int _105727; _105727 = _105724 ^ _105726; double _105728; _105728 = (double)_105727; double _105729; _105729 = 2.328306e-10 * _105728; double phi_105730; phi_105730 = 6.283185e+00 * _105729; _105733 = cos(phi_105730); p_105733 = _105733; l105731: ; _105733 = p_105733; _105736 = sin(phi_105730); p_105736 = _105736; l105734: ; _105736 = p_105736; double _105737; _105737 = theta_105720 * theta_105720; double _105738; _105738 = 1.000000e+00 - _105737; z_105741 = sqrt(_105738); pz_105741 = z_105741; l105739: ; z_105741 = pz_105741; double _105760; _105760 = z_105741 * _105163; double _105747; _105747 = z_105741 * _105152; double _105753; _105753 = z_105741 * _105165; double x_105742; x_105742 = _105733 * theta_105720; double y_105744; y_105744 = _105736 * theta_105720; double _105757; _105757 = x_105742 * _105190; double _105743; _105743 = x_105742 * _105196; double _105750; _105750 = x_105742 * _105192; double _105758; _105758 = y_105744 * _105303; double _105745; _105745 = y_105744 * _105280; double _105751; _105751 = y_105744 * _105291; double _105759; _105759 = _105757 + _105758; double _105746; _105746 = _105743 + _105745; double _105752; _105752 = _105750 + _105751; double rz_105761; rz_105761 = _105759 + _105760; double rx_105748; rx_105748 = _105746 + _105747; double ry_105754; ry_105754 = _105752 + _105753; double _105762; _105762 = _105301 * rz_105761; double _105749; _105749 = _105276 * rx_105748; double _105755; _105755 = _105289 * ry_105754; double _105756; _105756 = _105749 + _105755; double _105763; _105763 = _105756 + _105762; double _105764; _105764 = _105763 * _105763; double D_105765; D_105765 = _105764 - C_105317; bool _105766; _105766 = 0.000000e+00 < D_105765; if (_105766) goto l105767; else goto l107341; l107341: ; goto l107338; l105767: ; _105770 = sqrt(D_105765); p_105770 = _105770; l105768: ; _105770 = p_105770; double _105771; _105771 = -0.000000e+00 - _105763; double t_105772; t_105772 = _105771 - _105770; bool _105773; _105773 = 0.000000e+00 < t_105772; if (_105773) goto l105774; else goto l107340; l107340: ; goto l107337; l105774: ; bool _105775; _105775 = t_105772 < 1.000000e+17; if (_105775) goto l105776; else goto l107336; l107336: ; goto l107337; l107337: ; goto l107338; l107338: ; struct_Isect_9647 _107049_475; _107049_475.e0 = 1.000000e+17; // bottom: _107049_475.e1 = // bottom: struct_vec_9645 _107047_479;; // bottom: _107049_475.e2 = _107047_479; _107049_475.e3 = 0; pray_sphere_intersect_105804 = _107049_475; goto l105802; l105776: ; double _105781; _105781 = ry_105754 * t_105772; double _105786; _105786 = rz_105761 * t_105772; double _105777; _105777 = rx_105748 * t_105772; double _105782; _105782 = _105288 + _105781; double _105787; _105787 = _105300 + _105786; double _105788; _105788 = _105787 - -3.500000e+00; double _105778; _105778 = _105275 + _105777; double _105783; _105783 = _105782 - 0.000000e+00; double _105789; _105789 = _105788 * _105788; double _105779; _105779 = _105778 - -2.000000e+00; double _105784; _105784 = _105783 * _105783; double _105780; _105780 = _105779 * _105779; double _105785; _105785 = _105780 + _105784; double _105790; _105790 = _105785 + _105789; length_105793 = sqrt(_105790); plength_105793 = length_105793; l105791: ; length_105793 = plength_105793; _105796 = fabs(length_105793); p_105796 = _105796; l105794: ; _105796 = p_105796; bool _105797; _105797 = 1.000000e-17 < _105796; if (_105797) goto l105798; else goto l107334; l107334: ; struct_vec_9645 n_107335; n_107335.e0 = _105779; n_107335.e1 = _105783; n_107335.e2 = _105788; pvnormalize_105801 = n_107335; goto l105799; l105798: ; double _107331; _107331 = _105783 / length_105793; double _107332; _107332 = _105788 / length_105793; double _107330; _107330 = _105779 / length_105793; struct_vec_9645 _107333; _107333.e0 = _107330; _107333.e1 = _107331; _107333.e2 = _107332; pvnormalize_105801 = _107333; goto l105799; l105799: ; vnormalize_105801 = pvnormalize_105801; struct_vec_9645 p_107328; p_107328.e0 = _105778; p_107328.e1 = _105782; p_107328.e2 = _105787; struct_Isect_9647 isect_107329; isect_107329.e0 = t_105772; isect_107329.e1 = p_107328; isect_107329.e2 = vnormalize_105801; isect_107329.e3 = 1; pray_sphere_intersect_105804 = isect_107329; goto l105802; l105802: ; ray_sphere_intersect_105804 = pray_sphere_intersect_105804; double _105805; _105805 = _105358 * rx_105748; double _105806; _105806 = _105805 + _105755; double _105807; _105807 = _105361 * rz_105761; double _105808; _105808 = _105806 + _105807; double _105809; _105809 = _105808 * _105808; double D_105810; D_105810 = _105809 - C_105369; bool _105811; _105811 = 0.000000e+00 < D_105810; if (_105811) goto l105812; else goto l107327; l107327: ; goto l107324; l105812: ; _105815 = sqrt(D_105810); p_105815 = _105815; l105813: ; _105815 = p_105815; double _105816; _105816 = -0.000000e+00 - _105808; double t_105817; t_105817 = _105816 - _105815; bool _105818; _105818 = 0.000000e+00 < t_105817; if (_105818) goto l105819; else goto l107326; l107326: ; goto l107323; l105819: ; double _105820; _105820 = ray_sphere_intersect_105804.e0; bool _105821; _105821 = t_105817 < _105820; if (_105821) goto l105822; else goto l107322; l107322: ; goto l107323; l107323: ; goto l107324; l107324: ; pray_sphere_intersect_105850 = ray_sphere_intersect_105804; goto l105848; l105822: ; double _105827; _105827 = ry_105754 * t_105817; double _105832; _105832 = rz_105761 * t_105817; double _105833; _105833 = _105300 + _105832; double _105823; _105823 = rx_105748 * t_105817; double _105828; _105828 = _105288 + _105827; double _105834; _105834 = _105833 - -3.000000e+00; double _105824; _105824 = _105275 + _105823; double _105829; _105829 = _105828 - 0.000000e+00; double _105835; _105835 = _105834 * _105834; double _105825; _105825 = _105824 - -5.000000e-01; double _105830; _105830 = _105829 * _105829; double _105826; _105826 = _105825 * _105825; double _105831; _105831 = _105826 + _105830; double _105836; _105836 = _105831 + _105835; length_105839 = sqrt(_105836); plength_105839 = length_105839; l105837: ; length_105839 = plength_105839; _105842 = fabs(length_105839); p_105842 = _105842; l105840: ; _105842 = p_105842; bool _105843; _105843 = 1.000000e-17 < _105842; if (_105843) goto l105844; else goto l107320; l107320: ; struct_vec_9645 n_107321; n_107321.e0 = _105825; n_107321.e1 = _105829; n_107321.e2 = _105834; pvnormalize_105847 = n_107321; goto l105845; l105844: ; double _107316; _107316 = _105825 / length_105839; double _107318; _107318 = _105834 / length_105839; double _107317; _107317 = _105829 / length_105839; struct_vec_9645 _107319; _107319.e0 = _107316; _107319.e1 = _107317; _107319.e2 = _107318; pvnormalize_105847 = _107319; goto l105845; l105845: ; vnormalize_105847 = pvnormalize_105847; struct_vec_9645 p_107314; p_107314.e0 = _105824; p_107314.e1 = _105828; p_107314.e2 = _105833; struct_Isect_9647 isect_107315; isect_107315.e0 = t_105817; isect_107315.e1 = p_107314; isect_107315.e2 = vnormalize_105847; isect_107315.e3 = 1; pray_sphere_intersect_105850 = isect_107315; goto l105848; l105848: ; ray_sphere_intersect_105850 = pray_sphere_intersect_105850; double _105853; _105853 = _105414 * rz_105761; double _105851; _105851 = _105411 * rx_105748; double _105852; _105852 = _105851 + _105755; double _105854; _105854 = _105852 + _105853; double _105855; _105855 = _105854 * _105854; double D_105856; D_105856 = _105855 - C_105422; bool _105857; _105857 = 0.000000e+00 < D_105856; if (_105857) goto l105858; else goto l107313; l107313: ; goto l107310; l105858: ; _105861 = sqrt(D_105856); p_105861 = _105861; l105859: ; _105861 = p_105861; double _105862; _105862 = -0.000000e+00 - _105854; double t_105863; t_105863 = _105862 - _105861; bool _105864; _105864 = 0.000000e+00 < t_105863; if (_105864) goto l105865; else goto l107312; l107312: ; goto l107309; l105865: ; double _105866; _105866 = ray_sphere_intersect_105850.e0; bool _105867; _105867 = t_105863 < _105866; if (_105867) goto l105868; else goto l107308; l107308: ; goto l107309; l107309: ; goto l107310; l107310: ; pray_sphere_intersect_105896 = ray_sphere_intersect_105850; goto l105894; l105868: ; double _105869; _105869 = rx_105748 * t_105863; double _105878; _105878 = rz_105761 * t_105863; double _105873; _105873 = ry_105754 * t_105863; double _105870; _105870 = _105275 + _105869; double _105879; _105879 = _105300 + _105878; double _105874; _105874 = _105288 + _105873; double _105871; _105871 = _105870 - 1.000000e+00; double _105880; _105880 = _105879 - -2.200000e+00; double _105875; _105875 = _105874 - 0.000000e+00; double _105872; _105872 = _105871 * _105871; double _105881; _105881 = _105880 * _105880; double _105876; _105876 = _105875 * _105875; double _105877; _105877 = _105872 + _105876; double _105882; _105882 = _105877 + _105881; length_105885 = sqrt(_105882); plength_105885 = length_105885; l105883: ; length_105885 = plength_105885; _105888 = fabs(length_105885); p_105888 = _105888; l105886: ; _105888 = p_105888; bool _105889; _105889 = 1.000000e-17 < _105888; if (_105889) goto l105890; else goto l107306; l107306: ; struct_vec_9645 n_107307; n_107307.e0 = _105871; n_107307.e1 = _105875; n_107307.e2 = _105880; pvnormalize_105893 = n_107307; goto l105891; l105890: ; double _107303; _107303 = _105875 / length_105885; double _107302; _107302 = _105871 / length_105885; double _107304; _107304 = _105880 / length_105885; struct_vec_9645 _107305; _107305.e0 = _107302; _107305.e1 = _107303; _107305.e2 = _107304; pvnormalize_105893 = _107305; goto l105891; l105891: ; vnormalize_105893 = pvnormalize_105893; struct_vec_9645 p_107300; p_107300.e0 = _105870; p_107300.e1 = _105874; p_107300.e2 = _105879; struct_Isect_9647 isect_107301; isect_107301.e0 = t_105863; isect_107301.e1 = p_107300; isect_107301.e2 = vnormalize_105893; isect_107301.e3 = 1; pray_sphere_intersect_105896 = isect_107301; goto l105894; l105894: ; ray_sphere_intersect_105896 = pray_sphere_intersect_105896; double _105900; _105900 = 0.000000e+00 * rz_105761; double _105898; _105898 = 1.000000e+00 * ry_105754; double _105897; _105897 = 0.000000e+00 * rx_105748; double _105899; _105899 = _105897 + _105898; double _105901; _105901 = _105899 + _105900; _105904 = fabs(_105901); p_105904 = _105904; l105902: ; _105904 = p_105904; bool _105905; _105905 = 1.000000e-17 <= _105904; if (_105905) goto l105906; else goto l107299; l107299: ; goto l107296; l105906: ; double t_105907; t_105907 = _105480 / _105901; bool _105908; _105908 = 0.000000e+00 < t_105907; if (_105908) goto l105909; else goto l107298; l107298: ; goto l107295; l105909: ; double _105910; _105910 = ray_sphere_intersect_105896.e0; bool _105911; _105911 = t_105907 < _105910; if (_105911) goto l105912; else goto l107294; l107294: ; goto l107295; l107295: ; goto l107296; l107296: ; pray_plane_intersect_105915 = ray_sphere_intersect_105896; goto l105913; l105912: ; double _107290; _107290 = rz_105761 * t_105907; double _107286; _107286 = rx_105748 * t_105907; double _107287; _107287 = _105275 + _107286; double _107288; _107288 = ry_105754 * t_105907; double _107291; _107291 = _105300 + _107290; double _107289; _107289 = _105288 + _107288; struct_vec_9645 p_107292; p_107292.e0 = _107287; p_107292.e1 = _107289; p_107292.e2 = _107291; struct_vec_9645 _106999_554; _106999_554.e0 = 0.000000e+00; _106999_554.e1 = 1.000000e+00; _106999_554.e2 = 0.000000e+00; struct_Isect_9647 isect_107293; isect_107293.e0 = t_105907; isect_107293.e1 = p_107292; isect_107293.e2 = _106999_554; isect_107293.e3 = 1; pray_plane_intersect_105915 = isect_107293; goto l105913; l105913: ; ray_plane_intersect_105915 = pray_plane_intersect_105915; int _105916; _105916 = ray_plane_intersect_105915.e3; bool _105917; _105917 = _105916 == 1; if (_105917) goto l105918; else goto l107285; l107285: ; pocclusion_105921 = occlusion_105708; goto l105919; l105918: ; double _107284; _107284 = 1.000000e+00 + occlusion_105708; pocclusion_105921 = _107284; goto l105919; l105919: ; occlusion_105921 = pocclusion_105921; unsigned long _105922; _105922 = 4294883355 * lo_105723; unsigned long _105923; _105923 = _105922 + hi_105725; unsigned long hi_105926; hi_105926 = _105923 >> 32; unsigned long lo_105924; lo_105924 = 4294967295 & _105923; unsigned int _105927; _105927 = (unsigned int)hi_105926; unsigned int _105925; _105925 = (unsigned int)lo_105924; unsigned int _105928; _105928 = _105925 ^ _105927; double _105929; _105929 = (double)_105928; double _105930; _105930 = 2.328306e-10 * _105929; theta_105933 = sqrt(_105930); ptheta_105933 = theta_105933; l105931: ; theta_105933 = ptheta_105933; unsigned long _105934; _105934 = 4294883355 * lo_105924; unsigned long _105935; _105935 = _105934 + hi_105926; unsigned long lo_105936; lo_105936 = 4294967295 & _105935; unsigned long hi_105938; hi_105938 = _105935 >> 32; unsigned int _105937; _105937 = (unsigned int)lo_105936; unsigned int _105939; _105939 = (unsigned int)hi_105938; unsigned int _105940; _105940 = _105937 ^ _105939; double _105941; _105941 = (double)_105940; double _105942; _105942 = 2.328306e-10 * _105941; double phi_105943; phi_105943 = 6.283185e+00 * _105942; _105946 = cos(phi_105943); p_105946 = _105946; l105944: ; _105946 = p_105946; _105949 = sin(phi_105943); p_105949 = _105949; l105947: ; _105949 = p_105949; double _105950; _105950 = theta_105933 * theta_105933; double _105951; _105951 = 1.000000e+00 - _105950; z_105954 = sqrt(_105951); pz_105954 = z_105954; l105952: ; z_105954 = pz_105954; double _105960; _105960 = z_105954 * _105152; double x_105955; x_105955 = _105946 * theta_105933; double _105963; _105963 = x_105955 * _105192; double _105970; _105970 = x_105955 * _105190; double _105966; _105966 = z_105954 * _105165; double _105973; _105973 = z_105954 * _105163; double _105956; _105956 = x_105955 * _105196; double y_105957; y_105957 = _105949 * theta_105933; double _105971; _105971 = y_105957 * _105303; double _105958; _105958 = y_105957 * _105280; double _105964; _105964 = y_105957 * _105291; double _105972; _105972 = _105970 + _105971; double _105959; _105959 = _105956 + _105958; double _105965; _105965 = _105963 + _105964; double rz_105974; rz_105974 = _105972 + _105973; double rx_105961; rx_105961 = _105959 + _105960; double ry_105967; ry_105967 = _105965 + _105966; double _105975; _105975 = _105301 * rz_105974; double _105962; _105962 = _105276 * rx_105961; double _105968; _105968 = _105289 * ry_105967; double _105969; _105969 = _105962 + _105968; double _105976; _105976 = _105969 + _105975; double _105977; _105977 = _105976 * _105976; double D_105978; D_105978 = _105977 - C_105317; bool _105979; _105979 = 0.000000e+00 < D_105978; if (_105979) goto l105980; else goto l107283; l107283: ; goto l107280; l105980: ; _105983 = sqrt(D_105978); p_105983 = _105983; l105981: ; _105983 = p_105983; double _105984; _105984 = -0.000000e+00 - _105976; double t_105985; t_105985 = _105984 - _105983; bool _105986; _105986 = 0.000000e+00 < t_105985; if (_105986) goto l105987; else goto l107282; l107282: ; goto l107279; l105987: ; bool _105988; _105988 = t_105985 < 1.000000e+17; if (_105988) goto l105989; else goto l107278; l107278: ; goto l107279; l107279: ; goto l107280; l107280: ; struct_Isect_9647 _107049_583; _107049_583.e0 = 1.000000e+17; // bottom: _107049_583.e1 = // bottom: struct_vec_9645 _107047_587;; // bottom: _107049_583.e2 = _107047_587; _107049_583.e3 = 0; pray_sphere_intersect_106017 = _107049_583; goto l106015; l105989: ; double _105994; _105994 = ry_105967 * t_105985; double _105995; _105995 = _105288 + _105994; double _105999; _105999 = rz_105974 * t_105985; double _105990; _105990 = rx_105961 * t_105985; double _105996; _105996 = _105995 - 0.000000e+00; double _106000; _106000 = _105300 + _105999; double _105991; _105991 = _105275 + _105990; double _105997; _105997 = _105996 * _105996; double _106001; _106001 = _106000 - -3.500000e+00; double _105992; _105992 = _105991 - -2.000000e+00; double _106002; _106002 = _106001 * _106001; double _105993; _105993 = _105992 * _105992; double _105998; _105998 = _105993 + _105997; double _106003; _106003 = _105998 + _106002; length_106006 = sqrt(_106003); plength_106006 = length_106006; l106004: ; length_106006 = plength_106006; _106009 = fabs(length_106006); p_106009 = _106009; l106007: ; _106009 = p_106009; bool _106010; _106010 = 1.000000e-17 < _106009; if (_106010) goto l106011; else goto l107276; l107276: ; struct_vec_9645 n_107277; n_107277.e0 = _105992; n_107277.e1 = _105996; n_107277.e2 = _106001; pvnormalize_106014 = n_107277; goto l106012; l106011: ; double _107273; _107273 = _105996 / length_106006; double _107272; _107272 = _105992 / length_106006; double _107274; _107274 = _106001 / length_106006; struct_vec_9645 _107275; _107275.e0 = _107272; _107275.e1 = _107273; _107275.e2 = _107274; pvnormalize_106014 = _107275; goto l106012; l106012: ; vnormalize_106014 = pvnormalize_106014; struct_vec_9645 p_107270; p_107270.e0 = _105991; p_107270.e1 = _105995; p_107270.e2 = _106000; struct_Isect_9647 isect_107271; isect_107271.e0 = t_105985; isect_107271.e1 = p_107270; isect_107271.e2 = vnormalize_106014; isect_107271.e3 = 1; pray_sphere_intersect_106017 = isect_107271; goto l106015; l106015: ; ray_sphere_intersect_106017 = pray_sphere_intersect_106017; double _106020; _106020 = _105361 * rz_105974; double _106018; _106018 = _105358 * rx_105961; double _106019; _106019 = _106018 + _105968; double _106021; _106021 = _106019 + _106020; double _106022; _106022 = _106021 * _106021; double D_106023; D_106023 = _106022 - C_105369; bool _106024; _106024 = 0.000000e+00 < D_106023; if (_106024) goto l106025; else goto l107269; l107269: ; goto l107266; l106025: ; _106028 = sqrt(D_106023); p_106028 = _106028; l106026: ; _106028 = p_106028; double _106029; _106029 = -0.000000e+00 - _106021; double t_106030; t_106030 = _106029 - _106028; bool _106031; _106031 = 0.000000e+00 < t_106030; if (_106031) goto l106032; else goto l107268; l107268: ; goto l107265; l106032: ; double _106033; _106033 = ray_sphere_intersect_106017.e0; bool _106034; _106034 = t_106030 < _106033; if (_106034) goto l106035; else goto l107264; l107264: ; goto l107265; l107265: ; goto l107266; l107266: ; pray_sphere_intersect_106063 = ray_sphere_intersect_106017; goto l106061; l106035: ; double _106045; _106045 = rz_105974 * t_106030; double _106040; _106040 = ry_105967 * t_106030; double _106041; _106041 = _105288 + _106040; double _106046; _106046 = _105300 + _106045; double _106042; _106042 = _106041 - 0.000000e+00; double _106036; _106036 = rx_105961 * t_106030; double _106047; _106047 = _106046 - -3.000000e+00; double _106043; _106043 = _106042 * _106042; double _106037; _106037 = _105275 + _106036; double _106048; _106048 = _106047 * _106047; double _106038; _106038 = _106037 - -5.000000e-01; double _106039; _106039 = _106038 * _106038; double _106044; _106044 = _106039 + _106043; double _106049; _106049 = _106044 + _106048; length_106052 = sqrt(_106049); plength_106052 = length_106052; l106050: ; length_106052 = plength_106052; _106055 = fabs(length_106052); p_106055 = _106055; l106053: ; _106055 = p_106055; bool _106056; _106056 = 1.000000e-17 < _106055; if (_106056) goto l106057; else goto l107262; l107262: ; struct_vec_9645 n_107263; n_107263.e0 = _106038; n_107263.e1 = _106042; n_107263.e2 = _106047; pvnormalize_106060 = n_107263; goto l106058; l106057: ; double _107258; _107258 = _106038 / length_106052; double _107259; _107259 = _106042 / length_106052; double _107260; _107260 = _106047 / length_106052; struct_vec_9645 _107261; _107261.e0 = _107258; _107261.e1 = _107259; _107261.e2 = _107260; pvnormalize_106060 = _107261; goto l106058; l106058: ; vnormalize_106060 = pvnormalize_106060; struct_vec_9645 p_107256; p_107256.e0 = _106037; p_107256.e1 = _106041; p_107256.e2 = _106046; struct_Isect_9647 isect_107257; isect_107257.e0 = t_106030; isect_107257.e1 = p_107256; isect_107257.e2 = vnormalize_106060; isect_107257.e3 = 1; pray_sphere_intersect_106063 = isect_107257; goto l106061; l106061: ; ray_sphere_intersect_106063 = pray_sphere_intersect_106063; double _106066; _106066 = _105414 * rz_105974; double _106064; _106064 = _105411 * rx_105961; double _106065; _106065 = _106064 + _105968; double _106067; _106067 = _106065 + _106066; double _106068; _106068 = _106067 * _106067; double D_106069; D_106069 = _106068 - C_105422; bool _106070; _106070 = 0.000000e+00 < D_106069; if (_106070) goto l106071; else goto l107255; l107255: ; goto l107252; l106071: ; _106074 = sqrt(D_106069); p_106074 = _106074; l106072: ; _106074 = p_106074; double _106075; _106075 = -0.000000e+00 - _106067; double t_106076; t_106076 = _106075 - _106074; bool _106077; _106077 = 0.000000e+00 < t_106076; if (_106077) goto l106078; else goto l107254; l107254: ; goto l107251; l106078: ; double _106079; _106079 = ray_sphere_intersect_106063.e0; bool _106080; _106080 = t_106076 < _106079; if (_106080) goto l106081; else goto l107250; l107250: ; goto l107251; l107251: ; goto l107252; l107252: ; pray_sphere_intersect_106109 = ray_sphere_intersect_106063; goto l106107; l106081: ; double _106091; _106091 = rz_105974 * t_106076; double _106086; _106086 = ry_105967 * t_106076; double _106092; _106092 = _105300 + _106091; double _106093; _106093 = _106092 - -2.200000e+00; double _106087; _106087 = _105288 + _106086; double _106082; _106082 = rx_105961 * t_106076; double _106083; _106083 = _105275 + _106082; double _106084; _106084 = _106083 - 1.000000e+00; double _106088; _106088 = _106087 - 0.000000e+00; double _106085; _106085 = _106084 * _106084; double _106094; _106094 = _106093 * _106093; double _106089; _106089 = _106088 * _106088; double _106090; _106090 = _106085 + _106089; double _106095; _106095 = _106090 + _106094; length_106098 = sqrt(_106095); plength_106098 = length_106098; l106096: ; length_106098 = plength_106098; _106101 = fabs(length_106098); p_106101 = _106101; l106099: ; _106101 = p_106101; bool _106102; _106102 = 1.000000e-17 < _106101; if (_106102) goto l106103; else goto l107248; l107248: ; struct_vec_9645 n_107249; n_107249.e0 = _106084; n_107249.e1 = _106088; n_107249.e2 = _106093; pvnormalize_106106 = n_107249; goto l106104; l106103: ; double _107244; _107244 = _106084 / length_106098; double _107246; _107246 = _106093 / length_106098; double _107245; _107245 = _106088 / length_106098; struct_vec_9645 _107247; _107247.e0 = _107244; _107247.e1 = _107245; _107247.e2 = _107246; pvnormalize_106106 = _107247; goto l106104; l106104: ; vnormalize_106106 = pvnormalize_106106; struct_vec_9645 p_107242; p_107242.e0 = _106083; p_107242.e1 = _106087; p_107242.e2 = _106092; struct_Isect_9647 isect_107243; isect_107243.e0 = t_106076; isect_107243.e1 = p_107242; isect_107243.e2 = vnormalize_106106; isect_107243.e3 = 1; pray_sphere_intersect_106109 = isect_107243; goto l106107; l106107: ; ray_sphere_intersect_106109 = pray_sphere_intersect_106109; double _106111; _106111 = 1.000000e+00 * ry_105967; double _106113; _106113 = 0.000000e+00 * rz_105974; double _106110; _106110 = 0.000000e+00 * rx_105961; double _106112; _106112 = _106110 + _106111; double _106114; _106114 = _106112 + _106113; _106117 = fabs(_106114); p_106117 = _106117; l106115: ; _106117 = p_106117; bool _106118; _106118 = 1.000000e-17 <= _106117; if (_106118) goto l106119; else goto l107241; l107241: ; goto l107238; l106119: ; double t_106120; t_106120 = _105480 / _106114; bool _106121; _106121 = 0.000000e+00 < t_106120; if (_106121) goto l106122; else goto l107240; l107240: ; goto l107237; l106122: ; double _106123; _106123 = ray_sphere_intersect_106109.e0; bool _106124; _106124 = t_106120 < _106123; if (_106124) goto l106125; else goto l107236; l107236: ; goto l107237; l107237: ; goto l107238; l107238: ; pray_plane_intersect_106128 = ray_sphere_intersect_106109; goto l106126; l106125: ; double _107230; _107230 = ry_105967 * t_106120; double _107231; _107231 = _105288 + _107230; double _107228; _107228 = rx_105961 * t_106120; double _107232; _107232 = rz_105974 * t_106120; double _107233; _107233 = _105300 + _107232; double _107229; _107229 = _105275 + _107228; struct_vec_9645 p_107234; p_107234.e0 = _107229; p_107234.e1 = _107231; p_107234.e2 = _107233; struct_vec_9645 _106999_662; _106999_662.e0 = 0.000000e+00; _106999_662.e1 = 1.000000e+00; _106999_662.e2 = 0.000000e+00; struct_Isect_9647 isect_107235; isect_107235.e0 = t_106120; isect_107235.e1 = p_107234; isect_107235.e2 = _106999_662; isect_107235.e3 = 1; pray_plane_intersect_106128 = isect_107235; goto l106126; l106126: ; ray_plane_intersect_106128 = pray_plane_intersect_106128; int _106129; _106129 = ray_plane_intersect_106128.e3; bool _106130; _106130 = _106129 == 1; if (_106130) goto l106131; else goto l107227; l107227: ; pocclusion_106134 = occlusion_105921; goto l106132; l106131: ; double _107226; _107226 = 1.000000e+00 + occlusion_105921; pocclusion_106134 = _107226; goto l106132; l106132: ; occlusion_106134 = pocclusion_106134; unsigned long _106135; _106135 = 4294883355 * lo_105936; unsigned long _106136; _106136 = _106135 + hi_105938; unsigned long lo_106137; lo_106137 = 4294967295 & _106136; unsigned long hi_106139; hi_106139 = _106136 >> 32; unsigned int _106138; _106138 = (unsigned int)lo_106137; unsigned int _106140; _106140 = (unsigned int)hi_106139; unsigned int _106141; _106141 = _106138 ^ _106140; double _106142; _106142 = (double)_106141; double _106143; _106143 = 2.328306e-10 * _106142; theta_106146 = sqrt(_106143); ptheta_106146 = theta_106146; l106144: ; theta_106146 = ptheta_106146; unsigned long _106147; _106147 = 4294883355 * lo_106137; unsigned long _106148; _106148 = _106147 + hi_106139; unsigned long hi_106151; hi_106151 = _106148 >> 32; unsigned long lo_106149; lo_106149 = 4294967295 & _106148; unsigned int _106152; _106152 = (unsigned int)hi_106151; unsigned int _106150; _106150 = (unsigned int)lo_106149; unsigned int _106153; _106153 = _106150 ^ _106152; double _106154; _106154 = (double)_106153; double _106155; _106155 = 2.328306e-10 * _106154; double phi_106156; phi_106156 = 6.283185e+00 * _106155; _106159 = cos(phi_106156); p_106159 = _106159; l106157: ; _106159 = p_106159; _106162 = sin(phi_106156); p_106162 = _106162; l106160: ; _106162 = p_106162; double _106163; _106163 = theta_106146 * theta_106146; double _106164; _106164 = 1.000000e+00 - _106163; z_106167 = sqrt(_106164); pz_106167 = z_106167; l106165: ; z_106167 = pz_106167; double x_106168; x_106168 = _106159 * theta_106146; double _106169; _106169 = x_106168 * _105196; double _106179; _106179 = z_106167 * _105165; double _106186; _106186 = z_106167 * _105163; double y_106170; y_106170 = _106162 * theta_106146; double _106176; _106176 = x_106168 * _105192; double _106173; _106173 = z_106167 * _105152; double _106183; _106183 = x_106168 * _105190; double _106184; _106184 = y_106170 * _105303; double _106171; _106171 = y_106170 * _105280; double _106177; _106177 = y_106170 * _105291; double _106178; _106178 = _106176 + _106177; double _106185; _106185 = _106183 + _106184; double _106172; _106172 = _106169 + _106171; double ry_106180; ry_106180 = _106178 + _106179; double rz_106187; rz_106187 = _106185 + _106186; double rx_106174; rx_106174 = _106172 + _106173; double _106181; _106181 = _105289 * ry_106180; double _106188; _106188 = _105301 * rz_106187; double _106175; _106175 = _105276 * rx_106174; double _106182; _106182 = _106175 + _106181; double _106189; _106189 = _106182 + _106188; double _106190; _106190 = _106189 * _106189; double D_106191; D_106191 = _106190 - C_105317; bool _106192; _106192 = 0.000000e+00 < D_106191; if (_106192) goto l106193; else goto l107225; l107225: ; goto l107222; l106193: ; _106196 = sqrt(D_106191); p_106196 = _106196; l106194: ; _106196 = p_106196; double _106197; _106197 = -0.000000e+00 - _106189; double t_106198; t_106198 = _106197 - _106196; bool _106199; _106199 = 0.000000e+00 < t_106198; if (_106199) goto l106200; else goto l107224; l107224: ; goto l107221; l106200: ; bool _106201; _106201 = t_106198 < 1.000000e+17; if (_106201) goto l106202; else goto l107220; l107220: ; goto l107221; l107221: ; goto l107222; l107222: ; struct_Isect_9647 _107049_691; _107049_691.e0 = 1.000000e+17; // bottom: _107049_691.e1 = // bottom: struct_vec_9645 _107047_695;; // bottom: _107049_691.e2 = _107047_695; _107049_691.e3 = 0; pray_sphere_intersect_106230 = _107049_691; goto l106228; l106202: ; double _106207; _106207 = ry_106180 * t_106198; double _106212; _106212 = rz_106187 * t_106198; double _106203; _106203 = rx_106174 * t_106198; double _106208; _106208 = _105288 + _106207; double _106213; _106213 = _105300 + _106212; double _106204; _106204 = _105275 + _106203; double _106209; _106209 = _106208 - 0.000000e+00; double _106214; _106214 = _106213 - -3.500000e+00; double _106205; _106205 = _106204 - -2.000000e+00; double _106210; _106210 = _106209 * _106209; double _106215; _106215 = _106214 * _106214; double _106206; _106206 = _106205 * _106205; double _106211; _106211 = _106206 + _106210; double _106216; _106216 = _106211 + _106215; length_106219 = sqrt(_106216); plength_106219 = length_106219; l106217: ; length_106219 = plength_106219; _106222 = fabs(length_106219); p_106222 = _106222; l106220: ; _106222 = p_106222; bool _106223; _106223 = 1.000000e-17 < _106222; if (_106223) goto l106224; else goto l107218; l107218: ; struct_vec_9645 n_107219; n_107219.e0 = _106205; n_107219.e1 = _106209; n_107219.e2 = _106214; pvnormalize_106227 = n_107219; goto l106225; l106224: ; double _107216; _107216 = _106214 / length_106219; double _107214; _107214 = _106205 / length_106219; double _107215; _107215 = _106209 / length_106219; struct_vec_9645 _107217; _107217.e0 = _107214; _107217.e1 = _107215; _107217.e2 = _107216; pvnormalize_106227 = _107217; goto l106225; l106225: ; vnormalize_106227 = pvnormalize_106227; struct_vec_9645 p_107212; p_107212.e0 = _106204; p_107212.e1 = _106208; p_107212.e2 = _106213; struct_Isect_9647 isect_107213; isect_107213.e0 = t_106198; isect_107213.e1 = p_107212; isect_107213.e2 = vnormalize_106227; isect_107213.e3 = 1; pray_sphere_intersect_106230 = isect_107213; goto l106228; l106228: ; ray_sphere_intersect_106230 = pray_sphere_intersect_106230; double _106231; _106231 = _105358 * rx_106174; double _106233; _106233 = _105361 * rz_106187; double _106232; _106232 = _106231 + _106181; double _106234; _106234 = _106232 + _106233; double _106235; _106235 = _106234 * _106234; double D_106236; D_106236 = _106235 - C_105369; bool _106237; _106237 = 0.000000e+00 < D_106236; if (_106237) goto l106238; else goto l107211; l107211: ; goto l107208; l106238: ; _106241 = sqrt(D_106236); p_106241 = _106241; l106239: ; _106241 = p_106241; double _106242; _106242 = -0.000000e+00 - _106234; double t_106243; t_106243 = _106242 - _106241; bool _106244; _106244 = 0.000000e+00 < t_106243; if (_106244) goto l106245; else goto l107210; l107210: ; goto l107207; l106245: ; double _106246; _106246 = ray_sphere_intersect_106230.e0; bool _106247; _106247 = t_106243 < _106246; if (_106247) goto l106248; else goto l107206; l107206: ; goto l107207; l107207: ; goto l107208; l107208: ; pray_sphere_intersect_106276 = ray_sphere_intersect_106230; goto l106274; l106248: ; double _106253; _106253 = ry_106180 * t_106243; double _106254; _106254 = _105288 + _106253; double _106249; _106249 = rx_106174 * t_106243; double _106258; _106258 = rz_106187 * t_106243; double _106259; _106259 = _105300 + _106258; double _106260; _106260 = _106259 - -3.000000e+00; double _106255; _106255 = _106254 - 0.000000e+00; double _106250; _106250 = _105275 + _106249; double _106261; _106261 = _106260 * _106260; double _106256; _106256 = _106255 * _106255; double _106251; _106251 = _106250 - -5.000000e-01; double _106252; _106252 = _106251 * _106251; double _106257; _106257 = _106252 + _106256; double _106262; _106262 = _106257 + _106261; length_106265 = sqrt(_106262); plength_106265 = length_106265; l106263: ; length_106265 = plength_106265; _106268 = fabs(length_106265); p_106268 = _106268; l106266: ; _106268 = p_106268; bool _106269; _106269 = 1.000000e-17 < _106268; if (_106269) goto l106270; else goto l107204; l107204: ; struct_vec_9645 n_107205; n_107205.e0 = _106251; n_107205.e1 = _106255; n_107205.e2 = _106260; pvnormalize_106273 = n_107205; goto l106271; l106270: ; double _107202; _107202 = _106260 / length_106265; double _107200; _107200 = _106251 / length_106265; double _107201; _107201 = _106255 / length_106265; struct_vec_9645 _107203; _107203.e0 = _107200; _107203.e1 = _107201; _107203.e2 = _107202; pvnormalize_106273 = _107203; goto l106271; l106271: ; vnormalize_106273 = pvnormalize_106273; struct_vec_9645 p_107198; p_107198.e0 = _106250; p_107198.e1 = _106254; p_107198.e2 = _106259; struct_Isect_9647 isect_107199; isect_107199.e0 = t_106243; isect_107199.e1 = p_107198; isect_107199.e2 = vnormalize_106273; isect_107199.e3 = 1; pray_sphere_intersect_106276 = isect_107199; goto l106274; l106274: ; ray_sphere_intersect_106276 = pray_sphere_intersect_106276; double _106277; _106277 = _105411 * rx_106174; double _106279; _106279 = _105414 * rz_106187; double _106278; _106278 = _106277 + _106181; double _106280; _106280 = _106278 + _106279; double _106281; _106281 = _106280 * _106280; double D_106282; D_106282 = _106281 - C_105422; bool _106283; _106283 = 0.000000e+00 < D_106282; if (_106283) goto l106284; else goto l107197; l107197: ; goto l107194; l106284: ; _106287 = sqrt(D_106282); p_106287 = _106287; l106285: ; _106287 = p_106287; double _106288; _106288 = -0.000000e+00 - _106280; double t_106289; t_106289 = _106288 - _106287; bool _106290; _106290 = 0.000000e+00 < t_106289; if (_106290) goto l106291; else goto l107196; l107196: ; goto l107193; l106291: ; double _106292; _106292 = ray_sphere_intersect_106276.e0; bool _106293; _106293 = t_106289 < _106292; if (_106293) goto l106294; else goto l107192; l107192: ; goto l107193; l107193: ; goto l107194; l107194: ; pray_sphere_intersect_106322 = ray_sphere_intersect_106276; goto l106320; l106294: ; double _106295; _106295 = rx_106174 * t_106289; double _106296; _106296 = _105275 + _106295; double _106297; _106297 = _106296 - 1.000000e+00; double _106298; _106298 = _106297 * _106297; double _106299; _106299 = ry_106180 * t_106289; double _106304; _106304 = rz_106187 * t_106289; double _106300; _106300 = _105288 + _106299; double _106305; _106305 = _105300 + _106304; double _106301; _106301 = _106300 - 0.000000e+00; double _106306; _106306 = _106305 - -2.200000e+00; double _106302; _106302 = _106301 * _106301; double _106307; _106307 = _106306 * _106306; double _106303; _106303 = _106298 + _106302; double _106308; _106308 = _106303 + _106307; length_106311 = sqrt(_106308); plength_106311 = length_106311; l106309: ; length_106311 = plength_106311; _106314 = fabs(length_106311); p_106314 = _106314; l106312: ; _106314 = p_106314; bool _106315; _106315 = 1.000000e-17 < _106314; if (_106315) goto l106316; else goto l107190; l107190: ; struct_vec_9645 n_107191; n_107191.e0 = _106297; n_107191.e1 = _106301; n_107191.e2 = _106306; pvnormalize_106319 = n_107191; goto l106317; l106316: ; double _107186; _107186 = _106297 / length_106311; double _107188; _107188 = _106306 / length_106311; double _107187; _107187 = _106301 / length_106311; struct_vec_9645 _107189; _107189.e0 = _107186; _107189.e1 = _107187; _107189.e2 = _107188; pvnormalize_106319 = _107189; goto l106317; l106317: ; vnormalize_106319 = pvnormalize_106319; struct_vec_9645 p_107184; p_107184.e0 = _106296; p_107184.e1 = _106300; p_107184.e2 = _106305; struct_Isect_9647 isect_107185; isect_107185.e0 = t_106289; isect_107185.e1 = p_107184; isect_107185.e2 = vnormalize_106319; isect_107185.e3 = 1; pray_sphere_intersect_106322 = isect_107185; goto l106320; l106320: ; ray_sphere_intersect_106322 = pray_sphere_intersect_106322; double _106326; _106326 = 0.000000e+00 * rz_106187; double _106323; _106323 = 0.000000e+00 * rx_106174; double _106324; _106324 = 1.000000e+00 * ry_106180; double _106325; _106325 = _106323 + _106324; double _106327; _106327 = _106325 + _106326; _106330 = fabs(_106327); p_106330 = _106330; l106328: ; _106330 = p_106330; bool _106331; _106331 = 1.000000e-17 <= _106330; if (_106331) goto l106332; else goto l107183; l107183: ; goto l107180; l106332: ; double t_106333; t_106333 = _105480 / _106327; bool _106334; _106334 = 0.000000e+00 < t_106333; if (_106334) goto l106335; else goto l107182; l107182: ; goto l107179; l106335: ; double _106336; _106336 = ray_sphere_intersect_106322.e0; bool _106337; _106337 = t_106333 < _106336; if (_106337) goto l106338; else goto l107178; l107178: ; goto l107179; l107179: ; goto l107180; l107180: ; pray_plane_intersect_106341 = ray_sphere_intersect_106322; goto l106339; l106338: ; double _107174; _107174 = rz_106187 * t_106333; double _107172; _107172 = ry_106180 * t_106333; double _107173; _107173 = _105288 + _107172; double _107170; _107170 = rx_106174 * t_106333; double _107175; _107175 = _105300 + _107174; double _107171; _107171 = _105275 + _107170; struct_vec_9645 p_107176; p_107176.e0 = _107171; p_107176.e1 = _107173; p_107176.e2 = _107175; struct_vec_9645 _106999_770; _106999_770.e0 = 0.000000e+00; _106999_770.e1 = 1.000000e+00; _106999_770.e2 = 0.000000e+00; struct_Isect_9647 isect_107177; isect_107177.e0 = t_106333; isect_107177.e1 = p_107176; isect_107177.e2 = _106999_770; isect_107177.e3 = 1; pray_plane_intersect_106341 = isect_107177; goto l106339; l106339: ; ray_plane_intersect_106341 = pray_plane_intersect_106341; int _106342; _106342 = ray_plane_intersect_106341.e3; bool _106343; _106343 = _106342 == 1; if (_106343) goto l106344; else goto l107169; l107169: ; pocclusion_106347 = occlusion_106134; goto l106345; l106344: ; double _107168; _107168 = 1.000000e+00 + occlusion_106134; pocclusion_106347 = _107168; goto l106345; l106345: ; occlusion_106347 = pocclusion_106347; unsigned long _106348; _106348 = 4294883355 * lo_106149; unsigned long _106349; _106349 = _106348 + hi_106151; unsigned long lo_106350; lo_106350 = 4294967295 & _106349; unsigned long hi_106352; hi_106352 = _106349 >> 32; unsigned int _106351; _106351 = (unsigned int)lo_106350; unsigned int _106353; _106353 = (unsigned int)hi_106352; unsigned int _106354; _106354 = _106351 ^ _106353; double _106355; _106355 = (double)_106354; double _106356; _106356 = 2.328306e-10 * _106355; theta_106359 = sqrt(_106356); ptheta_106359 = theta_106359; l106357: ; theta_106359 = ptheta_106359; unsigned long _106360; _106360 = 4294883355 * lo_106350; unsigned long _106361; _106361 = _106360 + hi_106352; unsigned long lo_106362; lo_106362 = 4294967295 & _106361; unsigned int _106363; _106363 = (unsigned int)lo_106362; unsigned long hi_106364; hi_106364 = _106361 >> 32; unsigned int _106365; _106365 = (unsigned int)hi_106364; unsigned int _106366; _106366 = _106363 ^ _106365; double _106367; _106367 = (double)_106366; double _106368; _106368 = 2.328306e-10 * _106367; double phi_106369; phi_106369 = 6.283185e+00 * _106368; _106372 = cos(phi_106369); p_106372 = _106372; l106370: ; _106372 = p_106372; _106375 = sin(phi_106369); p_106375 = _106375; l106373: ; _106375 = p_106375; double _106376; _106376 = theta_106359 * theta_106359; double _106377; _106377 = 1.000000e+00 - _106376; z_106380 = sqrt(_106377); pz_106380 = z_106380; l106378: ; z_106380 = pz_106380; double x_106381; x_106381 = _106372 * theta_106359; double y_106383; y_106383 = _106375 * theta_106359; double _106399; _106399 = z_106380 * _105163; double _106384; _106384 = y_106383 * _105280; double _106389; _106389 = x_106381 * _105192; double _106390; _106390 = y_106383 * _105291; double _106391; _106391 = _106389 + _106390; double _106386; _106386 = z_106380 * _105152; double _106392; _106392 = z_106380 * _105165; double _106396; _106396 = x_106381 * _105190; double _106382; _106382 = x_106381 * _105196; double _106397; _106397 = y_106383 * _105303; double _106385; _106385 = _106382 + _106384; double ry_106393; ry_106393 = _106391 + _106392; double rx_106387; rx_106387 = _106385 + _106386; double _106398; _106398 = _106396 + _106397; double _106394; _106394 = _105289 * ry_106393; double _106388; _106388 = _105276 * rx_106387; double rz_106400; rz_106400 = _106398 + _106399; double _106395; _106395 = _106388 + _106394; double _106401; _106401 = _105301 * rz_106400; double _106402; _106402 = _106395 + _106401; double _106403; _106403 = _106402 * _106402; double D_106404; D_106404 = _106403 - C_105317; bool _106405; _106405 = 0.000000e+00 < D_106404; if (_106405) goto l106406; else goto l107167; l107167: ; goto l107164; l106406: ; _106409 = sqrt(D_106404); p_106409 = _106409; l106407: ; _106409 = p_106409; double _106410; _106410 = -0.000000e+00 - _106402; double t_106411; t_106411 = _106410 - _106409; bool _106412; _106412 = 0.000000e+00 < t_106411; if (_106412) goto l106413; else goto l107166; l107166: ; goto l107163; l106413: ; bool _106414; _106414 = t_106411 < 1.000000e+17; if (_106414) goto l106415; else goto l107162; l107162: ; goto l107163; l107163: ; goto l107164; l107164: ; struct_Isect_9647 _107049_799; _107049_799.e0 = 1.000000e+17; // bottom: _107049_799.e1 = // bottom: struct_vec_9645 _107047_803;; // bottom: _107049_799.e2 = _107047_803; _107049_799.e3 = 0; pray_sphere_intersect_106443 = _107049_799; goto l106441; l106415: ; double _106425; _106425 = rz_106400 * t_106411; double _106416; _106416 = rx_106387 * t_106411; double _106417; _106417 = _105275 + _106416; double _106420; _106420 = ry_106393 * t_106411; double _106426; _106426 = _105300 + _106425; double _106418; _106418 = _106417 - -2.000000e+00; double _106421; _106421 = _105288 + _106420; double _106427; _106427 = _106426 - -3.500000e+00; double _106419; _106419 = _106418 * _106418; double _106422; _106422 = _106421 - 0.000000e+00; double _106428; _106428 = _106427 * _106427; double _106423; _106423 = _106422 * _106422; double _106424; _106424 = _106419 + _106423; double _106429; _106429 = _106424 + _106428; length_106432 = sqrt(_106429); plength_106432 = length_106432; l106430: ; length_106432 = plength_106432; _106435 = fabs(length_106432); p_106435 = _106435; l106433: ; _106435 = p_106435; bool _106436; _106436 = 1.000000e-17 < _106435; if (_106436) goto l106437; else goto l107160; l107160: ; struct_vec_9645 n_107161; n_107161.e0 = _106418; n_107161.e1 = _106422; n_107161.e2 = _106427; pvnormalize_106440 = n_107161; goto l106438; l106437: ; double _107157; _107157 = _106422 / length_106432; double _107158; _107158 = _106427 / length_106432; double _107156; _107156 = _106418 / length_106432; struct_vec_9645 _107159; _107159.e0 = _107156; _107159.e1 = _107157; _107159.e2 = _107158; pvnormalize_106440 = _107159; goto l106438; l106438: ; vnormalize_106440 = pvnormalize_106440; struct_vec_9645 p_107154; p_107154.e0 = _106417; p_107154.e1 = _106421; p_107154.e2 = _106426; struct_Isect_9647 isect_107155; isect_107155.e0 = t_106411; isect_107155.e1 = p_107154; isect_107155.e2 = vnormalize_106440; isect_107155.e3 = 1; pray_sphere_intersect_106443 = isect_107155; goto l106441; l106441: ; ray_sphere_intersect_106443 = pray_sphere_intersect_106443; double _106444; _106444 = _105358 * rx_106387; double _106446; _106446 = _105361 * rz_106400; double _106445; _106445 = _106444 + _106394; double _106447; _106447 = _106445 + _106446; double _106448; _106448 = _106447 * _106447; double D_106449; D_106449 = _106448 - C_105369; bool _106450; _106450 = 0.000000e+00 < D_106449; if (_106450) goto l106451; else goto l107153; l107153: ; goto l107150; l106451: ; _106454 = sqrt(D_106449); p_106454 = _106454; l106452: ; _106454 = p_106454; double _106455; _106455 = -0.000000e+00 - _106447; double t_106456; t_106456 = _106455 - _106454; bool _106457; _106457 = 0.000000e+00 < t_106456; if (_106457) goto l106458; else goto l107152; l107152: ; goto l107149; l106458: ; double _106459; _106459 = ray_sphere_intersect_106443.e0; bool _106460; _106460 = t_106456 < _106459; if (_106460) goto l106461; else goto l107148; l107148: ; goto l107149; l107149: ; goto l107150; l107150: ; pray_sphere_intersect_106489 = ray_sphere_intersect_106443; goto l106487; l106461: ; double _106462; _106462 = rx_106387 * t_106456; double _106471; _106471 = rz_106400 * t_106456; double _106463; _106463 = _105275 + _106462; double _106466; _106466 = ry_106393 * t_106456; double _106472; _106472 = _105300 + _106471; double _106467; _106467 = _105288 + _106466; double _106464; _106464 = _106463 - -5.000000e-01; double _106473; _106473 = _106472 - -3.000000e+00; double _106468; _106468 = _106467 - 0.000000e+00; double _106465; _106465 = _106464 * _106464; double _106474; _106474 = _106473 * _106473; double _106469; _106469 = _106468 * _106468; double _106470; _106470 = _106465 + _106469; double _106475; _106475 = _106470 + _106474; length_106478 = sqrt(_106475); plength_106478 = length_106478; l106476: ; length_106478 = plength_106478; _106481 = fabs(length_106478); p_106481 = _106481; l106479: ; _106481 = p_106481; bool _106482; _106482 = 1.000000e-17 < _106481; if (_106482) goto l106483; else goto l107146; l107146: ; struct_vec_9645 n_107147; n_107147.e0 = _106464; n_107147.e1 = _106468; n_107147.e2 = _106473; pvnormalize_106486 = n_107147; goto l106484; l106483: ; double _107143; _107143 = _106468 / length_106478; double _107144; _107144 = _106473 / length_106478; double _107142; _107142 = _106464 / length_106478; struct_vec_9645 _107145; _107145.e0 = _107142; _107145.e1 = _107143; _107145.e2 = _107144; pvnormalize_106486 = _107145; goto l106484; l106484: ; vnormalize_106486 = pvnormalize_106486; struct_vec_9645 p_107140; p_107140.e0 = _106463; p_107140.e1 = _106467; p_107140.e2 = _106472; struct_Isect_9647 isect_107141; isect_107141.e0 = t_106456; isect_107141.e1 = p_107140; isect_107141.e2 = vnormalize_106486; isect_107141.e3 = 1; pray_sphere_intersect_106489 = isect_107141; goto l106487; l106487: ; ray_sphere_intersect_106489 = pray_sphere_intersect_106489; double _106492; _106492 = _105414 * rz_106400; double _106490; _106490 = _105411 * rx_106387; double _106491; _106491 = _106490 + _106394; double _106493; _106493 = _106491 + _106492; double _106494; _106494 = _106493 * _106493; double D_106495; D_106495 = _106494 - C_105422; bool _106496; _106496 = 0.000000e+00 < D_106495; if (_106496) goto l106497; else goto l107139; l107139: ; goto l107136; l106497: ; _106500 = sqrt(D_106495); p_106500 = _106500; l106498: ; _106500 = p_106500; double _106501; _106501 = -0.000000e+00 - _106493; double t_106502; t_106502 = _106501 - _106500; bool _106503; _106503 = 0.000000e+00 < t_106502; if (_106503) goto l106504; else goto l107138; l107138: ; goto l107135; l106504: ; double _106505; _106505 = ray_sphere_intersect_106489.e0; bool _106506; _106506 = t_106502 < _106505; if (_106506) goto l106507; else goto l107134; l107134: ; goto l107135; l107135: ; goto l107136; l107136: ; pray_sphere_intersect_106535 = ray_sphere_intersect_106489; goto l106533; l106507: ; double _106517; _106517 = rz_106400 * t_106502; double _106518; _106518 = _105300 + _106517; double _106508; _106508 = rx_106387 * t_106502; double _106509; _106509 = _105275 + _106508; double _106512; _106512 = ry_106393 * t_106502; double _106513; _106513 = _105288 + _106512; double _106519; _106519 = _106518 - -2.200000e+00; double _106510; _106510 = _106509 - 1.000000e+00; double _106514; _106514 = _106513 - 0.000000e+00; double _106520; _106520 = _106519 * _106519; double _106511; _106511 = _106510 * _106510; double _106515; _106515 = _106514 * _106514; double _106516; _106516 = _106511 + _106515; double _106521; _106521 = _106516 + _106520; length_106524 = sqrt(_106521); plength_106524 = length_106524; l106522: ; length_106524 = plength_106524; _106527 = fabs(length_106524); p_106527 = _106527; l106525: ; _106527 = p_106527; bool _106528; _106528 = 1.000000e-17 < _106527; if (_106528) goto l106529; else goto l107132; l107132: ; struct_vec_9645 n_107133; n_107133.e0 = _106510; n_107133.e1 = _106514; n_107133.e2 = _106519; pvnormalize_106532 = n_107133; goto l106530; l106529: ; double _107129; _107129 = _106514 / length_106524; double _107128; _107128 = _106510 / length_106524; double _107130; _107130 = _106519 / length_106524; struct_vec_9645 _107131; _107131.e0 = _107128; _107131.e1 = _107129; _107131.e2 = _107130; pvnormalize_106532 = _107131; goto l106530; l106530: ; vnormalize_106532 = pvnormalize_106532; struct_vec_9645 p_107126; p_107126.e0 = _106509; p_107126.e1 = _106513; p_107126.e2 = _106518; struct_Isect_9647 isect_107127; isect_107127.e0 = t_106502; isect_107127.e1 = p_107126; isect_107127.e2 = vnormalize_106532; isect_107127.e3 = 1; pray_sphere_intersect_106535 = isect_107127; goto l106533; l106533: ; ray_sphere_intersect_106535 = pray_sphere_intersect_106535; double _106539; _106539 = 0.000000e+00 * rz_106400; double _106537; _106537 = 1.000000e+00 * ry_106393; double _106536; _106536 = 0.000000e+00 * rx_106387; double _106538; _106538 = _106536 + _106537; double _106540; _106540 = _106538 + _106539; _106543 = fabs(_106540); p_106543 = _106543; l106541: ; _106543 = p_106543; bool _106544; _106544 = 1.000000e-17 <= _106543; if (_106544) goto l106545; else goto l107125; l107125: ; goto l107122; l106545: ; double t_106546; t_106546 = _105480 / _106540; bool _106547; _106547 = 0.000000e+00 < t_106546; if (_106547) goto l106548; else goto l107124; l107124: ; goto l107121; l106548: ; double _106549; _106549 = ray_sphere_intersect_106535.e0; bool _106550; _106550 = t_106546 < _106549; if (_106550) goto l106551; else goto l107120; l107120: ; goto l107121; l107121: ; goto l107122; l107122: ; pray_plane_intersect_106554 = ray_sphere_intersect_106535; goto l106552; l106551: ; double _107116; _107116 = rz_106400 * t_106546; double _107112; _107112 = rx_106387 * t_106546; double _107114; _107114 = ry_106393 * t_106546; double _107113; _107113 = _105275 + _107112; double _107117; _107117 = _105300 + _107116; double _107115; _107115 = _105288 + _107114; struct_vec_9645 p_107118; p_107118.e0 = _107113; p_107118.e1 = _107115; p_107118.e2 = _107117; struct_vec_9645 _106999_878; _106999_878.e0 = 0.000000e+00; _106999_878.e1 = 1.000000e+00; _106999_878.e2 = 0.000000e+00; struct_Isect_9647 isect_107119; isect_107119.e0 = t_106546; isect_107119.e1 = p_107118; isect_107119.e2 = _106999_878; isect_107119.e3 = 1; pray_plane_intersect_106554 = isect_107119; goto l106552; l106552: ; ray_plane_intersect_106554 = pray_plane_intersect_106554; int _106555; _106555 = ray_plane_intersect_106554.e3; bool _106556; _106556 = _106555 == 1; if (_106556) goto l106557; else goto l107111; l107111: ; pocclusion_106560 = occlusion_106347; goto l106558; l106557: ; double _107110; _107110 = 1.000000e+00 + occlusion_106347; pocclusion_106560 = _107110; goto l106558; l106558: ; occlusion_106560 = pocclusion_106560; unsigned long _106561; _106561 = 4294883355 * lo_106362; unsigned long _106562; _106562 = _106561 + hi_106364; unsigned long lo_106563; lo_106563 = 4294967295 & _106562; unsigned long hi_106565; hi_106565 = _106562 >> 32; unsigned int _106564; _106564 = (unsigned int)lo_106563; unsigned int _106566; _106566 = (unsigned int)hi_106565; unsigned int _106567; _106567 = _106564 ^ _106566; double _106568; _106568 = (double)_106567; double _106569; _106569 = 2.328306e-10 * _106568; theta_106572 = sqrt(_106569); ptheta_106572 = theta_106572; l106570: ; theta_106572 = ptheta_106572; unsigned long _106573; _106573 = 4294883355 * lo_106563; unsigned long _106574; _106574 = _106573 + hi_106565; unsigned long lo_106575; lo_106575 = 4294967295 & _106574; unsigned long hi_106577; hi_106577 = _106574 >> 32; unsigned int _106576; _106576 = (unsigned int)lo_106575; unsigned int _106578; _106578 = (unsigned int)hi_106577; unsigned int _106579; _106579 = _106576 ^ _106578; double _106580; _106580 = (double)_106579; double _106581; _106581 = 2.328306e-10 * _106580; double phi_106582; phi_106582 = 6.283185e+00 * _106581; _106585 = cos(phi_106582); p_106585 = _106585; l106583: ; _106585 = p_106585; _106588 = sin(phi_106582); p_106588 = _106588; l106586: ; _106588 = p_106588; double _106589; _106589 = theta_106572 * theta_106572; double _106590; _106590 = 1.000000e+00 - _106589; z_106593 = sqrt(_106590); pz_106593 = z_106593; l106591: ; z_106593 = pz_106593; double _106612; _106612 = z_106593 * _105163; double y_106596; y_106596 = _106588 * theta_106572; double _106603; _106603 = y_106596 * _105291; double x_106594; x_106594 = _106585 * theta_106572; double _106599; _106599 = z_106593 * _105152; double _106605; _106605 = z_106593 * _105165; double _106610; _106610 = y_106596 * _105303; double _106597; _106597 = y_106596 * _105280; double _106609; _106609 = x_106594 * _105190; double _106595; _106595 = x_106594 * _105196; double _106602; _106602 = x_106594 * _105192; double _106611; _106611 = _106609 + _106610; double _106598; _106598 = _106595 + _106597; double _106604; _106604 = _106602 + _106603; double rz_106613; rz_106613 = _106611 + _106612; double rx_106600; rx_106600 = _106598 + _106599; double ry_106606; ry_106606 = _106604 + _106605; double _106614; _106614 = _105301 * rz_106613; double _106601; _106601 = _105276 * rx_106600; double _106607; _106607 = _105289 * ry_106606; double _106608; _106608 = _106601 + _106607; double _106615; _106615 = _106608 + _106614; double _106616; _106616 = _106615 * _106615; double D_106617; D_106617 = _106616 - C_105317; bool _106618; _106618 = 0.000000e+00 < D_106617; if (_106618) goto l106619; else goto l107109; l107109: ; goto l107106; l106619: ; _106622 = sqrt(D_106617); p_106622 = _106622; l106620: ; _106622 = p_106622; double _106623; _106623 = -0.000000e+00 - _106615; double t_106624; t_106624 = _106623 - _106622; bool _106625; _106625 = 0.000000e+00 < t_106624; if (_106625) goto l106626; else goto l107108; l107108: ; goto l107105; l106626: ; bool _106627; _106627 = t_106624 < 1.000000e+17; if (_106627) goto l106628; else goto l107104; l107104: ; goto l107105; l107105: ; goto l107106; l107106: ; struct_Isect_9647 _107049_907; _107049_907.e0 = 1.000000e+17; // bottom: _107049_907.e1 = // bottom: struct_vec_9645 _107047_911;; // bottom: _107049_907.e2 = _107047_911; _107049_907.e3 = 0; pray_sphere_intersect_106656 = _107049_907; goto l106654; l106628: ; double _106633; _106633 = ry_106606 * t_106624; double _106634; _106634 = _105288 + _106633; double _106629; _106629 = rx_106600 * t_106624; double _106638; _106638 = rz_106613 * t_106624; double _106635; _106635 = _106634 - 0.000000e+00; double _106630; _106630 = _105275 + _106629; double _106639; _106639 = _105300 + _106638; double _106636; _106636 = _106635 * _106635; double _106631; _106631 = _106630 - -2.000000e+00; double _106640; _106640 = _106639 - -3.500000e+00; double _106632; _106632 = _106631 * _106631; double _106641; _106641 = _106640 * _106640; double _106637; _106637 = _106632 + _106636; double _106642; _106642 = _106637 + _106641; length_106645 = sqrt(_106642); plength_106645 = length_106645; l106643: ; length_106645 = plength_106645; _106648 = fabs(length_106645); p_106648 = _106648; l106646: ; _106648 = p_106648; bool _106649; _106649 = 1.000000e-17 < _106648; if (_106649) goto l106650; else goto l107102; l107102: ; struct_vec_9645 n_107103; n_107103.e0 = _106631; n_107103.e1 = _106635; n_107103.e2 = _106640; pvnormalize_106653 = n_107103; goto l106651; l106650: ; double _107099; _107099 = _106635 / length_106645; double _107098; _107098 = _106631 / length_106645; double _107100; _107100 = _106640 / length_106645; struct_vec_9645 _107101; _107101.e0 = _107098; _107101.e1 = _107099; _107101.e2 = _107100; pvnormalize_106653 = _107101; goto l106651; l106651: ; vnormalize_106653 = pvnormalize_106653; struct_vec_9645 p_107096; p_107096.e0 = _106630; p_107096.e1 = _106634; p_107096.e2 = _106639; struct_Isect_9647 isect_107097; isect_107097.e0 = t_106624; isect_107097.e1 = p_107096; isect_107097.e2 = vnormalize_106653; isect_107097.e3 = 1; pray_sphere_intersect_106656 = isect_107097; goto l106654; l106654: ; ray_sphere_intersect_106656 = pray_sphere_intersect_106656; double _106659; _106659 = _105361 * rz_106613; double _106657; _106657 = _105358 * rx_106600; double _106658; _106658 = _106657 + _106607; double _106660; _106660 = _106658 + _106659; double _106661; _106661 = _106660 * _106660; double D_106662; D_106662 = _106661 - C_105369; bool _106663; _106663 = 0.000000e+00 < D_106662; if (_106663) goto l106664; else goto l107095; l107095: ; goto l107092; l106664: ; _106667 = sqrt(D_106662); p_106667 = _106667; l106665: ; _106667 = p_106667; double _106668; _106668 = -0.000000e+00 - _106660; double t_106669; t_106669 = _106668 - _106667; bool _106670; _106670 = 0.000000e+00 < t_106669; if (_106670) goto l106671; else goto l107094; l107094: ; goto l107091; l106671: ; double _106672; _106672 = ray_sphere_intersect_106656.e0; bool _106673; _106673 = t_106669 < _106672; if (_106673) goto l106674; else goto l107090; l107090: ; goto l107091; l107091: ; goto l107092; l107092: ; pray_sphere_intersect_106702 = ray_sphere_intersect_106656; goto l106700; l106674: ; double _106684; _106684 = rz_106613 * t_106669; double _106675; _106675 = rx_106600 * t_106669; double _106679; _106679 = ry_106606 * t_106669; double _106685; _106685 = _105300 + _106684; double _106676; _106676 = _105275 + _106675; double _106680; _106680 = _105288 + _106679; double _106686; _106686 = _106685 - -3.000000e+00; double _106677; _106677 = _106676 - -5.000000e-01; double _106681; _106681 = _106680 - 0.000000e+00; double _106687; _106687 = _106686 * _106686; double _106678; _106678 = _106677 * _106677; double _106682; _106682 = _106681 * _106681; double _106683; _106683 = _106678 + _106682; double _106688; _106688 = _106683 + _106687; length_106691 = sqrt(_106688); plength_106691 = length_106691; l106689: ; length_106691 = plength_106691; _106694 = fabs(length_106691); p_106694 = _106694; l106692: ; _106694 = p_106694; bool _106695; _106695 = 1.000000e-17 < _106694; if (_106695) goto l106696; else goto l107088; l107088: ; struct_vec_9645 n_107089; n_107089.e0 = _106677; n_107089.e1 = _106681; n_107089.e2 = _106686; pvnormalize_106699 = n_107089; goto l106697; l106696: ; double _107084; _107084 = _106677 / length_106691; double _107085; _107085 = _106681 / length_106691; double _107086; _107086 = _106686 / length_106691; struct_vec_9645 _107087; _107087.e0 = _107084; _107087.e1 = _107085; _107087.e2 = _107086; pvnormalize_106699 = _107087; goto l106697; l106697: ; vnormalize_106699 = pvnormalize_106699; struct_vec_9645 p_107082; p_107082.e0 = _106676; p_107082.e1 = _106680; p_107082.e2 = _106685; struct_Isect_9647 isect_107083; isect_107083.e0 = t_106669; isect_107083.e1 = p_107082; isect_107083.e2 = vnormalize_106699; isect_107083.e3 = 1; pray_sphere_intersect_106702 = isect_107083; goto l106700; l106700: ; ray_sphere_intersect_106702 = pray_sphere_intersect_106702; double _106705; _106705 = _105414 * rz_106613; double _106703; _106703 = _105411 * rx_106600; double _106704; _106704 = _106703 + _106607; double _106706; _106706 = _106704 + _106705; double _106707; _106707 = _106706 * _106706; double D_106708; D_106708 = _106707 - C_105422; bool _106709; _106709 = 0.000000e+00 < D_106708; if (_106709) goto l106710; else goto l107081; l107081: ; goto l107078; l106710: ; _106713 = sqrt(D_106708); p_106713 = _106713; l106711: ; _106713 = p_106713; double _106714; _106714 = -0.000000e+00 - _106706; double t_106715; t_106715 = _106714 - _106713; bool _106716; _106716 = 0.000000e+00 < t_106715; if (_106716) goto l106717; else goto l107080; l107080: ; goto l107077; l106717: ; double _106718; _106718 = ray_sphere_intersect_106702.e0; bool _106719; _106719 = t_106715 < _106718; if (_106719) goto l106720; else goto l107076; l107076: ; goto l107077; l107077: ; goto l107078; l107078: ; pray_sphere_intersect_106748 = ray_sphere_intersect_106702; goto l106746; l106720: ; double _106730; _106730 = rz_106613 * t_106715; double _106721; _106721 = rx_106600 * t_106715; double _106725; _106725 = ry_106606 * t_106715; double _106726; _106726 = _105288 + _106725; double _106727; _106727 = _106726 - 0.000000e+00; double _106722; _106722 = _105275 + _106721; double _106723; _106723 = _106722 - 1.000000e+00; double _106731; _106731 = _105300 + _106730; double _106732; _106732 = _106731 - -2.200000e+00; double _106728; _106728 = _106727 * _106727; double _106724; _106724 = _106723 * _106723; double _106733; _106733 = _106732 * _106732; double _106729; _106729 = _106724 + _106728; double _106734; _106734 = _106729 + _106733; length_106737 = sqrt(_106734); plength_106737 = length_106737; l106735: ; length_106737 = plength_106737; _106740 = fabs(length_106737); p_106740 = _106740; l106738: ; _106740 = p_106740; bool _106741; _106741 = 1.000000e-17 < _106740; if (_106741) goto l106742; else goto l107074; l107074: ; struct_vec_9645 n_107075; n_107075.e0 = _106723; n_107075.e1 = _106727; n_107075.e2 = _106732; pvnormalize_106745 = n_107075; goto l106743; l106742: ; double _107072; _107072 = _106732 / length_106737; double _107070; _107070 = _106723 / length_106737; double _107071; _107071 = _106727 / length_106737; struct_vec_9645 _107073; _107073.e0 = _107070; _107073.e1 = _107071; _107073.e2 = _107072; pvnormalize_106745 = _107073; goto l106743; l106743: ; vnormalize_106745 = pvnormalize_106745; struct_vec_9645 p_107068; p_107068.e0 = _106722; p_107068.e1 = _106726; p_107068.e2 = _106731; struct_Isect_9647 isect_107069; isect_107069.e0 = t_106715; isect_107069.e1 = p_107068; isect_107069.e2 = vnormalize_106745; isect_107069.e3 = 1; pray_sphere_intersect_106748 = isect_107069; goto l106746; l106746: ; ray_sphere_intersect_106748 = pray_sphere_intersect_106748; double _106749; _106749 = 0.000000e+00 * rx_106600; double _106752; _106752 = 0.000000e+00 * rz_106613; double _106750; _106750 = 1.000000e+00 * ry_106606; double _106751; _106751 = _106749 + _106750; double _106753; _106753 = _106751 + _106752; _106756 = fabs(_106753); p_106756 = _106756; l106754: ; _106756 = p_106756; bool _106757; _106757 = 1.000000e-17 <= _106756; if (_106757) goto l106758; else goto l107067; l107067: ; goto l107064; l106758: ; double t_106759; t_106759 = _105480 / _106753; bool _106760; _106760 = 0.000000e+00 < t_106759; if (_106760) goto l106761; else goto l107066; l107066: ; goto l107063; l106761: ; double _106762; _106762 = ray_sphere_intersect_106748.e0; bool _106763; _106763 = t_106759 < _106762; if (_106763) goto l106764; else goto l107062; l107062: ; goto l107063; l107063: ; goto l107064; l107064: ; pray_plane_intersect_106767 = ray_sphere_intersect_106748; goto l106765; l106764: ; double _107054; _107054 = rx_106600 * t_106759; double _107056; _107056 = ry_106606 * t_106759; double _107055; _107055 = _105275 + _107054; double _107057; _107057 = _105288 + _107056; double _107058; _107058 = rz_106613 * t_106759; double _107059; _107059 = _105300 + _107058; struct_vec_9645 p_107060; p_107060.e0 = _107055; p_107060.e1 = _107057; p_107060.e2 = _107059; struct_vec_9645 _106999_986; _106999_986.e0 = 0.000000e+00; _106999_986.e1 = 1.000000e+00; _106999_986.e2 = 0.000000e+00; struct_Isect_9647 isect_107061; isect_107061.e0 = t_106759; isect_107061.e1 = p_107060; isect_107061.e2 = _106999_986; isect_107061.e3 = 1; pray_plane_intersect_106767 = isect_107061; goto l106765; l106765: ; ray_plane_intersect_106767 = pray_plane_intersect_106767; int _106768; _106768 = ray_plane_intersect_106767.e3; bool _106769; _106769 = _106768 == 1; if (_106769) goto l106770; else goto l107053; l107053: ; pocclusion_106773 = occlusion_106560; goto l106771; l106770: ; double _107052; _107052 = 1.000000e+00 + occlusion_106560; pocclusion_106773 = _107052; goto l106771; l106771: ; occlusion_106773 = pocclusion_106773; unsigned long _106774; _106774 = 4294883355 * lo_106575; unsigned long _106775; _106775 = _106774 + hi_106577; unsigned long hi_106778; hi_106778 = _106775 >> 32; unsigned long lo_106776; lo_106776 = 4294967295 & _106775; unsigned int _106779; _106779 = (unsigned int)hi_106778; unsigned int _106777; _106777 = (unsigned int)lo_106776; unsigned int _106780; _106780 = _106777 ^ _106779; double _106781; _106781 = (double)_106780; double _106782; _106782 = 2.328306e-10 * _106781; theta_106785 = sqrt(_106782); ptheta_106785 = theta_106785; l106783: ; theta_106785 = ptheta_106785; unsigned long _106786; _106786 = 4294883355 * lo_106776; unsigned long _106787; _106787 = _106786 + hi_106778; unsigned long hi_106790; hi_106790 = _106787 >> 32; unsigned long lo_106788; lo_106788 = 4294967295 & _106787; unsigned int _106791; _106791 = (unsigned int)hi_106790; unsigned int _106789; _106789 = (unsigned int)lo_106788; unsigned int _106792; _106792 = _106789 ^ _106791; double _106793; _106793 = (double)_106792; double _106794; _106794 = 2.328306e-10 * _106793; double phi_106795; phi_106795 = 6.283185e+00 * _106794; _106798 = cos(phi_106795); p_106798 = _106798; l106796: ; _106798 = p_106798; _106801 = sin(phi_106795); p_106801 = _106801; l106799: ; _106801 = p_106801; double _106802; _106802 = theta_106785 * theta_106785; double _106803; _106803 = 1.000000e+00 - _106802; z_106806 = sqrt(_106803); pz_106806 = z_106806; l106804: ; z_106806 = pz_106806; double x_106807; x_106807 = _106798 * theta_106785; double y_106809; y_106809 = _106801 * theta_106785; double _106815; _106815 = x_106807 * _105192; double _106823; _106823 = y_106809 * _105303; double _106812; _106812 = z_106806 * _105152; double _106810; _106810 = y_106809 * _105280; double _106822; _106822 = x_106807 * _105190; double _106824; _106824 = _106822 + _106823; double _106825; _106825 = z_106806 * _105163; double _106818; _106818 = z_106806 * _105165; double _106816; _106816 = y_106809 * _105291; double _106808; _106808 = x_106807 * _105196; double _106817; _106817 = _106815 + _106816; double _106811; _106811 = _106808 + _106810; double rz_106826; rz_106826 = _106824 + _106825; double ry_106819; ry_106819 = _106817 + _106818; double rx_106813; rx_106813 = _106811 + _106812; double _106827; _106827 = _105301 * rz_106826; double _106820; _106820 = _105289 * ry_106819; double _106814; _106814 = _105276 * rx_106813; double _106821; _106821 = _106814 + _106820; double _106828; _106828 = _106821 + _106827; double _106829; _106829 = _106828 * _106828; double D_106830; D_106830 = _106829 - C_105317; bool _106831; _106831 = 0.000000e+00 < D_106830; if (_106831) goto l106832; else goto l107051; l107051: ; goto l107045; l106832: ; _106835 = sqrt(D_106830); p_106835 = _106835; l106833: ; _106835 = p_106835; double _106836; _106836 = -0.000000e+00 - _106828; double t_106837; t_106837 = _106836 - _106835; bool _106838; _106838 = 0.000000e+00 < t_106837; if (_106838) goto l106839; else goto l107050; l107050: ; goto l107044; l106839: ; bool _106840; _106840 = t_106837 < 1.000000e+17; if (_106840) goto l106841; else goto l107043; l107043: ; goto l107044; l107044: ; goto l107045; l107045: ; struct_Isect_9647 _107049_1015; _107049_1015.e0 = 1.000000e+17; // bottom: _107049_1015.e1 = // bottom: struct_vec_9645 _107047_1019;; // bottom: _107049_1015.e2 = _107047_1019; _107049_1015.e3 = 0; pray_sphere_intersect_106869 = _107049_1015; goto l106867; l106841: ; double _106846; _106846 = ry_106819 * t_106837; double _106847; _106847 = _105288 + _106846; double _106842; _106842 = rx_106813 * t_106837; double _106851; _106851 = rz_106826 * t_106837; double _106848; _106848 = _106847 - 0.000000e+00; double _106843; _106843 = _105275 + _106842; double _106852; _106852 = _105300 + _106851; double _106849; _106849 = _106848 * _106848; double _106844; _106844 = _106843 - -2.000000e+00; double _106853; _106853 = _106852 - -3.500000e+00; double _106845; _106845 = _106844 * _106844; double _106854; _106854 = _106853 * _106853; double _106850; _106850 = _106845 + _106849; double _106855; _106855 = _106850 + _106854; length_106858 = sqrt(_106855); plength_106858 = length_106858; l106856: ; length_106858 = plength_106858; _106861 = fabs(length_106858); p_106861 = _106861; l106859: ; _106861 = p_106861; bool _106862; _106862 = 1.000000e-17 < _106861; if (_106862) goto l106863; else goto l107041; l107041: ; struct_vec_9645 n_107042; n_107042.e0 = _106844; n_107042.e1 = _106848; n_107042.e2 = _106853; pvnormalize_106866 = n_107042; goto l106864; l106863: ; double _107038; _107038 = _106848 / length_106858; double _107039; _107039 = _106853 / length_106858; double _107037; _107037 = _106844 / length_106858; struct_vec_9645 _107040; _107040.e0 = _107037; _107040.e1 = _107038; _107040.e2 = _107039; pvnormalize_106866 = _107040; goto l106864; l106864: ; vnormalize_106866 = pvnormalize_106866; struct_vec_9645 p_107035; p_107035.e0 = _106843; p_107035.e1 = _106847; p_107035.e2 = _106852; struct_Isect_9647 isect_107036; isect_107036.e0 = t_106837; isect_107036.e1 = p_107035; isect_107036.e2 = vnormalize_106866; isect_107036.e3 = 1; pray_sphere_intersect_106869 = isect_107036; goto l106867; l106867: ; ray_sphere_intersect_106869 = pray_sphere_intersect_106869; double _106872; _106872 = _105361 * rz_106826; double _106870; _106870 = _105358 * rx_106813; double _106871; _106871 = _106870 + _106820; double _106873; _106873 = _106871 + _106872; double _106874; _106874 = _106873 * _106873; double D_106875; D_106875 = _106874 - C_105369; bool _106876; _106876 = 0.000000e+00 < D_106875; if (_106876) goto l106877; else goto l107034; l107034: ; goto l107031; l106877: ; _106880 = sqrt(D_106875); p_106880 = _106880; l106878: ; _106880 = p_106880; double _106881; _106881 = -0.000000e+00 - _106873; double t_106882; t_106882 = _106881 - _106880; bool _106883; _106883 = 0.000000e+00 < t_106882; if (_106883) goto l106884; else goto l107033; l107033: ; goto l107030; l106884: ; double _106885; _106885 = ray_sphere_intersect_106869.e0; bool _106886; _106886 = t_106882 < _106885; if (_106886) goto l106887; else goto l107029; l107029: ; goto l107030; l107030: ; goto l107031; l107031: ; pray_sphere_intersect_106915 = ray_sphere_intersect_106869; goto l106913; l106887: ; double _106892; _106892 = ry_106819 * t_106882; double _106888; _106888 = rx_106813 * t_106882; double _106889; _106889 = _105275 + _106888; double _106890; _106890 = _106889 - -5.000000e-01; double _106897; _106897 = rz_106826 * t_106882; double _106893; _106893 = _105288 + _106892; double _106891; _106891 = _106890 * _106890; double _106898; _106898 = _105300 + _106897; double _106894; _106894 = _106893 - 0.000000e+00; double _106899; _106899 = _106898 - -3.000000e+00; double _106895; _106895 = _106894 * _106894; double _106900; _106900 = _106899 * _106899; double _106896; _106896 = _106891 + _106895; double _106901; _106901 = _106896 + _106900; length_106904 = sqrt(_106901); plength_106904 = length_106904; l106902: ; length_106904 = plength_106904; _106907 = fabs(length_106904); p_106907 = _106907; l106905: ; _106907 = p_106907; bool _106908; _106908 = 1.000000e-17 < _106907; if (_106908) goto l106909; else goto l107027; l107027: ; struct_vec_9645 n_107028; n_107028.e0 = _106890; n_107028.e1 = _106894; n_107028.e2 = _106899; pvnormalize_106912 = n_107028; goto l106910; l106909: ; double _107023; _107023 = _106890 / length_106904; double _107024; _107024 = _106894 / length_106904; double _107025; _107025 = _106899 / length_106904; struct_vec_9645 _107026; _107026.e0 = _107023; _107026.e1 = _107024; _107026.e2 = _107025; pvnormalize_106912 = _107026; goto l106910; l106910: ; vnormalize_106912 = pvnormalize_106912; struct_vec_9645 p_107021; p_107021.e0 = _106889; p_107021.e1 = _106893; p_107021.e2 = _106898; struct_Isect_9647 isect_107022; isect_107022.e0 = t_106882; isect_107022.e1 = p_107021; isect_107022.e2 = vnormalize_106912; isect_107022.e3 = 1; pray_sphere_intersect_106915 = isect_107022; goto l106913; l106913: ; ray_sphere_intersect_106915 = pray_sphere_intersect_106915; double _106918; _106918 = _105414 * rz_106826; double _106916; _106916 = _105411 * rx_106813; double _106917; _106917 = _106916 + _106820; double _106919; _106919 = _106917 + _106918; double _106920; _106920 = _106919 * _106919; double D_106921; D_106921 = _106920 - C_105422; bool _106922; _106922 = 0.000000e+00 < D_106921; if (_106922) goto l106923; else goto l107020; l107020: ; goto l107017; l106923: ; _106926 = sqrt(D_106921); p_106926 = _106926; l106924: ; _106926 = p_106926; double _106927; _106927 = -0.000000e+00 - _106919; double t_106928; t_106928 = _106927 - _106926; bool _106929; _106929 = 0.000000e+00 < t_106928; if (_106929) goto l106930; else goto l107019; l107019: ; goto l107016; l106930: ; double _106931; _106931 = ray_sphere_intersect_106915.e0; bool _106932; _106932 = t_106928 < _106931; if (_106932) goto l106933; else goto l107015; l107015: ; goto l107016; l107016: ; goto l107017; l107017: ; pray_sphere_intersect_106961 = ray_sphere_intersect_106915; goto l106959; l106933: ; double _106934; _106934 = rx_106813 * t_106928; double _106943; _106943 = rz_106826 * t_106928; double _106938; _106938 = ry_106819 * t_106928; double _106944; _106944 = _105300 + _106943; double _106935; _106935 = _105275 + _106934; double _106939; _106939 = _105288 + _106938; double _106945; _106945 = _106944 - -2.200000e+00; double _106936; _106936 = _106935 - 1.000000e+00; double _106940; _106940 = _106939 - 0.000000e+00; double _106946; _106946 = _106945 * _106945; double _106937; _106937 = _106936 * _106936; double _106941; _106941 = _106940 * _106940; double _106942; _106942 = _106937 + _106941; double _106947; _106947 = _106942 + _106946; length_106950 = sqrt(_106947); plength_106950 = length_106950; l106948: ; length_106950 = plength_106950; _106953 = fabs(length_106950); p_106953 = _106953; l106951: ; _106953 = p_106953; bool _106954; _106954 = 1.000000e-17 < _106953; if (_106954) goto l106955; else goto l107013; l107013: ; struct_vec_9645 n_107014; n_107014.e0 = _106936; n_107014.e1 = _106940; n_107014.e2 = _106945; pvnormalize_106958 = n_107014; goto l106956; l106955: ; double _107011; _107011 = _106945 / length_106950; double _107010; _107010 = _106940 / length_106950; double _107009; _107009 = _106936 / length_106950; struct_vec_9645 _107012; _107012.e0 = _107009; _107012.e1 = _107010; _107012.e2 = _107011; pvnormalize_106958 = _107012; goto l106956; l106956: ; vnormalize_106958 = pvnormalize_106958; struct_vec_9645 p_107007; p_107007.e0 = _106935; p_107007.e1 = _106939; p_107007.e2 = _106944; struct_Isect_9647 isect_107008; isect_107008.e0 = t_106928; isect_107008.e1 = p_107007; isect_107008.e2 = vnormalize_106958; isect_107008.e3 = 1; pray_sphere_intersect_106961 = isect_107008; goto l106959; l106959: ; ray_sphere_intersect_106961 = pray_sphere_intersect_106961; double _106965; _106965 = 0.000000e+00 * rz_106826; double _106963; _106963 = 1.000000e+00 * ry_106819; double _106962; _106962 = 0.000000e+00 * rx_106813; double _106964; _106964 = _106962 + _106963; double _106966; _106966 = _106964 + _106965; _106969 = fabs(_106966); p_106969 = _106969; l106967: ; _106969 = p_106969; bool _106970; _106970 = 1.000000e-17 <= _106969; if (_106970) goto l106971; else goto l107006; l107006: ; goto l107003; l106971: ; double t_106972; t_106972 = _105480 / _106966; bool _106973; _106973 = 0.000000e+00 < t_106972; if (_106973) goto l106974; else goto l107005; l107005: ; goto l107002; l106974: ; double _106975; _106975 = ray_sphere_intersect_106961.e0; bool _106976; _106976 = t_106972 < _106975; if (_106976) goto l106977; else goto l107001; l107001: ; goto l107002; l107002: ; goto l107003; l107003: ; pray_plane_intersect_106980 = ray_sphere_intersect_106961; goto l106978; l106977: ; double _106996; _106996 = rz_106826 * t_106972; double _106992; _106992 = rx_106813 * t_106972; double _106997; _106997 = _105300 + _106996; double _106994; _106994 = ry_106819 * t_106972; double _106993; _106993 = _105275 + _106992; double _106995; _106995 = _105288 + _106994; struct_vec_9645 p_106998; p_106998.e0 = _106993; p_106998.e1 = _106995; p_106998.e2 = _106997; struct_vec_9645 _106999_1094; _106999_1094.e0 = 0.000000e+00; _106999_1094.e1 = 1.000000e+00; _106999_1094.e2 = 0.000000e+00; struct_Isect_9647 isect_107000; isect_107000.e0 = t_106972; isect_107000.e1 = p_106998; isect_107000.e2 = _106999_1094; isect_107000.e3 = 1; pray_plane_intersect_106980 = isect_107000; goto l106978; l106978: ; ray_plane_intersect_106980 = pray_plane_intersect_106980; int _106981; _106981 = ray_plane_intersect_106980.e3; bool _106982; _106982 = _106981 == 1; if (_106982) goto l106983; else goto l106991; l106991: ; pocclusion_106986 = occlusion_106773; goto l106984; l106983: ; double _106990; _106990 = 1.000000e+00 + occlusion_106773; pocclusion_106986 = _106990; goto l106984; l106984: ; occlusion_106986 = pocclusion_106986; int _106987; _106987 = lower_105220 + step_105222; unsigned long _106988; _106988 = 4294883355 * lo_106788; unsigned long _106989; _106989 = _106988 + hi_106790; plower_105220 = _106987; pupper_105221 = upper_105221; pstep_105222 = step_105222; pocclusion_105223 = occlusion_106986; pstate_105224 = _106989; goto l105218; } }
e40040273426f1718781afe49b36ef9fd62829ad.cu
extern "C" { typedef struct { double e0; double e1; double e2; } struct_vec_9645; typedef struct { double e0; struct_vec_9645 e1; struct_vec_9645 e2; int e3; } struct_Isect_9647; __device__ inline int threadIdx_x() { return threadIdx.x; } __device__ inline int threadIdx_y() { return threadIdx.y; } __device__ inline int threadIdx_z() { return threadIdx.z; } __device__ inline int blockIdx_x() { return blockIdx.x; } __device__ inline int blockIdx_y() { return blockIdx.y; } __device__ inline int blockIdx_z() { return blockIdx.z; } __device__ inline int blockDim_x() { return blockDim.x; } __device__ inline int blockDim_y() { return blockDim.y; } __device__ inline int blockDim_z() { return blockDim.z; } __device__ inline int gridDim_x() { return gridDim.x; } __device__ inline int gridDim_y() { return gridDim.y; } __device__ inline int gridDim_z() { return gridDim.z; } __global__ void lambda_71814(unsigned long*, unsigned char*); __global__ __launch_bounds__ (32 * 4 * 1) void lambda_71814(unsigned long* _71817_104835, unsigned char* _71818_104836) { int threadIdx_y_104842; int pthreadIdx_y_104842; int blockDim_y_104848; int pblockDim_y_104848; int blockIdx_y_104854; int pblockIdx_y_104854; int threadIdx_x_104860; int pthreadIdx_x_104860; int blockDim_x_104866; int pblockDim_x_104866; int blockIdx_x_104872; int pblockIdx_x_104872; int threadIdx_x_104886; int pthreadIdx_x_104886; int blockDim_x_104889; int pblockDim_x_104889; int blockIdx_x_104892; int pblockIdx_x_104892; int threadIdx_y_104895; int pthreadIdx_y_104895; int blockDim_y_104898; int pblockDim_y_104898; int blockIdx_y_104901; int pblockIdx_y_104901; int lower_104904; int plower_104904; int upper_104905; int pupper_104905; int step_104906; int pstep_104906; double r_104907; double pr_104907; double g_104908; double pg_104908; double b_104909; double pb_104909; unsigned long state_104910; unsigned long pstate_104910; int _107577; int p_107577; int _107582; int p_107582; int _107589; int p_107589; int _107593; int p_107593; int _107600; int p_107600; int _107604; int p_107604; int threadIdx_y_107607; int pthreadIdx_y_107607; int blockDim_y_107610; int pblockDim_y_107610; int blockIdx_y_107613; int pblockIdx_y_107613; int threadIdx_x_107616; int pthreadIdx_x_107616; int blockDim_x_107619; int pblockDim_x_107619; int blockIdx_x_107622; int pblockIdx_x_107622; int threadIdx_y_107636; int pthreadIdx_y_107636; int blockDim_y_107639; int pblockDim_y_107639; int blockIdx_y_107642; int pblockIdx_y_107642; int threadIdx_x_107645; int pthreadIdx_x_107645; int blockDim_x_107648; int pblockDim_x_107648; int blockIdx_x_107651; int pblockIdx_x_107651; int threadIdx_y_107665; int pthreadIdx_y_107665; int blockDim_y_107668; int pblockDim_y_107668; int blockIdx_y_107671; int pblockIdx_y_107671; int threadIdx_x_107674; int pthreadIdx_x_107674; int blockDim_x_107677; int pblockDim_x_107677; int blockIdx_x_107680; int pblockIdx_x_107680; int lower_104915; int plower_104915; int upper_104916; int pupper_104916; int step_104917; int pstep_104917; double r_104918; double pr_104918; double g_104919; double pg_104919; double b_104920; double pb_104920; unsigned long state_104921; unsigned long pstate_104921; double length_104955; double plength_104955; double _104962; double p_104962; struct_vec_9645 vnormalize_104968; struct_vec_9645 pvnormalize_104968; double _104988; double p_104988; double length_105014; double plength_105014; double _105017; double p_105017; struct_vec_9645 vnormalize_105022; struct_vec_9645 pvnormalize_105022; struct_Isect_9647 ray_sphere_intersect_105025; struct_Isect_9647 pray_sphere_intersect_105025; double _105039; double p_105039; double length_105065; double plength_105065; double _105068; double p_105068; struct_vec_9645 vnormalize_105073; struct_vec_9645 pvnormalize_105073; struct_Isect_9647 ray_sphere_intersect_105076; struct_Isect_9647 pray_sphere_intersect_105076; double _105090; double p_105090; double length_105115; double plength_105115; double _105118; double p_105118; struct_vec_9645 vnormalize_105123; struct_vec_9645 pvnormalize_105123; struct_Isect_9647 ray_sphere_intersect_105126; struct_Isect_9647 pray_sphere_intersect_105126; double _105134; double p_105134; struct_Isect_9647 ray_plane_intersect_105145; struct_Isect_9647 pray_plane_intersect_105145; double _105160; double p_105160; double _105161; double p_105161; double _105162; double p_105162; double length_105181; double plength_105181; double _105184; double p_105184; struct_vec_9645 vnormalize_105189; struct_vec_9645 pvnormalize_105189; double length_105209; double plength_105209; double _105212; double p_105212; struct_vec_9645 vnormalize_105217; struct_vec_9645 pvnormalize_105217; int lower_105220; int plower_105220; int upper_105221; int pupper_105221; int step_105222; int pstep_105222; double occlusion_105223; double pocclusion_105223; unsigned long state_105224; unsigned long pstate_105224; double r_107461; double pr_107461; double g_107462; double pg_107462; double b_107463; double pb_107463; unsigned long state_107464; unsigned long pstate_107464; double theta_105239; double ptheta_105239; double _105258; double p_105258; double _105265; double p_105265; double z_105270; double pz_105270; double _105323; double p_105323; double length_105346; double plength_105346; double _105349; double p_105349; struct_vec_9645 vnormalize_105354; struct_vec_9645 pvnormalize_105354; struct_Isect_9647 ray_sphere_intersect_105357; struct_Isect_9647 pray_sphere_intersect_105357; double _105375; double p_105375; double length_105399; double plength_105399; double _105402; double p_105402; struct_vec_9645 vnormalize_105407; struct_vec_9645 pvnormalize_105407; struct_Isect_9647 ray_sphere_intersect_105410; struct_Isect_9647 pray_sphere_intersect_105410; double _105428; double p_105428; double length_105452; double plength_105452; double _105455; double p_105455; struct_vec_9645 vnormalize_105460; struct_vec_9645 pvnormalize_105460; struct_Isect_9647 ray_sphere_intersect_105463; struct_Isect_9647 pray_sphere_intersect_105463; double _105471; double p_105471; struct_Isect_9647 ray_plane_intersect_105489; struct_Isect_9647 pray_plane_intersect_105489; double occlusion_105495; double pocclusion_105495; double theta_105507; double ptheta_105507; double _105520; double p_105520; double _105523; double p_105523; double z_105528; double pz_105528; double _105557; double p_105557; double length_105580; double plength_105580; double _105583; double p_105583; struct_vec_9645 vnormalize_105588; struct_vec_9645 pvnormalize_105588; struct_Isect_9647 ray_sphere_intersect_105591; struct_Isect_9647 pray_sphere_intersect_105591; double _105602; double p_105602; double length_105626; double plength_105626; double _105629; double p_105629; struct_vec_9645 vnormalize_105634; struct_vec_9645 pvnormalize_105634; struct_Isect_9647 ray_sphere_intersect_105637; struct_Isect_9647 pray_sphere_intersect_105637; double _105648; double p_105648; double length_105672; double plength_105672; double _105675; double p_105675; struct_vec_9645 vnormalize_105680; struct_vec_9645 pvnormalize_105680; struct_Isect_9647 ray_sphere_intersect_105683; struct_Isect_9647 pray_sphere_intersect_105683; double _105691; double p_105691; struct_Isect_9647 ray_plane_intersect_105702; struct_Isect_9647 pray_plane_intersect_105702; double occlusion_105708; double pocclusion_105708; double theta_105720; double ptheta_105720; double _105733; double p_105733; double _105736; double p_105736; double z_105741; double pz_105741; double _105770; double p_105770; double length_105793; double plength_105793; double _105796; double p_105796; struct_vec_9645 vnormalize_105801; struct_vec_9645 pvnormalize_105801; struct_Isect_9647 ray_sphere_intersect_105804; struct_Isect_9647 pray_sphere_intersect_105804; double _105815; double p_105815; double length_105839; double plength_105839; double _105842; double p_105842; struct_vec_9645 vnormalize_105847; struct_vec_9645 pvnormalize_105847; struct_Isect_9647 ray_sphere_intersect_105850; struct_Isect_9647 pray_sphere_intersect_105850; double _105861; double p_105861; double length_105885; double plength_105885; double _105888; double p_105888; struct_vec_9645 vnormalize_105893; struct_vec_9645 pvnormalize_105893; struct_Isect_9647 ray_sphere_intersect_105896; struct_Isect_9647 pray_sphere_intersect_105896; double _105904; double p_105904; struct_Isect_9647 ray_plane_intersect_105915; struct_Isect_9647 pray_plane_intersect_105915; double occlusion_105921; double pocclusion_105921; double theta_105933; double ptheta_105933; double _105946; double p_105946; double _105949; double p_105949; double z_105954; double pz_105954; double _105983; double p_105983; double length_106006; double plength_106006; double _106009; double p_106009; struct_vec_9645 vnormalize_106014; struct_vec_9645 pvnormalize_106014; struct_Isect_9647 ray_sphere_intersect_106017; struct_Isect_9647 pray_sphere_intersect_106017; double _106028; double p_106028; double length_106052; double plength_106052; double _106055; double p_106055; struct_vec_9645 vnormalize_106060; struct_vec_9645 pvnormalize_106060; struct_Isect_9647 ray_sphere_intersect_106063; struct_Isect_9647 pray_sphere_intersect_106063; double _106074; double p_106074; double length_106098; double plength_106098; double _106101; double p_106101; struct_vec_9645 vnormalize_106106; struct_vec_9645 pvnormalize_106106; struct_Isect_9647 ray_sphere_intersect_106109; struct_Isect_9647 pray_sphere_intersect_106109; double _106117; double p_106117; struct_Isect_9647 ray_plane_intersect_106128; struct_Isect_9647 pray_plane_intersect_106128; double occlusion_106134; double pocclusion_106134; double theta_106146; double ptheta_106146; double _106159; double p_106159; double _106162; double p_106162; double z_106167; double pz_106167; double _106196; double p_106196; double length_106219; double plength_106219; double _106222; double p_106222; struct_vec_9645 vnormalize_106227; struct_vec_9645 pvnormalize_106227; struct_Isect_9647 ray_sphere_intersect_106230; struct_Isect_9647 pray_sphere_intersect_106230; double _106241; double p_106241; double length_106265; double plength_106265; double _106268; double p_106268; struct_vec_9645 vnormalize_106273; struct_vec_9645 pvnormalize_106273; struct_Isect_9647 ray_sphere_intersect_106276; struct_Isect_9647 pray_sphere_intersect_106276; double _106287; double p_106287; double length_106311; double plength_106311; double _106314; double p_106314; struct_vec_9645 vnormalize_106319; struct_vec_9645 pvnormalize_106319; struct_Isect_9647 ray_sphere_intersect_106322; struct_Isect_9647 pray_sphere_intersect_106322; double _106330; double p_106330; struct_Isect_9647 ray_plane_intersect_106341; struct_Isect_9647 pray_plane_intersect_106341; double occlusion_106347; double pocclusion_106347; double theta_106359; double ptheta_106359; double _106372; double p_106372; double _106375; double p_106375; double z_106380; double pz_106380; double _106409; double p_106409; double length_106432; double plength_106432; double _106435; double p_106435; struct_vec_9645 vnormalize_106440; struct_vec_9645 pvnormalize_106440; struct_Isect_9647 ray_sphere_intersect_106443; struct_Isect_9647 pray_sphere_intersect_106443; double _106454; double p_106454; double length_106478; double plength_106478; double _106481; double p_106481; struct_vec_9645 vnormalize_106486; struct_vec_9645 pvnormalize_106486; struct_Isect_9647 ray_sphere_intersect_106489; struct_Isect_9647 pray_sphere_intersect_106489; double _106500; double p_106500; double length_106524; double plength_106524; double _106527; double p_106527; struct_vec_9645 vnormalize_106532; struct_vec_9645 pvnormalize_106532; struct_Isect_9647 ray_sphere_intersect_106535; struct_Isect_9647 pray_sphere_intersect_106535; double _106543; double p_106543; struct_Isect_9647 ray_plane_intersect_106554; struct_Isect_9647 pray_plane_intersect_106554; double occlusion_106560; double pocclusion_106560; double theta_106572; double ptheta_106572; double _106585; double p_106585; double _106588; double p_106588; double z_106593; double pz_106593; double _106622; double p_106622; double length_106645; double plength_106645; double _106648; double p_106648; struct_vec_9645 vnormalize_106653; struct_vec_9645 pvnormalize_106653; struct_Isect_9647 ray_sphere_intersect_106656; struct_Isect_9647 pray_sphere_intersect_106656; double _106667; double p_106667; double length_106691; double plength_106691; double _106694; double p_106694; struct_vec_9645 vnormalize_106699; struct_vec_9645 pvnormalize_106699; struct_Isect_9647 ray_sphere_intersect_106702; struct_Isect_9647 pray_sphere_intersect_106702; double _106713; double p_106713; double length_106737; double plength_106737; double _106740; double p_106740; struct_vec_9645 vnormalize_106745; struct_vec_9645 pvnormalize_106745; struct_Isect_9647 ray_sphere_intersect_106748; struct_Isect_9647 pray_sphere_intersect_106748; double _106756; double p_106756; struct_Isect_9647 ray_plane_intersect_106767; struct_Isect_9647 pray_plane_intersect_106767; double occlusion_106773; double pocclusion_106773; double theta_106785; double ptheta_106785; double _106798; double p_106798; double _106801; double p_106801; double z_106806; double pz_106806; double _106835; double p_106835; double length_106858; double plength_106858; double _106861; double p_106861; struct_vec_9645 vnormalize_106866; struct_vec_9645 pvnormalize_106866; struct_Isect_9647 ray_sphere_intersect_106869; struct_Isect_9647 pray_sphere_intersect_106869; double _106880; double p_106880; double length_106904; double plength_106904; double _106907; double p_106907; struct_vec_9645 vnormalize_106912; struct_vec_9645 pvnormalize_106912; struct_Isect_9647 ray_sphere_intersect_106915; struct_Isect_9647 pray_sphere_intersect_106915; double _106926; double p_106926; double length_106950; double plength_106950; double _106953; double p_106953; struct_vec_9645 vnormalize_106958; struct_vec_9645 pvnormalize_106958; struct_Isect_9647 ray_sphere_intersect_106961; struct_Isect_9647 pray_sphere_intersect_106961; double _106969; double p_106969; struct_Isect_9647 ray_plane_intersect_106980; struct_Isect_9647 pray_plane_intersect_106980; double occlusion_106986; double pocclusion_106986; threadIdx_y_104842 = threadIdx_y(); pthreadIdx_y_104842 = threadIdx_y_104842; l104840: ; threadIdx_y_104842 = pthreadIdx_y_104842; blockDim_y_104848 = blockDim_y(); pblockDim_y_104848 = blockDim_y_104848; l104846: ; blockDim_y_104848 = pblockDim_y_104848; blockIdx_y_104854 = blockIdx_y(); pblockIdx_y_104854 = blockIdx_y_104854; l104852: ; blockIdx_y_104854 = pblockIdx_y_104854; threadIdx_x_104860 = threadIdx_x(); pthreadIdx_x_104860 = threadIdx_x_104860; l104858: ; threadIdx_x_104860 = pthreadIdx_x_104860; blockDim_x_104866 = blockDim_x(); pblockDim_x_104866 = blockDim_x_104866; l104864: ; blockDim_x_104866 = pblockDim_x_104866; blockIdx_x_104872 = blockIdx_x(); pblockIdx_x_104872 = blockIdx_x_104872; l104870: ; blockIdx_x_104872 = pblockIdx_x_104872; int _104877; _104877 = blockDim_x_104866 * blockIdx_x_104872; int _104874; _104874 = blockDim_y_104848 * blockIdx_y_104854; int _104875; _104875 = threadIdx_y_104842 + _104874; int _104878; _104878 = threadIdx_x_104860 + _104877; int _104876; _104876 = 256 * _104875; int _104879; _104879 = _104876 + _104878; unsigned long* _104880; _104880 = _71817_104835 + _104879; unsigned long _104881; _104881 = *_104880; threadIdx_x_104886 = threadIdx_x(); pthreadIdx_x_104886 = threadIdx_x_104886; l104884: ; threadIdx_x_104886 = pthreadIdx_x_104886; blockDim_x_104889 = blockDim_x(); pblockDim_x_104889 = blockDim_x_104889; l104887: ; blockDim_x_104889 = pblockDim_x_104889; blockIdx_x_104892 = blockIdx_x(); pblockIdx_x_104892 = blockIdx_x_104892; l104890: ; blockIdx_x_104892 = pblockIdx_x_104892; threadIdx_y_104895 = threadIdx_y(); pthreadIdx_y_104895 = threadIdx_y_104895; l104893: ; threadIdx_y_104895 = pthreadIdx_y_104895; blockDim_y_104898 = blockDim_y(); pblockDim_y_104898 = blockDim_y_104898; l104896: ; blockDim_y_104898 = pblockDim_y_104898; blockIdx_y_104901 = blockIdx_y(); pblockIdx_y_104901 = blockIdx_y_104901; l104899: ; blockIdx_y_104901 = pblockIdx_y_104901; int _104929; _104929 = blockDim_x_104889 * blockIdx_x_104892; unsigned long state_107698; state_107698 = _104881; int _104930; _104930 = threadIdx_x_104886 + _104929; int _104941; _104941 = blockDim_y_104898 * blockIdx_y_104901; double _104931; _104931 = (double)_104930; int _104942; _104942 = threadIdx_y_104895 + _104941; double _104943; _104943 = (double)_104942; plower_104904 = 0; pupper_104905 = 2; pstep_104906 = 1; pr_104907 = 0.000000e+00; pg_104908 = 0.000000e+00; pb_104909 = 0.000000e+00; pstate_104910 = state_107698; goto l104902; l104902: ; lower_104904 = plower_104904; upper_104905 = pupper_104905; step_104906 = pstep_104906; r_104907 = pr_104907; g_104908 = pg_104908; b_104909 = pb_104909; state_104910 = pstate_104910; bool _104911; _104911 = lower_104904 < upper_104905; if (_104911) goto l104912; else goto l107568; l107568: ; double _107571; _107571 = r_104907 / 4.000000e+00; double _107572; _107572 = 2.555000e+02 * _107571; int i_107573; i_107573 = (int)_107572; bool _107574; _107574 = i_107573 < 0; if (_107574) goto l107575; else goto l107697; l107697: ; p_107577 = i_107573; goto l107576; l107575: ; p_107577 = 0; goto l107576; l107576: ; _107577 = p_107577; bool _107579; _107579 = 255 < _107577; if (_107579) goto l107580; else goto l107696; l107696: ; p_107582 = _107577; goto l107581; l107580: ; p_107582 = 255; goto l107581; l107581: ; _107582 = p_107582; double _107583; _107583 = g_104908 / 4.000000e+00; double _107584; _107584 = 2.555000e+02 * _107583; int i_107585; i_107585 = (int)_107584; bool _107586; _107586 = i_107585 < 0; if (_107586) goto l107587; else goto l107695; l107695: ; p_107589 = i_107585; goto l107588; l107587: ; p_107589 = 0; goto l107588; l107588: ; _107589 = p_107589; bool _107590; _107590 = 255 < _107589; if (_107590) goto l107591; else goto l107694; l107694: ; p_107593 = _107589; goto l107592; l107591: ; p_107593 = 255; goto l107592; l107592: ; _107593 = p_107593; double _107594; _107594 = b_104909 / 4.000000e+00; double _107595; _107595 = 2.555000e+02 * _107594; int i_107596; i_107596 = (int)_107595; bool _107597; _107597 = i_107596 < 0; if (_107597) goto l107598; else goto l107693; l107693: ; p_107600 = i_107596; goto l107599; l107598: ; p_107600 = 0; goto l107599; l107599: ; _107600 = p_107600; bool _107601; _107601 = 255 < _107600; if (_107601) goto l107602; else goto l107692; l107692: ; p_107604 = _107600; goto l107603; l107602: ; p_107604 = 255; goto l107603; l107603: ; _107604 = p_107604; threadIdx_y_107607 = threadIdx_y(); pthreadIdx_y_107607 = threadIdx_y_107607; l107605: ; threadIdx_y_107607 = pthreadIdx_y_107607; blockDim_y_107610 = blockDim_y(); pblockDim_y_107610 = blockDim_y_107610; l107608: ; blockDim_y_107610 = pblockDim_y_107610; blockIdx_y_107613 = blockIdx_y(); pblockIdx_y_107613 = blockIdx_y_107613; l107611: ; blockIdx_y_107613 = pblockIdx_y_107613; threadIdx_x_107616 = threadIdx_x(); pthreadIdx_x_107616 = threadIdx_x_107616; l107614: ; threadIdx_x_107616 = pthreadIdx_x_107616; blockDim_x_107619 = blockDim_x(); pblockDim_x_107619 = blockDim_x_107619; l107617: ; blockDim_x_107619 = pblockDim_x_107619; blockIdx_x_107622 = blockIdx_x(); pblockIdx_x_107622 = blockIdx_x_107622; l107620: ; blockIdx_x_107622 = pblockIdx_x_107622; int _107624; _107624 = blockDim_y_107610 * blockIdx_y_107613; int _107627; _107627 = blockDim_x_107619 * blockIdx_x_107622; int _107628; _107628 = threadIdx_x_107616 + _107627; unsigned char _107632; _107632 = (unsigned char)_107582; int _107625; _107625 = threadIdx_y_107607 + _107624; int _107626; _107626 = 256 * _107625; int _107629; _107629 = _107626 + _107628; int _107630; _107630 = 3 * _107629; unsigned char* _107631; _107631 = _71818_104836 + _107630; *_107631 = _107632; threadIdx_y_107636 = threadIdx_y(); pthreadIdx_y_107636 = threadIdx_y_107636; l107634: ; threadIdx_y_107636 = pthreadIdx_y_107636; blockDim_y_107639 = blockDim_y(); pblockDim_y_107639 = blockDim_y_107639; l107637: ; blockDim_y_107639 = pblockDim_y_107639; blockIdx_y_107642 = blockIdx_y(); pblockIdx_y_107642 = blockIdx_y_107642; l107640: ; blockIdx_y_107642 = pblockIdx_y_107642; threadIdx_x_107645 = threadIdx_x(); pthreadIdx_x_107645 = threadIdx_x_107645; l107643: ; threadIdx_x_107645 = pthreadIdx_x_107645; blockDim_x_107648 = blockDim_x(); pblockDim_x_107648 = blockDim_x_107648; l107646: ; blockDim_x_107648 = pblockDim_x_107648; blockIdx_x_107651 = blockIdx_x(); pblockIdx_x_107651 = blockIdx_x_107651; l107649: ; blockIdx_x_107651 = pblockIdx_x_107651; int _107652; _107652 = blockDim_y_107639 * blockIdx_y_107642; int _107655; _107655 = blockDim_x_107648 * blockIdx_x_107651; int _107656; _107656 = threadIdx_x_107645 + _107655; unsigned char _107661; _107661 = (unsigned char)_107593; int _107653; _107653 = threadIdx_y_107636 + _107652; int _107654; _107654 = 256 * _107653; int _107657; _107657 = _107654 + _107656; int _107658; _107658 = 3 * _107657; int _107659; _107659 = 1 + _107658; unsigned char* _107660; _107660 = _71818_104836 + _107659; *_107660 = _107661; threadIdx_y_107665 = threadIdx_y(); pthreadIdx_y_107665 = threadIdx_y_107665; l107663: ; threadIdx_y_107665 = pthreadIdx_y_107665; blockDim_y_107668 = blockDim_y(); pblockDim_y_107668 = blockDim_y_107668; l107666: ; blockDim_y_107668 = pblockDim_y_107668; blockIdx_y_107671 = blockIdx_y(); pblockIdx_y_107671 = blockIdx_y_107671; l107669: ; blockIdx_y_107671 = pblockIdx_y_107671; threadIdx_x_107674 = threadIdx_x(); pthreadIdx_x_107674 = threadIdx_x_107674; l107672: ; threadIdx_x_107674 = pthreadIdx_x_107674; blockDim_x_107677 = blockDim_x(); pblockDim_x_107677 = blockDim_x_107677; l107675: ; blockDim_x_107677 = pblockDim_x_107677; blockIdx_x_107680 = blockIdx_x(); pblockIdx_x_107680 = blockIdx_x_107680; l107678: ; blockIdx_x_107680 = pblockIdx_x_107680; int _107684; _107684 = blockDim_x_107677 * blockIdx_x_107680; int _107681; _107681 = blockDim_y_107668 * blockIdx_y_107671; unsigned char _107690; _107690 = (unsigned char)_107604; int _107685; _107685 = threadIdx_x_107674 + _107684; int _107682; _107682 = threadIdx_y_107665 + _107681; int _107683; _107683 = 256 * _107682; int _107686; _107686 = _107683 + _107685; int _107687; _107687 = 3 * _107686; int _107688; _107688 = 2 + _107687; unsigned char* _107689; _107689 = _71818_104836 + _107688; *_107689 = _107690; return ; l104912: ; double _104944; _104944 = (double)lower_104904; double _104945; _104945 = _104944 / 2.000000e+00; double _104946; _104946 = _104943 + _104945; double _104947; _104947 = _104946 - 1.280000e+02; double _104948; _104948 = -0.000000e+00 - _104947; double py_104949; py_104949 = _104948 / 1.280000e+02; double _104950; _104950 = py_104949 * py_104949; plower_104915 = 0; pupper_104916 = 2; pstep_104917 = 1; pr_104918 = r_104907; pg_104919 = g_104908; pb_104920 = b_104909; pstate_104921 = state_104910; goto l104913; l104913: ; lower_104915 = plower_104915; upper_104916 = pupper_104916; step_104917 = pstep_104917; r_104918 = pr_104918; g_104919 = pg_104919; b_104920 = pb_104920; state_104921 = pstate_104921; bool _104922; _104922 = lower_104915 < upper_104916; if (_104922) goto l104923; else goto l107565; l107565: ; int _107566; _107566 = lower_104904 + step_104906; plower_104904 = _107566; pupper_104905 = upper_104905; pstep_104906 = step_104906; pr_104907 = r_104918; pg_104908 = g_104919; pb_104909 = b_104920; pstate_104910 = state_104921; goto l104902; l104923: ; double _104932; _104932 = (double)lower_104915; double _104934; _104934 = _104932 / 2.000000e+00; double _104935; _104935 = _104931 + _104934; double _104937; _104937 = _104935 - 1.280000e+02; double px_104938; px_104938 = _104937 / 1.280000e+02; double _104939; _104939 = px_104938 * px_104938; double _104951; _104951 = _104939 + _104950; double _104952; _104952 = 1.000000e+00 + _104951; length_104955 = sqrt(_104952); plength_104955 = length_104955; l104953: ; length_104955 = plength_104955; _104962 = fabs(length_104955); p_104962 = _104962; l104960: ; _104962 = p_104962; bool _104964; _104964 = 1.000000e-17 < _104962; if (_104964) goto l104965; else goto l107563; l107563: ; struct_vec_9645 _107564; _107564.e0 = px_104938; _107564.e1 = py_104949; _107564.e2 = -1.000000e+00; pvnormalize_104968 = _107564; goto l104966; l104965: ; double _107561; _107561 = -1.000000e+00 / length_104955; double _107559; _107559 = px_104938 / length_104955; double _107560; _107560 = py_104949 / length_104955; struct_vec_9645 _107562; _107562.e0 = _107559; _107562.e1 = _107560; _107562.e2 = _107561; pvnormalize_104968 = _107562; goto l104966; l104966: ; vnormalize_104968 = pvnormalize_104968; double _104970; _104970 = vnormalize_104968.e0; double _104978; _104978 = vnormalize_104968.e2; double _104973; _104973 = vnormalize_104968.e1; double _104971; _104971 = 2.000000e+00 * _104970; double _104979; _104979 = 3.500000e+00 * _104978; double _104974; _104974 = 0.000000e+00 * _104973; double _104975; _104975 = _104971 + _104974; double _104980; _104980 = _104975 + _104979; double _104981; _104981 = _104980 * _104980; double D_104983; D_104983 = _104981 - 1.600000e+01; bool _104984; _104984 = 0.000000e+00 < D_104983; if (_104984) goto l104985; else goto l107558; l107558: ; goto l107555; l104985: ; _104988 = sqrt(D_104983); p_104988 = _104988; l104986: ; _104988 = p_104988; double _104989; _104989 = -0.000000e+00 - _104980; double t_104990; t_104990 = _104989 - _104988; bool _104991; _104991 = 0.000000e+00 < t_104990; if (_104991) goto l104992; else goto l107557; l107557: ; goto l107554; l104992: ; bool _104994; _104994 = t_104990 < 1.000000e+17; if (_104994) goto l104995; else goto l107553; l107553: ; goto l107554; l107554: ; goto l107555; l107555: ; struct_Isect_9647 _107049_64; _107049_64.e0 = 1.000000e+17; // bottom: _107049_64.e1 = // bottom: struct_vec_9645 _107047_68;; // bottom: _107049_64.e2 = _107047_68; _107049_64.e3 = 0; pray_sphere_intersect_105025 = _107049_64; goto l105023; l104995: ; double _104996; _104996 = _104970 * t_104990; double _105001; _105001 = _104973 * t_104990; double _105006; _105006 = _104978 * t_104990; double _104997; _104997 = 0.000000e+00 + _104996; double _105002; _105002 = 0.000000e+00 + _105001; double _105007; _105007 = 0.000000e+00 + _105006; double _104999; _104999 = _104997 - -2.000000e+00; double _105003; _105003 = _105002 - 0.000000e+00; double _105009; _105009 = _105007 - -3.500000e+00; double _105000; _105000 = _104999 * _104999; double _105004; _105004 = _105003 * _105003; double _105010; _105010 = _105009 * _105009; double _105005; _105005 = _105000 + _105004; double _105011; _105011 = _105005 + _105010; length_105014 = sqrt(_105011); plength_105014 = length_105014; l105012: ; length_105014 = plength_105014; _105017 = fabs(length_105014); p_105017 = _105017; l105015: ; _105017 = p_105017; bool _105018; _105018 = 1.000000e-17 < _105017; if (_105018) goto l105019; else goto l107551; l107551: ; struct_vec_9645 n_107552; n_107552.e0 = _104999; n_107552.e1 = _105003; n_107552.e2 = _105009; pvnormalize_105022 = n_107552; goto l105020; l105019: ; double _107548; _107548 = _105003 / length_105014; double _107547; _107547 = _104999 / length_105014; double _107549; _107549 = _105009 / length_105014; struct_vec_9645 _107550; _107550.e0 = _107547; _107550.e1 = _107548; _107550.e2 = _107549; pvnormalize_105022 = _107550; goto l105020; l105020: ; vnormalize_105022 = pvnormalize_105022; struct_vec_9645 p_107545; p_107545.e0 = _104997; p_107545.e1 = _105002; p_107545.e2 = _105007; struct_Isect_9647 isect_107546; isect_107546.e0 = t_104990; isect_107546.e1 = p_107545; isect_107546.e2 = vnormalize_105022; isect_107546.e3 = 1; pray_sphere_intersect_105025 = isect_107546; goto l105023; l105023: ; ray_sphere_intersect_105025 = pray_sphere_intersect_105025; double _105030; _105030 = 3.000000e+00 * _104978; double _105027; _105027 = 5.000000e-01 * _104970; double _105028; _105028 = _105027 + _104974; double _105031; _105031 = _105028 + _105030; double _105032; _105032 = _105031 * _105031; double D_105034; D_105034 = _105032 - 9.000000e+00; bool _105035; _105035 = 0.000000e+00 < D_105034; if (_105035) goto l105036; else goto l107544; l107544: ; goto l107541; l105036: ; _105039 = sqrt(D_105034); p_105039 = _105039; l105037: ; _105039 = p_105039; double _105040; _105040 = -0.000000e+00 - _105031; double t_105041; t_105041 = _105040 - _105039; bool _105042; _105042 = 0.000000e+00 < t_105041; if (_105042) goto l105043; else goto l107543; l107543: ; goto l107540; l105043: ; double _105044; _105044 = ray_sphere_intersect_105025.e0; bool _105045; _105045 = t_105041 < _105044; if (_105045) goto l105046; else goto l107539; l107539: ; goto l107540; l107540: ; goto l107541; l107541: ; pray_sphere_intersect_105076 = ray_sphere_intersect_105025; goto l105074; l105046: ; double _105047; _105047 = _104970 * t_105041; double _105052; _105052 = _104973 * t_105041; double _105057; _105057 = _104978 * t_105041; double _105053; _105053 = 0.000000e+00 + _105052; double _105054; _105054 = _105053 - 0.000000e+00; double _105048; _105048 = 0.000000e+00 + _105047; double _105058; _105058 = 0.000000e+00 + _105057; double _105055; _105055 = _105054 * _105054; double _105050; _105050 = _105048 - -5.000000e-01; double _105060; _105060 = _105058 - -3.000000e+00; double _105051; _105051 = _105050 * _105050; double _105061; _105061 = _105060 * _105060; double _105056; _105056 = _105051 + _105055; double _105062; _105062 = _105056 + _105061; length_105065 = sqrt(_105062); plength_105065 = length_105065; l105063: ; length_105065 = plength_105065; _105068 = fabs(length_105065); p_105068 = _105068; l105066: ; _105068 = p_105068; bool _105069; _105069 = 1.000000e-17 < _105068; if (_105069) goto l105070; else goto l107537; l107537: ; struct_vec_9645 n_107538; n_107538.e0 = _105050; n_107538.e1 = _105054; n_107538.e2 = _105060; pvnormalize_105073 = n_107538; goto l105071; l105070: ; double _107533; _107533 = _105050 / length_105065; double _107534; _107534 = _105054 / length_105065; double _107535; _107535 = _105060 / length_105065; struct_vec_9645 _107536; _107536.e0 = _107533; _107536.e1 = _107534; _107536.e2 = _107535; pvnormalize_105073 = _107536; goto l105071; l105071: ; vnormalize_105073 = pvnormalize_105073; struct_vec_9645 p_107531; p_107531.e0 = _105048; p_107531.e1 = _105053; p_107531.e2 = _105058; struct_Isect_9647 isect_107532; isect_107532.e0 = t_105041; isect_107532.e1 = p_107531; isect_107532.e2 = vnormalize_105073; isect_107532.e3 = 1; pray_sphere_intersect_105076 = isect_107532; goto l105074; l105074: ; ray_sphere_intersect_105076 = pray_sphere_intersect_105076; double _105081; _105081 = 2.200000e+00 * _104978; double _105078; _105078 = -1.000000e+00 * _104970; double _105079; _105079 = _105078 + _104974; double _105082; _105082 = _105079 + _105081; double _105083; _105083 = _105082 * _105082; double D_105085; D_105085 = _105083 - 5.590000e+00; bool _105086; _105086 = 0.000000e+00 < D_105085; if (_105086) goto l105087; else goto l107530; l107530: ; goto l107527; l105087: ; _105090 = sqrt(D_105085); p_105090 = _105090; l105088: ; _105090 = p_105090; double _105091; _105091 = -0.000000e+00 - _105082; double t_105092; t_105092 = _105091 - _105090; bool _105093; _105093 = 0.000000e+00 < t_105092; if (_105093) goto l105094; else goto l107529; l107529: ; goto l107526; l105094: ; double _105095; _105095 = ray_sphere_intersect_105076.e0; bool _105096; _105096 = t_105092 < _105095; if (_105096) goto l105097; else goto l107525; l107525: ; goto l107526; l107526: ; goto l107527; l107527: ; pray_sphere_intersect_105126 = ray_sphere_intersect_105076; goto l105124; l105097: ; double _105107; _105107 = _104978 * t_105092; double _105098; _105098 = _104970 * t_105092; double _105108; _105108 = 0.000000e+00 + _105107; double _105102; _105102 = _104973 * t_105092; double _105099; _105099 = 0.000000e+00 + _105098; double _105110; _105110 = _105108 - -2.200000e+00; double _105103; _105103 = 0.000000e+00 + _105102; double _105100; _105100 = _105099 - 1.000000e+00; double _105111; _105111 = _105110 * _105110; double _105104; _105104 = _105103 - 0.000000e+00; double _105101; _105101 = _105100 * _105100; double _105105; _105105 = _105104 * _105104; double _105106; _105106 = _105101 + _105105; double _105112; _105112 = _105106 + _105111; length_105115 = sqrt(_105112); plength_105115 = length_105115; l105113: ; length_105115 = plength_105115; _105118 = fabs(length_105115); p_105118 = _105118; l105116: ; _105118 = p_105118; bool _105119; _105119 = 1.000000e-17 < _105118; if (_105119) goto l105120; else goto l107523; l107523: ; struct_vec_9645 n_107524; n_107524.e0 = _105100; n_107524.e1 = _105104; n_107524.e2 = _105110; pvnormalize_105123 = n_107524; goto l105121; l105120: ; double _107520; _107520 = _105104 / length_105115; double _107521; _107521 = _105110 / length_105115; double _107519; _107519 = _105100 / length_105115; struct_vec_9645 _107522; _107522.e0 = _107519; _107522.e1 = _107520; _107522.e2 = _107521; pvnormalize_105123 = _107522; goto l105121; l105121: ; vnormalize_105123 = pvnormalize_105123; struct_vec_9645 p_107517; p_107517.e0 = _105099; p_107517.e1 = _105103; p_107517.e2 = _105108; struct_Isect_9647 isect_107518; isect_107518.e0 = t_105092; isect_107518.e1 = p_107517; isect_107518.e2 = vnormalize_105123; isect_107518.e3 = 1; pray_sphere_intersect_105126 = isect_107518; goto l105124; l105124: ; ray_sphere_intersect_105126 = pray_sphere_intersect_105126; double _105128; _105128 = 1.000000e+00 * _104973; double _105127; _105127 = 0.000000e+00 * _104970; double _105130; _105130 = 0.000000e+00 * _104978; double _105129; _105129 = _105127 + _105128; double _105131; _105131 = _105129 + _105130; _105134 = fabs(_105131); p_105134 = _105134; l105132: ; _105134 = p_105134; bool _105135; _105135 = 1.000000e-17 <= _105134; if (_105135) goto l105136; else goto l107516; l107516: ; goto l107513; l105136: ; double t_105137; t_105137 = -5.000000e-01 / _105131; bool _105138; _105138 = 0.000000e+00 < t_105137; if (_105138) goto l105139; else goto l107515; l107515: ; goto l107512; l105139: ; double _105140; _105140 = ray_sphere_intersect_105126.e0; bool _105141; _105141 = t_105137 < _105140; if (_105141) goto l105142; else goto l107511; l107511: ; goto l107512; l107512: ; goto l107513; l107513: ; pray_plane_intersect_105145 = ray_sphere_intersect_105126; goto l105143; l105142: ; double _107505; _107505 = _104973 * t_105137; double _107506; _107506 = 0.000000e+00 + _107505; double _107507; _107507 = _104978 * t_105137; double _107503; _107503 = _104970 * t_105137; double _107508; _107508 = 0.000000e+00 + _107507; double _107504; _107504 = 0.000000e+00 + _107503; struct_vec_9645 p_107509; p_107509.e0 = _107504; p_107509.e1 = _107506; p_107509.e2 = _107508; struct_vec_9645 _106999_162; _106999_162.e0 = 0.000000e+00; _106999_162.e1 = 1.000000e+00; _106999_162.e2 = 0.000000e+00; struct_Isect_9647 isect_107510; isect_107510.e0 = t_105137; isect_107510.e1 = p_107509; isect_107510.e2 = _106999_162; isect_107510.e3 = 1; pray_plane_intersect_105145 = isect_107510; goto l105143; l105143: ; ray_plane_intersect_105145 = pray_plane_intersect_105145; int _105147; _105147 = ray_plane_intersect_105145.e3; bool _105149; _105149 = _105147 == 1; if (_105149) goto l105150; else goto l107502; l107502: ; pr_107461 = r_104918; pg_107462 = g_104919; pb_107463 = b_104920; pstate_107464 = state_104921; goto l107459; l105150: ; struct_vec_9645 _105151; _105151 = ray_plane_intersect_105145.e2; double _105152; _105152 = _105151.e0; double _105165; _105165 = _105151.e1; double _105163; _105163 = _105151.e2; bool _105154; _105154 = _105152 < 6.000000e-01; if (_105154) goto l105155; else goto l107501; l107501: ; goto l107486; l105155: ; bool _105157; _105157 = -6.000000e-01 < _105152; if (_105157) goto l105158; else goto l107485; l107485: ; goto l107486; l107486: ; bool _107487; _107487 = _105165 < 6.000000e-01; if (_107487) goto l107488; else goto l107500; l107500: ; goto l107492; l107488: ; bool _107489; _107489 = -6.000000e-01 < _105165; if (_107489) goto l107490; else goto l107491; l107491: ; goto l107492; l107492: ; bool _107493; _107493 = _105163 < 6.000000e-01; if (_107493) goto l107494; else goto l107499; l107499: ; goto l107498; l107494: ; bool _107495; _107495 = -6.000000e-01 < _105163; if (_107495) goto l107496; else goto l107497; l107497: ; goto l107498; l107498: ; p_105160 = 1.000000e+00; p_105161 = 0.000000e+00; p_105162 = 0.000000e+00; goto l105159; l107496: ; p_105160 = 0.000000e+00; p_105161 = 0.000000e+00; p_105162 = 1.000000e+00; goto l105159; l107490: ; p_105160 = 0.000000e+00; p_105161 = 1.000000e+00; p_105162 = 0.000000e+00; goto l105159; l105158: ; p_105160 = 1.000000e+00; p_105161 = 0.000000e+00; p_105162 = 0.000000e+00; goto l105159; l105159: ; _105160 = p_105160; _105161 = p_105161; _105162 = p_105162; double _105169; _105169 = _105162 * _105152; double _105164; _105164 = _105161 * _105163; double _105174; _105174 = _105160 * _105165; double _105170; _105170 = _105160 * _105163; double _105166; _105166 = _105162 * _105165; double _105175; _105175 = _105161 * _105152; double _105171; _105171 = _105169 - _105170; double _105167; _105167 = _105164 - _105166; double _105176; _105176 = _105174 - _105175; double _105172; _105172 = _105171 * _105171; double _105168; _105168 = _105167 * _105167; double _105177; _105177 = _105176 * _105176; double _105173; _105173 = _105168 + _105172; double _105178; _105178 = _105173 + _105177; length_105181 = sqrt(_105178); plength_105181 = length_105181; l105179: ; length_105181 = plength_105181; _105184 = fabs(length_105181); p_105184 = _105184; l105182: ; _105184 = p_105184; bool _105185; _105185 = 1.000000e-17 < _105184; if (_105185) goto l105186; else goto l107483; l107483: ; struct_vec_9645 _107484; _107484.e0 = _105167; _107484.e1 = _105171; _107484.e2 = _105176; pvnormalize_105189 = _107484; goto l105187; l105186: ; double _107481; _107481 = _105176 / length_105181; double _107479; _107479 = _105167 / length_105181; double _107480; _107480 = _105171 / length_105181; struct_vec_9645 _107482; _107482.e0 = _107479; _107482.e1 = _107480; _107482.e2 = _107481; pvnormalize_105189 = _107482; goto l105187; l105187: ; vnormalize_105189 = pvnormalize_105189; double _105190; _105190 = vnormalize_105189.e2; double _105196; _105196 = vnormalize_105189.e0; double _105192; _105192 = vnormalize_105189.e1; double _105191; _105191 = _105165 * _105190; double _105198; _105198 = _105152 * _105190; double _105203; _105203 = _105165 * _105196; double _105197; _105197 = _105163 * _105196; double _105202; _105202 = _105152 * _105192; double _105193; _105193 = _105163 * _105192; double _105194; _105194 = _105191 - _105193; double _105199; _105199 = _105197 - _105198; double _105204; _105204 = _105202 - _105203; double _105195; _105195 = _105194 * _105194; double _105200; _105200 = _105199 * _105199; double _105205; _105205 = _105204 * _105204; double _105201; _105201 = _105195 + _105200; double _105206; _105206 = _105201 + _105205; length_105209 = sqrt(_105206); plength_105209 = length_105209; l105207: ; length_105209 = plength_105209; _105212 = fabs(length_105209); p_105212 = _105212; l105210: ; _105212 = p_105212; bool _105213; _105213 = 1.000000e-17 < _105212; if (_105213) goto l105214; else goto l107477; l107477: ; struct_vec_9645 _107478; _107478.e0 = _105194; _107478.e1 = _105199; _107478.e2 = _105204; pvnormalize_105217 = _107478; goto l105215; l105214: ; double _107475; _107475 = _105204 / length_105209; double _107473; _107473 = _105194 / length_105209; double _107474; _107474 = _105199 / length_105209; struct_vec_9645 _107476; _107476.e0 = _107473; _107476.e1 = _107474; _107476.e2 = _107475; pvnormalize_105217 = _107476; goto l105215; l105215: ; vnormalize_105217 = pvnormalize_105217; double _105299; _105299 = 1.000000e-04 * _105163; struct_vec_9645 _105271; _105271 = ray_plane_intersect_105145.e1; double _105298; _105298 = _105271.e2; double _105274; _105274 = 1.000000e-04 * _105152; double _105300; _105300 = _105298 + _105299; double _105303; _105303 = vnormalize_105217.e2; double _105291; _105291 = vnormalize_105217.e1; double _105272; _105272 = _105271.e0; double _105286; _105286 = _105271.e1; double _105414; _105414 = _105300 - -2.200000e+00; double _105361; _105361 = _105300 - -3.000000e+00; double _105280; _105280 = vnormalize_105217.e0; double _105287; _105287 = 1.000000e-04 * _105165; double _105275; _105275 = _105272 + _105274; double _105477; _105477 = 0.000000e+00 * _105300; double _105301; _105301 = _105300 - -3.500000e+00; double _105288; _105288 = _105286 + _105287; double _105420; _105420 = _105414 * _105414; double _105367; _105367 = _105361 * _105361; double _105358; _105358 = _105275 - -5.000000e-01; double _105276; _105276 = _105275 - -2.000000e+00; double _105474; _105474 = 0.000000e+00 * _105275; double _105411; _105411 = _105275 - 1.000000e+00; double _105314; _105314 = _105301 * _105301; double _105475; _105475 = 1.000000e+00 * _105288; double _105289; _105289 = _105288 - 0.000000e+00; double _105365; _105365 = _105358 * _105358; double _105311; _105311 = _105276 * _105276; double _105476; _105476 = _105474 + _105475; double _105418; _105418 = _105411 * _105411; double _105312; _105312 = _105289 * _105289; double _105366; _105366 = _105365 + _105312; double _105313; _105313 = _105311 + _105312; double _105478; _105478 = _105476 + _105477; double _105419; _105419 = _105418 + _105312; double _105368; _105368 = _105366 + _105367; double _105315; _105315 = _105313 + _105314; double _105479; _105479 = 5.000000e-01 + _105478; double _105421; _105421 = _105419 + _105420; double C_105369; C_105369 = _105368 - 2.500000e-01; double C_105317; C_105317 = _105315 - 2.500000e-01; double _105480; _105480 = -0.000000e+00 - _105479; double C_105422; C_105422 = _105421 - 2.500000e-01; plower_105220 = 0; pupper_105221 = 8; pstep_105222 = 1; pocclusion_105223 = 0.000000e+00; pstate_105224 = state_104921; goto l105218; l105218: ; lower_105220 = plower_105220; upper_105221 = pupper_105221; step_105222 = pstep_105222; occlusion_105223 = pocclusion_105223; state_105224 = pstate_105224; bool _105225; _105225 = lower_105220 < upper_105221; if (_105225) goto l105226; else goto l107458; l107458: ; double _107467; _107467 = 6.400000e+01 - occlusion_105223; double _107468; _107468 = _107467 / 6.400000e+01; double _107469; _107469 = r_104918 + _107468; double _107471; _107471 = b_104920 + _107468; double _107470; _107470 = g_104919 + _107468; pr_107461 = _107469; pg_107462 = _107470; pb_107463 = _107471; pstate_107464 = state_105224; goto l107459; l107459: ; r_107461 = pr_107461; g_107462 = pg_107462; b_107463 = pb_107463; state_107464 = pstate_107464; int _107465; _107465 = lower_104915 + step_104917; plower_104915 = _107465; pupper_104916 = upper_104916; pstep_104917 = step_104917; pr_104918 = r_107461; pg_104919 = g_107462; pb_104920 = b_107463; pstate_104921 = state_107464; goto l104913; l105226: ; unsigned long hi_105232; hi_105232 = state_105224 >> 32; unsigned long lo_105229; lo_105229 = 4294967295 & state_105224; unsigned int _105230; _105230 = (unsigned int)lo_105229; unsigned int _105233; _105233 = (unsigned int)hi_105232; unsigned int _105234; _105234 = _105230 ^ _105233; double _105235; _105235 = (double)_105234; double _105236; _105236 = 2.328306e-10 * _105235; theta_105239 = sqrt(_105236); ptheta_105239 = theta_105239; l105237: ; theta_105239 = ptheta_105239; unsigned long _105246; _105246 = 4294883355 * lo_105229; unsigned long _105247; _105247 = _105246 + hi_105232; unsigned long lo_105248; lo_105248 = 4294967295 & _105247; unsigned long hi_105250; hi_105250 = _105247 >> 32; unsigned int _105249; _105249 = (unsigned int)lo_105248; unsigned int _105251; _105251 = (unsigned int)hi_105250; unsigned int _105252; _105252 = _105249 ^ _105251; double _105253; _105253 = (double)_105252; double _105254; _105254 = 2.328306e-10 * _105253; double phi_105255; phi_105255 = 6.283185e+00 * _105254; _105258 = cos(phi_105255); p_105258 = _105258; l105256: ; _105258 = p_105258; _105265 = sin(phi_105255); p_105265 = _105265; l105263: ; _105265 = p_105265; double _105266; _105266 = theta_105239 * theta_105239; double _105267; _105267 = 1.000000e+00 - _105266; z_105270 = sqrt(_105267); pz_105270 = z_105270; l105268: ; z_105270 = pz_105270; double _105294; _105294 = z_105270 * _105165; double _105283; _105283 = z_105270 * _105152; double y_105279; y_105279 = _105265 * theta_105239; double _105292; _105292 = y_105279 * _105291; double _105281; _105281 = y_105279 * _105280; double x_105277; x_105277 = _105258 * theta_105239; double _105306; _105306 = z_105270 * _105163; double _105304; _105304 = y_105279 * _105303; double _105278; _105278 = x_105277 * _105196; double _105290; _105290 = x_105277 * _105192; double _105293; _105293 = _105290 + _105292; double _105282; _105282 = _105278 + _105281; double _105302; _105302 = x_105277 * _105190; double _105305; _105305 = _105302 + _105304; double ry_105295; ry_105295 = _105293 + _105294; double rx_105284; rx_105284 = _105282 + _105283; double rz_105307; rz_105307 = _105305 + _105306; double _105296; _105296 = _105289 * ry_105295; double _105285; _105285 = _105276 * rx_105284; double _105308; _105308 = _105301 * rz_105307; double _105297; _105297 = _105285 + _105296; double _105309; _105309 = _105297 + _105308; double _105310; _105310 = _105309 * _105309; double D_105318; D_105318 = _105310 - C_105317; bool _105319; _105319 = 0.000000e+00 < D_105318; if (_105319) goto l105320; else goto l107457; l107457: ; goto l107454; l105320: ; _105323 = sqrt(D_105318); p_105323 = _105323; l105321: ; _105323 = p_105323; double _105324; _105324 = -0.000000e+00 - _105309; double t_105325; t_105325 = _105324 - _105323; bool _105326; _105326 = 0.000000e+00 < t_105325; if (_105326) goto l105327; else goto l107456; l107456: ; goto l107453; l105327: ; bool _105328; _105328 = t_105325 < 1.000000e+17; if (_105328) goto l105329; else goto l107452; l107452: ; goto l107453; l107453: ; goto l107454; l107454: ; struct_Isect_9647 _107049_259; _107049_259.e0 = 1.000000e+17; // bottom: _107049_259.e1 = // bottom: struct_vec_9645 _107047_263;; // bottom: _107049_259.e2 = _107047_263; _107049_259.e3 = 0; pray_sphere_intersect_105357 = _107049_259; goto l105355; l105329: ; double _105334; _105334 = ry_105295 * t_105325; double _105339; _105339 = rz_105307 * t_105325; double _105330; _105330 = rx_105284 * t_105325; double _105335; _105335 = _105288 + _105334; double _105340; _105340 = _105300 + _105339; double _105331; _105331 = _105275 + _105330; double _105336; _105336 = _105335 - 0.000000e+00; double _105341; _105341 = _105340 - -3.500000e+00; double _105332; _105332 = _105331 - -2.000000e+00; double _105337; _105337 = _105336 * _105336; double _105342; _105342 = _105341 * _105341; double _105333; _105333 = _105332 * _105332; double _105338; _105338 = _105333 + _105337; double _105343; _105343 = _105338 + _105342; length_105346 = sqrt(_105343); plength_105346 = length_105346; l105344: ; length_105346 = plength_105346; _105349 = fabs(length_105346); p_105349 = _105349; l105347: ; _105349 = p_105349; bool _105350; _105350 = 1.000000e-17 < _105349; if (_105350) goto l105351; else goto l107450; l107450: ; struct_vec_9645 n_107451; n_107451.e0 = _105332; n_107451.e1 = _105336; n_107451.e2 = _105341; pvnormalize_105354 = n_107451; goto l105352; l105351: ; double _107448; _107448 = _105341 / length_105346; double _107447; _107447 = _105336 / length_105346; double _107446; _107446 = _105332 / length_105346; struct_vec_9645 _107449; _107449.e0 = _107446; _107449.e1 = _107447; _107449.e2 = _107448; pvnormalize_105354 = _107449; goto l105352; l105352: ; vnormalize_105354 = pvnormalize_105354; struct_vec_9645 p_107444; p_107444.e0 = _105331; p_107444.e1 = _105335; p_107444.e2 = _105340; struct_Isect_9647 isect_107445; isect_107445.e0 = t_105325; isect_107445.e1 = p_107444; isect_107445.e2 = vnormalize_105354; isect_107445.e3 = 1; pray_sphere_intersect_105357 = isect_107445; goto l105355; l105355: ; ray_sphere_intersect_105357 = pray_sphere_intersect_105357; double _105359; _105359 = _105358 * rx_105284; double _105360; _105360 = _105359 + _105296; double _105362; _105362 = _105361 * rz_105307; double _105363; _105363 = _105360 + _105362; double _105364; _105364 = _105363 * _105363; double D_105370; D_105370 = _105364 - C_105369; bool _105371; _105371 = 0.000000e+00 < D_105370; if (_105371) goto l105372; else goto l107443; l107443: ; goto l107440; l105372: ; _105375 = sqrt(D_105370); p_105375 = _105375; l105373: ; _105375 = p_105375; double _105376; _105376 = -0.000000e+00 - _105363; double t_105377; t_105377 = _105376 - _105375; bool _105378; _105378 = 0.000000e+00 < t_105377; if (_105378) goto l105379; else goto l107442; l107442: ; goto l107439; l105379: ; double _105380; _105380 = ray_sphere_intersect_105357.e0; bool _105381; _105381 = t_105377 < _105380; if (_105381) goto l105382; else goto l107438; l107438: ; goto l107439; l107439: ; goto l107440; l107440: ; pray_sphere_intersect_105410 = ray_sphere_intersect_105357; goto l105408; l105382: ; double _105383; _105383 = rx_105284 * t_105377; double _105387; _105387 = ry_105295 * t_105377; double _105384; _105384 = _105275 + _105383; double _105392; _105392 = rz_105307 * t_105377; double _105388; _105388 = _105288 + _105387; double _105385; _105385 = _105384 - -5.000000e-01; double _105393; _105393 = _105300 + _105392; double _105389; _105389 = _105388 - 0.000000e+00; double _105386; _105386 = _105385 * _105385; double _105394; _105394 = _105393 - -3.000000e+00; double _105390; _105390 = _105389 * _105389; double _105391; _105391 = _105386 + _105390; double _105395; _105395 = _105394 * _105394; double _105396; _105396 = _105391 + _105395; length_105399 = sqrt(_105396); plength_105399 = length_105399; l105397: ; length_105399 = plength_105399; _105402 = fabs(length_105399); p_105402 = _105402; l105400: ; _105402 = p_105402; bool _105403; _105403 = 1.000000e-17 < _105402; if (_105403) goto l105404; else goto l107436; l107436: ; struct_vec_9645 n_107437; n_107437.e0 = _105385; n_107437.e1 = _105389; n_107437.e2 = _105394; pvnormalize_105407 = n_107437; goto l105405; l105404: ; double _107434; _107434 = _105394 / length_105399; double _107433; _107433 = _105389 / length_105399; double _107432; _107432 = _105385 / length_105399; struct_vec_9645 _107435; _107435.e0 = _107432; _107435.e1 = _107433; _107435.e2 = _107434; pvnormalize_105407 = _107435; goto l105405; l105405: ; vnormalize_105407 = pvnormalize_105407; struct_vec_9645 p_107430; p_107430.e0 = _105384; p_107430.e1 = _105388; p_107430.e2 = _105393; struct_Isect_9647 isect_107431; isect_107431.e0 = t_105377; isect_107431.e1 = p_107430; isect_107431.e2 = vnormalize_105407; isect_107431.e3 = 1; pray_sphere_intersect_105410 = isect_107431; goto l105408; l105408: ; ray_sphere_intersect_105410 = pray_sphere_intersect_105410; double _105412; _105412 = _105411 * rx_105284; double _105415; _105415 = _105414 * rz_105307; double _105413; _105413 = _105412 + _105296; double _105416; _105416 = _105413 + _105415; double _105417; _105417 = _105416 * _105416; double D_105423; D_105423 = _105417 - C_105422; bool _105424; _105424 = 0.000000e+00 < D_105423; if (_105424) goto l105425; else goto l107429; l107429: ; goto l107426; l105425: ; _105428 = sqrt(D_105423); p_105428 = _105428; l105426: ; _105428 = p_105428; double _105429; _105429 = -0.000000e+00 - _105416; double t_105430; t_105430 = _105429 - _105428; bool _105431; _105431 = 0.000000e+00 < t_105430; if (_105431) goto l105432; else goto l107428; l107428: ; goto l107425; l105432: ; double _105433; _105433 = ray_sphere_intersect_105410.e0; bool _105434; _105434 = t_105430 < _105433; if (_105434) goto l105435; else goto l107424; l107424: ; goto l107425; l107425: ; goto l107426; l107426: ; pray_sphere_intersect_105463 = ray_sphere_intersect_105410; goto l105461; l105435: ; double _105436; _105436 = rx_105284 * t_105430; double _105445; _105445 = rz_105307 * t_105430; double _105440; _105440 = ry_105295 * t_105430; double _105437; _105437 = _105275 + _105436; double _105438; _105438 = _105437 - 1.000000e+00; double _105446; _105446 = _105300 + _105445; double _105441; _105441 = _105288 + _105440; double _105439; _105439 = _105438 * _105438; double _105447; _105447 = _105446 - -2.200000e+00; double _105442; _105442 = _105441 - 0.000000e+00; double _105448; _105448 = _105447 * _105447; double _105443; _105443 = _105442 * _105442; double _105444; _105444 = _105439 + _105443; double _105449; _105449 = _105444 + _105448; length_105452 = sqrt(_105449); plength_105452 = length_105452; l105450: ; length_105452 = plength_105452; _105455 = fabs(length_105452); p_105455 = _105455; l105453: ; _105455 = p_105455; bool _105456; _105456 = 1.000000e-17 < _105455; if (_105456) goto l105457; else goto l107422; l107422: ; struct_vec_9645 n_107423; n_107423.e0 = _105438; n_107423.e1 = _105442; n_107423.e2 = _105447; pvnormalize_105460 = n_107423; goto l105458; l105457: ; double _107418; _107418 = _105438 / length_105452; double _107419; _107419 = _105442 / length_105452; double _107420; _107420 = _105447 / length_105452; struct_vec_9645 _107421; _107421.e0 = _107418; _107421.e1 = _107419; _107421.e2 = _107420; pvnormalize_105460 = _107421; goto l105458; l105458: ; vnormalize_105460 = pvnormalize_105460; struct_vec_9645 p_107416; p_107416.e0 = _105437; p_107416.e1 = _105441; p_107416.e2 = _105446; struct_Isect_9647 isect_107417; isect_107417.e0 = t_105430; isect_107417.e1 = p_107416; isect_107417.e2 = vnormalize_105460; isect_107417.e3 = 1; pray_sphere_intersect_105463 = isect_107417; goto l105461; l105461: ; ray_sphere_intersect_105463 = pray_sphere_intersect_105463; double _105464; _105464 = 0.000000e+00 * rx_105284; double _105465; _105465 = 1.000000e+00 * ry_105295; double _105467; _105467 = 0.000000e+00 * rz_105307; double _105466; _105466 = _105464 + _105465; double _105468; _105468 = _105466 + _105467; _105471 = fabs(_105468); p_105471 = _105471; l105469: ; _105471 = p_105471; bool _105472; _105472 = 1.000000e-17 <= _105471; if (_105472) goto l105473; else goto l107415; l107415: ; goto l107412; l105473: ; double t_105481; t_105481 = _105480 / _105468; bool _105482; _105482 = 0.000000e+00 < t_105481; if (_105482) goto l105483; else goto l107414; l107414: ; goto l107411; l105483: ; double _105484; _105484 = ray_sphere_intersect_105463.e0; bool _105485; _105485 = t_105481 < _105484; if (_105485) goto l105486; else goto l107410; l107410: ; goto l107411; l107411: ; goto l107412; l107412: ; pray_plane_intersect_105489 = ray_sphere_intersect_105463; goto l105487; l105486: ; double _107406; _107406 = rz_105307 * t_105481; double _107407; _107407 = _105300 + _107406; double _107402; _107402 = rx_105284 * t_105481; double _107403; _107403 = _105275 + _107402; double _107404; _107404 = ry_105295 * t_105481; double _107405; _107405 = _105288 + _107404; struct_vec_9645 p_107408; p_107408.e0 = _107403; p_107408.e1 = _107405; p_107408.e2 = _107407; struct_vec_9645 _106999_338; _106999_338.e0 = 0.000000e+00; _106999_338.e1 = 1.000000e+00; _106999_338.e2 = 0.000000e+00; struct_Isect_9647 isect_107409; isect_107409.e0 = t_105481; isect_107409.e1 = p_107408; isect_107409.e2 = _106999_338; isect_107409.e3 = 1; pray_plane_intersect_105489 = isect_107409; goto l105487; l105487: ; ray_plane_intersect_105489 = pray_plane_intersect_105489; int _105490; _105490 = ray_plane_intersect_105489.e3; bool _105491; _105491 = _105490 == 1; if (_105491) goto l105492; else goto l107401; l107401: ; pocclusion_105495 = occlusion_105223; goto l105493; l105492: ; double _107400; _107400 = 1.000000e+00 + occlusion_105223; pocclusion_105495 = _107400; goto l105493; l105493: ; occlusion_105495 = pocclusion_105495; unsigned long _105496; _105496 = 4294883355 * lo_105248; unsigned long _105497; _105497 = _105496 + hi_105250; unsigned long lo_105498; lo_105498 = 4294967295 & _105497; unsigned long hi_105500; hi_105500 = _105497 >> 32; unsigned int _105499; _105499 = (unsigned int)lo_105498; unsigned int _105501; _105501 = (unsigned int)hi_105500; unsigned int _105502; _105502 = _105499 ^ _105501; double _105503; _105503 = (double)_105502; double _105504; _105504 = 2.328306e-10 * _105503; theta_105507 = sqrt(_105504); ptheta_105507 = theta_105507; l105505: ; theta_105507 = ptheta_105507; unsigned long _105508; _105508 = 4294883355 * lo_105498; unsigned long _105509; _105509 = _105508 + hi_105500; unsigned long lo_105510; lo_105510 = 4294967295 & _105509; unsigned long hi_105512; hi_105512 = _105509 >> 32; unsigned int _105511; _105511 = (unsigned int)lo_105510; unsigned int _105513; _105513 = (unsigned int)hi_105512; unsigned int _105514; _105514 = _105511 ^ _105513; double _105515; _105515 = (double)_105514; double _105516; _105516 = 2.328306e-10 * _105515; double phi_105517; phi_105517 = 6.283185e+00 * _105516; _105520 = cos(phi_105517); p_105520 = _105520; l105518: ; _105520 = p_105520; _105523 = sin(phi_105517); p_105523 = _105523; l105521: ; _105523 = p_105523; double _105524; _105524 = theta_105507 * theta_105507; double _105525; _105525 = 1.000000e+00 - _105524; z_105528 = sqrt(_105525); pz_105528 = z_105528; l105526: ; z_105528 = pz_105528; double _105540; _105540 = z_105528 * _105165; double _105547; _105547 = z_105528 * _105163; double x_105529; x_105529 = _105520 * theta_105507; double y_105531; y_105531 = _105523 * theta_105507; double _105530; _105530 = x_105529 * _105196; double _105537; _105537 = x_105529 * _105192; double _105538; _105538 = y_105531 * _105291; double _105534; _105534 = z_105528 * _105152; double _105532; _105532 = y_105531 * _105280; double _105544; _105544 = x_105529 * _105190; double _105545; _105545 = y_105531 * _105303; double _105533; _105533 = _105530 + _105532; double _105539; _105539 = _105537 + _105538; double rx_105535; rx_105535 = _105533 + _105534; double _105546; _105546 = _105544 + _105545; double ry_105541; ry_105541 = _105539 + _105540; double _105536; _105536 = _105276 * rx_105535; double rz_105548; rz_105548 = _105546 + _105547; double _105542; _105542 = _105289 * ry_105541; double _105543; _105543 = _105536 + _105542; double _105549; _105549 = _105301 * rz_105548; double _105550; _105550 = _105543 + _105549; double _105551; _105551 = _105550 * _105550; double D_105552; D_105552 = _105551 - C_105317; bool _105553; _105553 = 0.000000e+00 < D_105552; if (_105553) goto l105554; else goto l107399; l107399: ; goto l107396; l105554: ; _105557 = sqrt(D_105552); p_105557 = _105557; l105555: ; _105557 = p_105557; double _105558; _105558 = -0.000000e+00 - _105550; double t_105559; t_105559 = _105558 - _105557; bool _105560; _105560 = 0.000000e+00 < t_105559; if (_105560) goto l105561; else goto l107398; l107398: ; goto l107395; l105561: ; bool _105562; _105562 = t_105559 < 1.000000e+17; if (_105562) goto l105563; else goto l107394; l107394: ; goto l107395; l107395: ; goto l107396; l107396: ; struct_Isect_9647 _107049_367; _107049_367.e0 = 1.000000e+17; // bottom: _107049_367.e1 = // bottom: struct_vec_9645 _107047_371;; // bottom: _107049_367.e2 = _107047_371; _107049_367.e3 = 0; pray_sphere_intersect_105591 = _107049_367; goto l105589; l105563: ; double _105573; _105573 = rz_105548 * t_105559; double _105564; _105564 = rx_105535 * t_105559; double _105568; _105568 = ry_105541 * t_105559; double _105569; _105569 = _105288 + _105568; double _105574; _105574 = _105300 + _105573; double _105565; _105565 = _105275 + _105564; double _105570; _105570 = _105569 - 0.000000e+00; double _105575; _105575 = _105574 - -3.500000e+00; double _105566; _105566 = _105565 - -2.000000e+00; double _105571; _105571 = _105570 * _105570; double _105576; _105576 = _105575 * _105575; double _105567; _105567 = _105566 * _105566; double _105572; _105572 = _105567 + _105571; double _105577; _105577 = _105572 + _105576; length_105580 = sqrt(_105577); plength_105580 = length_105580; l105578: ; length_105580 = plength_105580; _105583 = fabs(length_105580); p_105583 = _105583; l105581: ; _105583 = p_105583; bool _105584; _105584 = 1.000000e-17 < _105583; if (_105584) goto l105585; else goto l107392; l107392: ; struct_vec_9645 n_107393; n_107393.e0 = _105566; n_107393.e1 = _105570; n_107393.e2 = _105575; pvnormalize_105588 = n_107393; goto l105586; l105585: ; double _107389; _107389 = _105570 / length_105580; double _107388; _107388 = _105566 / length_105580; double _107390; _107390 = _105575 / length_105580; struct_vec_9645 _107391; _107391.e0 = _107388; _107391.e1 = _107389; _107391.e2 = _107390; pvnormalize_105588 = _107391; goto l105586; l105586: ; vnormalize_105588 = pvnormalize_105588; struct_vec_9645 p_107386; p_107386.e0 = _105565; p_107386.e1 = _105569; p_107386.e2 = _105574; struct_Isect_9647 isect_107387; isect_107387.e0 = t_105559; isect_107387.e1 = p_107386; isect_107387.e2 = vnormalize_105588; isect_107387.e3 = 1; pray_sphere_intersect_105591 = isect_107387; goto l105589; l105589: ; ray_sphere_intersect_105591 = pray_sphere_intersect_105591; double _105592; _105592 = _105358 * rx_105535; double _105594; _105594 = _105361 * rz_105548; double _105593; _105593 = _105592 + _105542; double _105595; _105595 = _105593 + _105594; double _105596; _105596 = _105595 * _105595; double D_105597; D_105597 = _105596 - C_105369; bool _105598; _105598 = 0.000000e+00 < D_105597; if (_105598) goto l105599; else goto l107385; l107385: ; goto l107382; l105599: ; _105602 = sqrt(D_105597); p_105602 = _105602; l105600: ; _105602 = p_105602; double _105603; _105603 = -0.000000e+00 - _105595; double t_105604; t_105604 = _105603 - _105602; bool _105605; _105605 = 0.000000e+00 < t_105604; if (_105605) goto l105606; else goto l107384; l107384: ; goto l107381; l105606: ; double _105607; _105607 = ray_sphere_intersect_105591.e0; bool _105608; _105608 = t_105604 < _105607; if (_105608) goto l105609; else goto l107380; l107380: ; goto l107381; l107381: ; goto l107382; l107382: ; pray_sphere_intersect_105637 = ray_sphere_intersect_105591; goto l105635; l105609: ; double _105614; _105614 = ry_105541 * t_105604; double _105619; _105619 = rz_105548 * t_105604; double _105615; _105615 = _105288 + _105614; double _105610; _105610 = rx_105535 * t_105604; double _105611; _105611 = _105275 + _105610; double _105620; _105620 = _105300 + _105619; double _105616; _105616 = _105615 - 0.000000e+00; double _105612; _105612 = _105611 - -5.000000e-01; double _105621; _105621 = _105620 - -3.000000e+00; double _105617; _105617 = _105616 * _105616; double _105613; _105613 = _105612 * _105612; double _105622; _105622 = _105621 * _105621; double _105618; _105618 = _105613 + _105617; double _105623; _105623 = _105618 + _105622; length_105626 = sqrt(_105623); plength_105626 = length_105626; l105624: ; length_105626 = plength_105626; _105629 = fabs(length_105626); p_105629 = _105629; l105627: ; _105629 = p_105629; bool _105630; _105630 = 1.000000e-17 < _105629; if (_105630) goto l105631; else goto l107378; l107378: ; struct_vec_9645 n_107379; n_107379.e0 = _105612; n_107379.e1 = _105616; n_107379.e2 = _105621; pvnormalize_105634 = n_107379; goto l105632; l105631: ; double _107375; _107375 = _105616 / length_105626; double _107374; _107374 = _105612 / length_105626; double _107376; _107376 = _105621 / length_105626; struct_vec_9645 _107377; _107377.e0 = _107374; _107377.e1 = _107375; _107377.e2 = _107376; pvnormalize_105634 = _107377; goto l105632; l105632: ; vnormalize_105634 = pvnormalize_105634; struct_vec_9645 p_107372; p_107372.e0 = _105611; p_107372.e1 = _105615; p_107372.e2 = _105620; struct_Isect_9647 isect_107373; isect_107373.e0 = t_105604; isect_107373.e1 = p_107372; isect_107373.e2 = vnormalize_105634; isect_107373.e3 = 1; pray_sphere_intersect_105637 = isect_107373; goto l105635; l105635: ; ray_sphere_intersect_105637 = pray_sphere_intersect_105637; double _105638; _105638 = _105411 * rx_105535; double _105640; _105640 = _105414 * rz_105548; double _105639; _105639 = _105638 + _105542; double _105641; _105641 = _105639 + _105640; double _105642; _105642 = _105641 * _105641; double D_105643; D_105643 = _105642 - C_105422; bool _105644; _105644 = 0.000000e+00 < D_105643; if (_105644) goto l105645; else goto l107371; l107371: ; goto l107368; l105645: ; _105648 = sqrt(D_105643); p_105648 = _105648; l105646: ; _105648 = p_105648; double _105649; _105649 = -0.000000e+00 - _105641; double t_105650; t_105650 = _105649 - _105648; bool _105651; _105651 = 0.000000e+00 < t_105650; if (_105651) goto l105652; else goto l107370; l107370: ; goto l107367; l105652: ; double _105653; _105653 = ray_sphere_intersect_105637.e0; bool _105654; _105654 = t_105650 < _105653; if (_105654) goto l105655; else goto l107366; l107366: ; goto l107367; l107367: ; goto l107368; l107368: ; pray_sphere_intersect_105683 = ray_sphere_intersect_105637; goto l105681; l105655: ; double _105660; _105660 = ry_105541 * t_105650; double _105661; _105661 = _105288 + _105660; double _105665; _105665 = rz_105548 * t_105650; double _105656; _105656 = rx_105535 * t_105650; double _105657; _105657 = _105275 + _105656; double _105662; _105662 = _105661 - 0.000000e+00; double _105666; _105666 = _105300 + _105665; double _105658; _105658 = _105657 - 1.000000e+00; double _105663; _105663 = _105662 * _105662; double _105667; _105667 = _105666 - -2.200000e+00; double _105659; _105659 = _105658 * _105658; double _105664; _105664 = _105659 + _105663; double _105668; _105668 = _105667 * _105667; double _105669; _105669 = _105664 + _105668; length_105672 = sqrt(_105669); plength_105672 = length_105672; l105670: ; length_105672 = plength_105672; _105675 = fabs(length_105672); p_105675 = _105675; l105673: ; _105675 = p_105675; bool _105676; _105676 = 1.000000e-17 < _105675; if (_105676) goto l105677; else goto l107364; l107364: ; struct_vec_9645 n_107365; n_107365.e0 = _105658; n_107365.e1 = _105662; n_107365.e2 = _105667; pvnormalize_105680 = n_107365; goto l105678; l105677: ; double _107360; _107360 = _105658 / length_105672; double _107362; _107362 = _105667 / length_105672; double _107361; _107361 = _105662 / length_105672; struct_vec_9645 _107363; _107363.e0 = _107360; _107363.e1 = _107361; _107363.e2 = _107362; pvnormalize_105680 = _107363; goto l105678; l105678: ; vnormalize_105680 = pvnormalize_105680; struct_vec_9645 p_107358; p_107358.e0 = _105657; p_107358.e1 = _105661; p_107358.e2 = _105666; struct_Isect_9647 isect_107359; isect_107359.e0 = t_105650; isect_107359.e1 = p_107358; isect_107359.e2 = vnormalize_105680; isect_107359.e3 = 1; pray_sphere_intersect_105683 = isect_107359; goto l105681; l105681: ; ray_sphere_intersect_105683 = pray_sphere_intersect_105683; double _105687; _105687 = 0.000000e+00 * rz_105548; double _105684; _105684 = 0.000000e+00 * rx_105535; double _105685; _105685 = 1.000000e+00 * ry_105541; double _105686; _105686 = _105684 + _105685; double _105688; _105688 = _105686 + _105687; _105691 = fabs(_105688); p_105691 = _105691; l105689: ; _105691 = p_105691; bool _105692; _105692 = 1.000000e-17 <= _105691; if (_105692) goto l105693; else goto l107357; l107357: ; goto l107354; l105693: ; double t_105694; t_105694 = _105480 / _105688; bool _105695; _105695 = 0.000000e+00 < t_105694; if (_105695) goto l105696; else goto l107356; l107356: ; goto l107353; l105696: ; double _105697; _105697 = ray_sphere_intersect_105683.e0; bool _105698; _105698 = t_105694 < _105697; if (_105698) goto l105699; else goto l107352; l107352: ; goto l107353; l107353: ; goto l107354; l107354: ; pray_plane_intersect_105702 = ray_sphere_intersect_105683; goto l105700; l105699: ; double _107348; _107348 = rz_105548 * t_105694; double _107349; _107349 = _105300 + _107348; double _107346; _107346 = ry_105541 * t_105694; double _107344; _107344 = rx_105535 * t_105694; double _107345; _107345 = _105275 + _107344; double _107347; _107347 = _105288 + _107346; struct_vec_9645 p_107350; p_107350.e0 = _107345; p_107350.e1 = _107347; p_107350.e2 = _107349; struct_vec_9645 _106999_446; _106999_446.e0 = 0.000000e+00; _106999_446.e1 = 1.000000e+00; _106999_446.e2 = 0.000000e+00; struct_Isect_9647 isect_107351; isect_107351.e0 = t_105694; isect_107351.e1 = p_107350; isect_107351.e2 = _106999_446; isect_107351.e3 = 1; pray_plane_intersect_105702 = isect_107351; goto l105700; l105700: ; ray_plane_intersect_105702 = pray_plane_intersect_105702; int _105703; _105703 = ray_plane_intersect_105702.e3; bool _105704; _105704 = _105703 == 1; if (_105704) goto l105705; else goto l107343; l107343: ; pocclusion_105708 = occlusion_105495; goto l105706; l105705: ; double _107342; _107342 = 1.000000e+00 + occlusion_105495; pocclusion_105708 = _107342; goto l105706; l105706: ; occlusion_105708 = pocclusion_105708; unsigned long _105709; _105709 = 4294883355 * lo_105510; unsigned long _105710; _105710 = _105709 + hi_105512; unsigned long lo_105711; lo_105711 = 4294967295 & _105710; unsigned long hi_105713; hi_105713 = _105710 >> 32; unsigned int _105712; _105712 = (unsigned int)lo_105711; unsigned int _105714; _105714 = (unsigned int)hi_105713; unsigned int _105715; _105715 = _105712 ^ _105714; double _105716; _105716 = (double)_105715; double _105717; _105717 = 2.328306e-10 * _105716; theta_105720 = sqrt(_105717); ptheta_105720 = theta_105720; l105718: ; theta_105720 = ptheta_105720; unsigned long _105721; _105721 = 4294883355 * lo_105711; unsigned long _105722; _105722 = _105721 + hi_105713; unsigned long lo_105723; lo_105723 = 4294967295 & _105722; unsigned long hi_105725; hi_105725 = _105722 >> 32; unsigned int _105724; _105724 = (unsigned int)lo_105723; unsigned int _105726; _105726 = (unsigned int)hi_105725; unsigned int _105727; _105727 = _105724 ^ _105726; double _105728; _105728 = (double)_105727; double _105729; _105729 = 2.328306e-10 * _105728; double phi_105730; phi_105730 = 6.283185e+00 * _105729; _105733 = cos(phi_105730); p_105733 = _105733; l105731: ; _105733 = p_105733; _105736 = sin(phi_105730); p_105736 = _105736; l105734: ; _105736 = p_105736; double _105737; _105737 = theta_105720 * theta_105720; double _105738; _105738 = 1.000000e+00 - _105737; z_105741 = sqrt(_105738); pz_105741 = z_105741; l105739: ; z_105741 = pz_105741; double _105760; _105760 = z_105741 * _105163; double _105747; _105747 = z_105741 * _105152; double _105753; _105753 = z_105741 * _105165; double x_105742; x_105742 = _105733 * theta_105720; double y_105744; y_105744 = _105736 * theta_105720; double _105757; _105757 = x_105742 * _105190; double _105743; _105743 = x_105742 * _105196; double _105750; _105750 = x_105742 * _105192; double _105758; _105758 = y_105744 * _105303; double _105745; _105745 = y_105744 * _105280; double _105751; _105751 = y_105744 * _105291; double _105759; _105759 = _105757 + _105758; double _105746; _105746 = _105743 + _105745; double _105752; _105752 = _105750 + _105751; double rz_105761; rz_105761 = _105759 + _105760; double rx_105748; rx_105748 = _105746 + _105747; double ry_105754; ry_105754 = _105752 + _105753; double _105762; _105762 = _105301 * rz_105761; double _105749; _105749 = _105276 * rx_105748; double _105755; _105755 = _105289 * ry_105754; double _105756; _105756 = _105749 + _105755; double _105763; _105763 = _105756 + _105762; double _105764; _105764 = _105763 * _105763; double D_105765; D_105765 = _105764 - C_105317; bool _105766; _105766 = 0.000000e+00 < D_105765; if (_105766) goto l105767; else goto l107341; l107341: ; goto l107338; l105767: ; _105770 = sqrt(D_105765); p_105770 = _105770; l105768: ; _105770 = p_105770; double _105771; _105771 = -0.000000e+00 - _105763; double t_105772; t_105772 = _105771 - _105770; bool _105773; _105773 = 0.000000e+00 < t_105772; if (_105773) goto l105774; else goto l107340; l107340: ; goto l107337; l105774: ; bool _105775; _105775 = t_105772 < 1.000000e+17; if (_105775) goto l105776; else goto l107336; l107336: ; goto l107337; l107337: ; goto l107338; l107338: ; struct_Isect_9647 _107049_475; _107049_475.e0 = 1.000000e+17; // bottom: _107049_475.e1 = // bottom: struct_vec_9645 _107047_479;; // bottom: _107049_475.e2 = _107047_479; _107049_475.e3 = 0; pray_sphere_intersect_105804 = _107049_475; goto l105802; l105776: ; double _105781; _105781 = ry_105754 * t_105772; double _105786; _105786 = rz_105761 * t_105772; double _105777; _105777 = rx_105748 * t_105772; double _105782; _105782 = _105288 + _105781; double _105787; _105787 = _105300 + _105786; double _105788; _105788 = _105787 - -3.500000e+00; double _105778; _105778 = _105275 + _105777; double _105783; _105783 = _105782 - 0.000000e+00; double _105789; _105789 = _105788 * _105788; double _105779; _105779 = _105778 - -2.000000e+00; double _105784; _105784 = _105783 * _105783; double _105780; _105780 = _105779 * _105779; double _105785; _105785 = _105780 + _105784; double _105790; _105790 = _105785 + _105789; length_105793 = sqrt(_105790); plength_105793 = length_105793; l105791: ; length_105793 = plength_105793; _105796 = fabs(length_105793); p_105796 = _105796; l105794: ; _105796 = p_105796; bool _105797; _105797 = 1.000000e-17 < _105796; if (_105797) goto l105798; else goto l107334; l107334: ; struct_vec_9645 n_107335; n_107335.e0 = _105779; n_107335.e1 = _105783; n_107335.e2 = _105788; pvnormalize_105801 = n_107335; goto l105799; l105798: ; double _107331; _107331 = _105783 / length_105793; double _107332; _107332 = _105788 / length_105793; double _107330; _107330 = _105779 / length_105793; struct_vec_9645 _107333; _107333.e0 = _107330; _107333.e1 = _107331; _107333.e2 = _107332; pvnormalize_105801 = _107333; goto l105799; l105799: ; vnormalize_105801 = pvnormalize_105801; struct_vec_9645 p_107328; p_107328.e0 = _105778; p_107328.e1 = _105782; p_107328.e2 = _105787; struct_Isect_9647 isect_107329; isect_107329.e0 = t_105772; isect_107329.e1 = p_107328; isect_107329.e2 = vnormalize_105801; isect_107329.e3 = 1; pray_sphere_intersect_105804 = isect_107329; goto l105802; l105802: ; ray_sphere_intersect_105804 = pray_sphere_intersect_105804; double _105805; _105805 = _105358 * rx_105748; double _105806; _105806 = _105805 + _105755; double _105807; _105807 = _105361 * rz_105761; double _105808; _105808 = _105806 + _105807; double _105809; _105809 = _105808 * _105808; double D_105810; D_105810 = _105809 - C_105369; bool _105811; _105811 = 0.000000e+00 < D_105810; if (_105811) goto l105812; else goto l107327; l107327: ; goto l107324; l105812: ; _105815 = sqrt(D_105810); p_105815 = _105815; l105813: ; _105815 = p_105815; double _105816; _105816 = -0.000000e+00 - _105808; double t_105817; t_105817 = _105816 - _105815; bool _105818; _105818 = 0.000000e+00 < t_105817; if (_105818) goto l105819; else goto l107326; l107326: ; goto l107323; l105819: ; double _105820; _105820 = ray_sphere_intersect_105804.e0; bool _105821; _105821 = t_105817 < _105820; if (_105821) goto l105822; else goto l107322; l107322: ; goto l107323; l107323: ; goto l107324; l107324: ; pray_sphere_intersect_105850 = ray_sphere_intersect_105804; goto l105848; l105822: ; double _105827; _105827 = ry_105754 * t_105817; double _105832; _105832 = rz_105761 * t_105817; double _105833; _105833 = _105300 + _105832; double _105823; _105823 = rx_105748 * t_105817; double _105828; _105828 = _105288 + _105827; double _105834; _105834 = _105833 - -3.000000e+00; double _105824; _105824 = _105275 + _105823; double _105829; _105829 = _105828 - 0.000000e+00; double _105835; _105835 = _105834 * _105834; double _105825; _105825 = _105824 - -5.000000e-01; double _105830; _105830 = _105829 * _105829; double _105826; _105826 = _105825 * _105825; double _105831; _105831 = _105826 + _105830; double _105836; _105836 = _105831 + _105835; length_105839 = sqrt(_105836); plength_105839 = length_105839; l105837: ; length_105839 = plength_105839; _105842 = fabs(length_105839); p_105842 = _105842; l105840: ; _105842 = p_105842; bool _105843; _105843 = 1.000000e-17 < _105842; if (_105843) goto l105844; else goto l107320; l107320: ; struct_vec_9645 n_107321; n_107321.e0 = _105825; n_107321.e1 = _105829; n_107321.e2 = _105834; pvnormalize_105847 = n_107321; goto l105845; l105844: ; double _107316; _107316 = _105825 / length_105839; double _107318; _107318 = _105834 / length_105839; double _107317; _107317 = _105829 / length_105839; struct_vec_9645 _107319; _107319.e0 = _107316; _107319.e1 = _107317; _107319.e2 = _107318; pvnormalize_105847 = _107319; goto l105845; l105845: ; vnormalize_105847 = pvnormalize_105847; struct_vec_9645 p_107314; p_107314.e0 = _105824; p_107314.e1 = _105828; p_107314.e2 = _105833; struct_Isect_9647 isect_107315; isect_107315.e0 = t_105817; isect_107315.e1 = p_107314; isect_107315.e2 = vnormalize_105847; isect_107315.e3 = 1; pray_sphere_intersect_105850 = isect_107315; goto l105848; l105848: ; ray_sphere_intersect_105850 = pray_sphere_intersect_105850; double _105853; _105853 = _105414 * rz_105761; double _105851; _105851 = _105411 * rx_105748; double _105852; _105852 = _105851 + _105755; double _105854; _105854 = _105852 + _105853; double _105855; _105855 = _105854 * _105854; double D_105856; D_105856 = _105855 - C_105422; bool _105857; _105857 = 0.000000e+00 < D_105856; if (_105857) goto l105858; else goto l107313; l107313: ; goto l107310; l105858: ; _105861 = sqrt(D_105856); p_105861 = _105861; l105859: ; _105861 = p_105861; double _105862; _105862 = -0.000000e+00 - _105854; double t_105863; t_105863 = _105862 - _105861; bool _105864; _105864 = 0.000000e+00 < t_105863; if (_105864) goto l105865; else goto l107312; l107312: ; goto l107309; l105865: ; double _105866; _105866 = ray_sphere_intersect_105850.e0; bool _105867; _105867 = t_105863 < _105866; if (_105867) goto l105868; else goto l107308; l107308: ; goto l107309; l107309: ; goto l107310; l107310: ; pray_sphere_intersect_105896 = ray_sphere_intersect_105850; goto l105894; l105868: ; double _105869; _105869 = rx_105748 * t_105863; double _105878; _105878 = rz_105761 * t_105863; double _105873; _105873 = ry_105754 * t_105863; double _105870; _105870 = _105275 + _105869; double _105879; _105879 = _105300 + _105878; double _105874; _105874 = _105288 + _105873; double _105871; _105871 = _105870 - 1.000000e+00; double _105880; _105880 = _105879 - -2.200000e+00; double _105875; _105875 = _105874 - 0.000000e+00; double _105872; _105872 = _105871 * _105871; double _105881; _105881 = _105880 * _105880; double _105876; _105876 = _105875 * _105875; double _105877; _105877 = _105872 + _105876; double _105882; _105882 = _105877 + _105881; length_105885 = sqrt(_105882); plength_105885 = length_105885; l105883: ; length_105885 = plength_105885; _105888 = fabs(length_105885); p_105888 = _105888; l105886: ; _105888 = p_105888; bool _105889; _105889 = 1.000000e-17 < _105888; if (_105889) goto l105890; else goto l107306; l107306: ; struct_vec_9645 n_107307; n_107307.e0 = _105871; n_107307.e1 = _105875; n_107307.e2 = _105880; pvnormalize_105893 = n_107307; goto l105891; l105890: ; double _107303; _107303 = _105875 / length_105885; double _107302; _107302 = _105871 / length_105885; double _107304; _107304 = _105880 / length_105885; struct_vec_9645 _107305; _107305.e0 = _107302; _107305.e1 = _107303; _107305.e2 = _107304; pvnormalize_105893 = _107305; goto l105891; l105891: ; vnormalize_105893 = pvnormalize_105893; struct_vec_9645 p_107300; p_107300.e0 = _105870; p_107300.e1 = _105874; p_107300.e2 = _105879; struct_Isect_9647 isect_107301; isect_107301.e0 = t_105863; isect_107301.e1 = p_107300; isect_107301.e2 = vnormalize_105893; isect_107301.e3 = 1; pray_sphere_intersect_105896 = isect_107301; goto l105894; l105894: ; ray_sphere_intersect_105896 = pray_sphere_intersect_105896; double _105900; _105900 = 0.000000e+00 * rz_105761; double _105898; _105898 = 1.000000e+00 * ry_105754; double _105897; _105897 = 0.000000e+00 * rx_105748; double _105899; _105899 = _105897 + _105898; double _105901; _105901 = _105899 + _105900; _105904 = fabs(_105901); p_105904 = _105904; l105902: ; _105904 = p_105904; bool _105905; _105905 = 1.000000e-17 <= _105904; if (_105905) goto l105906; else goto l107299; l107299: ; goto l107296; l105906: ; double t_105907; t_105907 = _105480 / _105901; bool _105908; _105908 = 0.000000e+00 < t_105907; if (_105908) goto l105909; else goto l107298; l107298: ; goto l107295; l105909: ; double _105910; _105910 = ray_sphere_intersect_105896.e0; bool _105911; _105911 = t_105907 < _105910; if (_105911) goto l105912; else goto l107294; l107294: ; goto l107295; l107295: ; goto l107296; l107296: ; pray_plane_intersect_105915 = ray_sphere_intersect_105896; goto l105913; l105912: ; double _107290; _107290 = rz_105761 * t_105907; double _107286; _107286 = rx_105748 * t_105907; double _107287; _107287 = _105275 + _107286; double _107288; _107288 = ry_105754 * t_105907; double _107291; _107291 = _105300 + _107290; double _107289; _107289 = _105288 + _107288; struct_vec_9645 p_107292; p_107292.e0 = _107287; p_107292.e1 = _107289; p_107292.e2 = _107291; struct_vec_9645 _106999_554; _106999_554.e0 = 0.000000e+00; _106999_554.e1 = 1.000000e+00; _106999_554.e2 = 0.000000e+00; struct_Isect_9647 isect_107293; isect_107293.e0 = t_105907; isect_107293.e1 = p_107292; isect_107293.e2 = _106999_554; isect_107293.e3 = 1; pray_plane_intersect_105915 = isect_107293; goto l105913; l105913: ; ray_plane_intersect_105915 = pray_plane_intersect_105915; int _105916; _105916 = ray_plane_intersect_105915.e3; bool _105917; _105917 = _105916 == 1; if (_105917) goto l105918; else goto l107285; l107285: ; pocclusion_105921 = occlusion_105708; goto l105919; l105918: ; double _107284; _107284 = 1.000000e+00 + occlusion_105708; pocclusion_105921 = _107284; goto l105919; l105919: ; occlusion_105921 = pocclusion_105921; unsigned long _105922; _105922 = 4294883355 * lo_105723; unsigned long _105923; _105923 = _105922 + hi_105725; unsigned long hi_105926; hi_105926 = _105923 >> 32; unsigned long lo_105924; lo_105924 = 4294967295 & _105923; unsigned int _105927; _105927 = (unsigned int)hi_105926; unsigned int _105925; _105925 = (unsigned int)lo_105924; unsigned int _105928; _105928 = _105925 ^ _105927; double _105929; _105929 = (double)_105928; double _105930; _105930 = 2.328306e-10 * _105929; theta_105933 = sqrt(_105930); ptheta_105933 = theta_105933; l105931: ; theta_105933 = ptheta_105933; unsigned long _105934; _105934 = 4294883355 * lo_105924; unsigned long _105935; _105935 = _105934 + hi_105926; unsigned long lo_105936; lo_105936 = 4294967295 & _105935; unsigned long hi_105938; hi_105938 = _105935 >> 32; unsigned int _105937; _105937 = (unsigned int)lo_105936; unsigned int _105939; _105939 = (unsigned int)hi_105938; unsigned int _105940; _105940 = _105937 ^ _105939; double _105941; _105941 = (double)_105940; double _105942; _105942 = 2.328306e-10 * _105941; double phi_105943; phi_105943 = 6.283185e+00 * _105942; _105946 = cos(phi_105943); p_105946 = _105946; l105944: ; _105946 = p_105946; _105949 = sin(phi_105943); p_105949 = _105949; l105947: ; _105949 = p_105949; double _105950; _105950 = theta_105933 * theta_105933; double _105951; _105951 = 1.000000e+00 - _105950; z_105954 = sqrt(_105951); pz_105954 = z_105954; l105952: ; z_105954 = pz_105954; double _105960; _105960 = z_105954 * _105152; double x_105955; x_105955 = _105946 * theta_105933; double _105963; _105963 = x_105955 * _105192; double _105970; _105970 = x_105955 * _105190; double _105966; _105966 = z_105954 * _105165; double _105973; _105973 = z_105954 * _105163; double _105956; _105956 = x_105955 * _105196; double y_105957; y_105957 = _105949 * theta_105933; double _105971; _105971 = y_105957 * _105303; double _105958; _105958 = y_105957 * _105280; double _105964; _105964 = y_105957 * _105291; double _105972; _105972 = _105970 + _105971; double _105959; _105959 = _105956 + _105958; double _105965; _105965 = _105963 + _105964; double rz_105974; rz_105974 = _105972 + _105973; double rx_105961; rx_105961 = _105959 + _105960; double ry_105967; ry_105967 = _105965 + _105966; double _105975; _105975 = _105301 * rz_105974; double _105962; _105962 = _105276 * rx_105961; double _105968; _105968 = _105289 * ry_105967; double _105969; _105969 = _105962 + _105968; double _105976; _105976 = _105969 + _105975; double _105977; _105977 = _105976 * _105976; double D_105978; D_105978 = _105977 - C_105317; bool _105979; _105979 = 0.000000e+00 < D_105978; if (_105979) goto l105980; else goto l107283; l107283: ; goto l107280; l105980: ; _105983 = sqrt(D_105978); p_105983 = _105983; l105981: ; _105983 = p_105983; double _105984; _105984 = -0.000000e+00 - _105976; double t_105985; t_105985 = _105984 - _105983; bool _105986; _105986 = 0.000000e+00 < t_105985; if (_105986) goto l105987; else goto l107282; l107282: ; goto l107279; l105987: ; bool _105988; _105988 = t_105985 < 1.000000e+17; if (_105988) goto l105989; else goto l107278; l107278: ; goto l107279; l107279: ; goto l107280; l107280: ; struct_Isect_9647 _107049_583; _107049_583.e0 = 1.000000e+17; // bottom: _107049_583.e1 = // bottom: struct_vec_9645 _107047_587;; // bottom: _107049_583.e2 = _107047_587; _107049_583.e3 = 0; pray_sphere_intersect_106017 = _107049_583; goto l106015; l105989: ; double _105994; _105994 = ry_105967 * t_105985; double _105995; _105995 = _105288 + _105994; double _105999; _105999 = rz_105974 * t_105985; double _105990; _105990 = rx_105961 * t_105985; double _105996; _105996 = _105995 - 0.000000e+00; double _106000; _106000 = _105300 + _105999; double _105991; _105991 = _105275 + _105990; double _105997; _105997 = _105996 * _105996; double _106001; _106001 = _106000 - -3.500000e+00; double _105992; _105992 = _105991 - -2.000000e+00; double _106002; _106002 = _106001 * _106001; double _105993; _105993 = _105992 * _105992; double _105998; _105998 = _105993 + _105997; double _106003; _106003 = _105998 + _106002; length_106006 = sqrt(_106003); plength_106006 = length_106006; l106004: ; length_106006 = plength_106006; _106009 = fabs(length_106006); p_106009 = _106009; l106007: ; _106009 = p_106009; bool _106010; _106010 = 1.000000e-17 < _106009; if (_106010) goto l106011; else goto l107276; l107276: ; struct_vec_9645 n_107277; n_107277.e0 = _105992; n_107277.e1 = _105996; n_107277.e2 = _106001; pvnormalize_106014 = n_107277; goto l106012; l106011: ; double _107273; _107273 = _105996 / length_106006; double _107272; _107272 = _105992 / length_106006; double _107274; _107274 = _106001 / length_106006; struct_vec_9645 _107275; _107275.e0 = _107272; _107275.e1 = _107273; _107275.e2 = _107274; pvnormalize_106014 = _107275; goto l106012; l106012: ; vnormalize_106014 = pvnormalize_106014; struct_vec_9645 p_107270; p_107270.e0 = _105991; p_107270.e1 = _105995; p_107270.e2 = _106000; struct_Isect_9647 isect_107271; isect_107271.e0 = t_105985; isect_107271.e1 = p_107270; isect_107271.e2 = vnormalize_106014; isect_107271.e3 = 1; pray_sphere_intersect_106017 = isect_107271; goto l106015; l106015: ; ray_sphere_intersect_106017 = pray_sphere_intersect_106017; double _106020; _106020 = _105361 * rz_105974; double _106018; _106018 = _105358 * rx_105961; double _106019; _106019 = _106018 + _105968; double _106021; _106021 = _106019 + _106020; double _106022; _106022 = _106021 * _106021; double D_106023; D_106023 = _106022 - C_105369; bool _106024; _106024 = 0.000000e+00 < D_106023; if (_106024) goto l106025; else goto l107269; l107269: ; goto l107266; l106025: ; _106028 = sqrt(D_106023); p_106028 = _106028; l106026: ; _106028 = p_106028; double _106029; _106029 = -0.000000e+00 - _106021; double t_106030; t_106030 = _106029 - _106028; bool _106031; _106031 = 0.000000e+00 < t_106030; if (_106031) goto l106032; else goto l107268; l107268: ; goto l107265; l106032: ; double _106033; _106033 = ray_sphere_intersect_106017.e0; bool _106034; _106034 = t_106030 < _106033; if (_106034) goto l106035; else goto l107264; l107264: ; goto l107265; l107265: ; goto l107266; l107266: ; pray_sphere_intersect_106063 = ray_sphere_intersect_106017; goto l106061; l106035: ; double _106045; _106045 = rz_105974 * t_106030; double _106040; _106040 = ry_105967 * t_106030; double _106041; _106041 = _105288 + _106040; double _106046; _106046 = _105300 + _106045; double _106042; _106042 = _106041 - 0.000000e+00; double _106036; _106036 = rx_105961 * t_106030; double _106047; _106047 = _106046 - -3.000000e+00; double _106043; _106043 = _106042 * _106042; double _106037; _106037 = _105275 + _106036; double _106048; _106048 = _106047 * _106047; double _106038; _106038 = _106037 - -5.000000e-01; double _106039; _106039 = _106038 * _106038; double _106044; _106044 = _106039 + _106043; double _106049; _106049 = _106044 + _106048; length_106052 = sqrt(_106049); plength_106052 = length_106052; l106050: ; length_106052 = plength_106052; _106055 = fabs(length_106052); p_106055 = _106055; l106053: ; _106055 = p_106055; bool _106056; _106056 = 1.000000e-17 < _106055; if (_106056) goto l106057; else goto l107262; l107262: ; struct_vec_9645 n_107263; n_107263.e0 = _106038; n_107263.e1 = _106042; n_107263.e2 = _106047; pvnormalize_106060 = n_107263; goto l106058; l106057: ; double _107258; _107258 = _106038 / length_106052; double _107259; _107259 = _106042 / length_106052; double _107260; _107260 = _106047 / length_106052; struct_vec_9645 _107261; _107261.e0 = _107258; _107261.e1 = _107259; _107261.e2 = _107260; pvnormalize_106060 = _107261; goto l106058; l106058: ; vnormalize_106060 = pvnormalize_106060; struct_vec_9645 p_107256; p_107256.e0 = _106037; p_107256.e1 = _106041; p_107256.e2 = _106046; struct_Isect_9647 isect_107257; isect_107257.e0 = t_106030; isect_107257.e1 = p_107256; isect_107257.e2 = vnormalize_106060; isect_107257.e3 = 1; pray_sphere_intersect_106063 = isect_107257; goto l106061; l106061: ; ray_sphere_intersect_106063 = pray_sphere_intersect_106063; double _106066; _106066 = _105414 * rz_105974; double _106064; _106064 = _105411 * rx_105961; double _106065; _106065 = _106064 + _105968; double _106067; _106067 = _106065 + _106066; double _106068; _106068 = _106067 * _106067; double D_106069; D_106069 = _106068 - C_105422; bool _106070; _106070 = 0.000000e+00 < D_106069; if (_106070) goto l106071; else goto l107255; l107255: ; goto l107252; l106071: ; _106074 = sqrt(D_106069); p_106074 = _106074; l106072: ; _106074 = p_106074; double _106075; _106075 = -0.000000e+00 - _106067; double t_106076; t_106076 = _106075 - _106074; bool _106077; _106077 = 0.000000e+00 < t_106076; if (_106077) goto l106078; else goto l107254; l107254: ; goto l107251; l106078: ; double _106079; _106079 = ray_sphere_intersect_106063.e0; bool _106080; _106080 = t_106076 < _106079; if (_106080) goto l106081; else goto l107250; l107250: ; goto l107251; l107251: ; goto l107252; l107252: ; pray_sphere_intersect_106109 = ray_sphere_intersect_106063; goto l106107; l106081: ; double _106091; _106091 = rz_105974 * t_106076; double _106086; _106086 = ry_105967 * t_106076; double _106092; _106092 = _105300 + _106091; double _106093; _106093 = _106092 - -2.200000e+00; double _106087; _106087 = _105288 + _106086; double _106082; _106082 = rx_105961 * t_106076; double _106083; _106083 = _105275 + _106082; double _106084; _106084 = _106083 - 1.000000e+00; double _106088; _106088 = _106087 - 0.000000e+00; double _106085; _106085 = _106084 * _106084; double _106094; _106094 = _106093 * _106093; double _106089; _106089 = _106088 * _106088; double _106090; _106090 = _106085 + _106089; double _106095; _106095 = _106090 + _106094; length_106098 = sqrt(_106095); plength_106098 = length_106098; l106096: ; length_106098 = plength_106098; _106101 = fabs(length_106098); p_106101 = _106101; l106099: ; _106101 = p_106101; bool _106102; _106102 = 1.000000e-17 < _106101; if (_106102) goto l106103; else goto l107248; l107248: ; struct_vec_9645 n_107249; n_107249.e0 = _106084; n_107249.e1 = _106088; n_107249.e2 = _106093; pvnormalize_106106 = n_107249; goto l106104; l106103: ; double _107244; _107244 = _106084 / length_106098; double _107246; _107246 = _106093 / length_106098; double _107245; _107245 = _106088 / length_106098; struct_vec_9645 _107247; _107247.e0 = _107244; _107247.e1 = _107245; _107247.e2 = _107246; pvnormalize_106106 = _107247; goto l106104; l106104: ; vnormalize_106106 = pvnormalize_106106; struct_vec_9645 p_107242; p_107242.e0 = _106083; p_107242.e1 = _106087; p_107242.e2 = _106092; struct_Isect_9647 isect_107243; isect_107243.e0 = t_106076; isect_107243.e1 = p_107242; isect_107243.e2 = vnormalize_106106; isect_107243.e3 = 1; pray_sphere_intersect_106109 = isect_107243; goto l106107; l106107: ; ray_sphere_intersect_106109 = pray_sphere_intersect_106109; double _106111; _106111 = 1.000000e+00 * ry_105967; double _106113; _106113 = 0.000000e+00 * rz_105974; double _106110; _106110 = 0.000000e+00 * rx_105961; double _106112; _106112 = _106110 + _106111; double _106114; _106114 = _106112 + _106113; _106117 = fabs(_106114); p_106117 = _106117; l106115: ; _106117 = p_106117; bool _106118; _106118 = 1.000000e-17 <= _106117; if (_106118) goto l106119; else goto l107241; l107241: ; goto l107238; l106119: ; double t_106120; t_106120 = _105480 / _106114; bool _106121; _106121 = 0.000000e+00 < t_106120; if (_106121) goto l106122; else goto l107240; l107240: ; goto l107237; l106122: ; double _106123; _106123 = ray_sphere_intersect_106109.e0; bool _106124; _106124 = t_106120 < _106123; if (_106124) goto l106125; else goto l107236; l107236: ; goto l107237; l107237: ; goto l107238; l107238: ; pray_plane_intersect_106128 = ray_sphere_intersect_106109; goto l106126; l106125: ; double _107230; _107230 = ry_105967 * t_106120; double _107231; _107231 = _105288 + _107230; double _107228; _107228 = rx_105961 * t_106120; double _107232; _107232 = rz_105974 * t_106120; double _107233; _107233 = _105300 + _107232; double _107229; _107229 = _105275 + _107228; struct_vec_9645 p_107234; p_107234.e0 = _107229; p_107234.e1 = _107231; p_107234.e2 = _107233; struct_vec_9645 _106999_662; _106999_662.e0 = 0.000000e+00; _106999_662.e1 = 1.000000e+00; _106999_662.e2 = 0.000000e+00; struct_Isect_9647 isect_107235; isect_107235.e0 = t_106120; isect_107235.e1 = p_107234; isect_107235.e2 = _106999_662; isect_107235.e3 = 1; pray_plane_intersect_106128 = isect_107235; goto l106126; l106126: ; ray_plane_intersect_106128 = pray_plane_intersect_106128; int _106129; _106129 = ray_plane_intersect_106128.e3; bool _106130; _106130 = _106129 == 1; if (_106130) goto l106131; else goto l107227; l107227: ; pocclusion_106134 = occlusion_105921; goto l106132; l106131: ; double _107226; _107226 = 1.000000e+00 + occlusion_105921; pocclusion_106134 = _107226; goto l106132; l106132: ; occlusion_106134 = pocclusion_106134; unsigned long _106135; _106135 = 4294883355 * lo_105936; unsigned long _106136; _106136 = _106135 + hi_105938; unsigned long lo_106137; lo_106137 = 4294967295 & _106136; unsigned long hi_106139; hi_106139 = _106136 >> 32; unsigned int _106138; _106138 = (unsigned int)lo_106137; unsigned int _106140; _106140 = (unsigned int)hi_106139; unsigned int _106141; _106141 = _106138 ^ _106140; double _106142; _106142 = (double)_106141; double _106143; _106143 = 2.328306e-10 * _106142; theta_106146 = sqrt(_106143); ptheta_106146 = theta_106146; l106144: ; theta_106146 = ptheta_106146; unsigned long _106147; _106147 = 4294883355 * lo_106137; unsigned long _106148; _106148 = _106147 + hi_106139; unsigned long hi_106151; hi_106151 = _106148 >> 32; unsigned long lo_106149; lo_106149 = 4294967295 & _106148; unsigned int _106152; _106152 = (unsigned int)hi_106151; unsigned int _106150; _106150 = (unsigned int)lo_106149; unsigned int _106153; _106153 = _106150 ^ _106152; double _106154; _106154 = (double)_106153; double _106155; _106155 = 2.328306e-10 * _106154; double phi_106156; phi_106156 = 6.283185e+00 * _106155; _106159 = cos(phi_106156); p_106159 = _106159; l106157: ; _106159 = p_106159; _106162 = sin(phi_106156); p_106162 = _106162; l106160: ; _106162 = p_106162; double _106163; _106163 = theta_106146 * theta_106146; double _106164; _106164 = 1.000000e+00 - _106163; z_106167 = sqrt(_106164); pz_106167 = z_106167; l106165: ; z_106167 = pz_106167; double x_106168; x_106168 = _106159 * theta_106146; double _106169; _106169 = x_106168 * _105196; double _106179; _106179 = z_106167 * _105165; double _106186; _106186 = z_106167 * _105163; double y_106170; y_106170 = _106162 * theta_106146; double _106176; _106176 = x_106168 * _105192; double _106173; _106173 = z_106167 * _105152; double _106183; _106183 = x_106168 * _105190; double _106184; _106184 = y_106170 * _105303; double _106171; _106171 = y_106170 * _105280; double _106177; _106177 = y_106170 * _105291; double _106178; _106178 = _106176 + _106177; double _106185; _106185 = _106183 + _106184; double _106172; _106172 = _106169 + _106171; double ry_106180; ry_106180 = _106178 + _106179; double rz_106187; rz_106187 = _106185 + _106186; double rx_106174; rx_106174 = _106172 + _106173; double _106181; _106181 = _105289 * ry_106180; double _106188; _106188 = _105301 * rz_106187; double _106175; _106175 = _105276 * rx_106174; double _106182; _106182 = _106175 + _106181; double _106189; _106189 = _106182 + _106188; double _106190; _106190 = _106189 * _106189; double D_106191; D_106191 = _106190 - C_105317; bool _106192; _106192 = 0.000000e+00 < D_106191; if (_106192) goto l106193; else goto l107225; l107225: ; goto l107222; l106193: ; _106196 = sqrt(D_106191); p_106196 = _106196; l106194: ; _106196 = p_106196; double _106197; _106197 = -0.000000e+00 - _106189; double t_106198; t_106198 = _106197 - _106196; bool _106199; _106199 = 0.000000e+00 < t_106198; if (_106199) goto l106200; else goto l107224; l107224: ; goto l107221; l106200: ; bool _106201; _106201 = t_106198 < 1.000000e+17; if (_106201) goto l106202; else goto l107220; l107220: ; goto l107221; l107221: ; goto l107222; l107222: ; struct_Isect_9647 _107049_691; _107049_691.e0 = 1.000000e+17; // bottom: _107049_691.e1 = // bottom: struct_vec_9645 _107047_695;; // bottom: _107049_691.e2 = _107047_695; _107049_691.e3 = 0; pray_sphere_intersect_106230 = _107049_691; goto l106228; l106202: ; double _106207; _106207 = ry_106180 * t_106198; double _106212; _106212 = rz_106187 * t_106198; double _106203; _106203 = rx_106174 * t_106198; double _106208; _106208 = _105288 + _106207; double _106213; _106213 = _105300 + _106212; double _106204; _106204 = _105275 + _106203; double _106209; _106209 = _106208 - 0.000000e+00; double _106214; _106214 = _106213 - -3.500000e+00; double _106205; _106205 = _106204 - -2.000000e+00; double _106210; _106210 = _106209 * _106209; double _106215; _106215 = _106214 * _106214; double _106206; _106206 = _106205 * _106205; double _106211; _106211 = _106206 + _106210; double _106216; _106216 = _106211 + _106215; length_106219 = sqrt(_106216); plength_106219 = length_106219; l106217: ; length_106219 = plength_106219; _106222 = fabs(length_106219); p_106222 = _106222; l106220: ; _106222 = p_106222; bool _106223; _106223 = 1.000000e-17 < _106222; if (_106223) goto l106224; else goto l107218; l107218: ; struct_vec_9645 n_107219; n_107219.e0 = _106205; n_107219.e1 = _106209; n_107219.e2 = _106214; pvnormalize_106227 = n_107219; goto l106225; l106224: ; double _107216; _107216 = _106214 / length_106219; double _107214; _107214 = _106205 / length_106219; double _107215; _107215 = _106209 / length_106219; struct_vec_9645 _107217; _107217.e0 = _107214; _107217.e1 = _107215; _107217.e2 = _107216; pvnormalize_106227 = _107217; goto l106225; l106225: ; vnormalize_106227 = pvnormalize_106227; struct_vec_9645 p_107212; p_107212.e0 = _106204; p_107212.e1 = _106208; p_107212.e2 = _106213; struct_Isect_9647 isect_107213; isect_107213.e0 = t_106198; isect_107213.e1 = p_107212; isect_107213.e2 = vnormalize_106227; isect_107213.e3 = 1; pray_sphere_intersect_106230 = isect_107213; goto l106228; l106228: ; ray_sphere_intersect_106230 = pray_sphere_intersect_106230; double _106231; _106231 = _105358 * rx_106174; double _106233; _106233 = _105361 * rz_106187; double _106232; _106232 = _106231 + _106181; double _106234; _106234 = _106232 + _106233; double _106235; _106235 = _106234 * _106234; double D_106236; D_106236 = _106235 - C_105369; bool _106237; _106237 = 0.000000e+00 < D_106236; if (_106237) goto l106238; else goto l107211; l107211: ; goto l107208; l106238: ; _106241 = sqrt(D_106236); p_106241 = _106241; l106239: ; _106241 = p_106241; double _106242; _106242 = -0.000000e+00 - _106234; double t_106243; t_106243 = _106242 - _106241; bool _106244; _106244 = 0.000000e+00 < t_106243; if (_106244) goto l106245; else goto l107210; l107210: ; goto l107207; l106245: ; double _106246; _106246 = ray_sphere_intersect_106230.e0; bool _106247; _106247 = t_106243 < _106246; if (_106247) goto l106248; else goto l107206; l107206: ; goto l107207; l107207: ; goto l107208; l107208: ; pray_sphere_intersect_106276 = ray_sphere_intersect_106230; goto l106274; l106248: ; double _106253; _106253 = ry_106180 * t_106243; double _106254; _106254 = _105288 + _106253; double _106249; _106249 = rx_106174 * t_106243; double _106258; _106258 = rz_106187 * t_106243; double _106259; _106259 = _105300 + _106258; double _106260; _106260 = _106259 - -3.000000e+00; double _106255; _106255 = _106254 - 0.000000e+00; double _106250; _106250 = _105275 + _106249; double _106261; _106261 = _106260 * _106260; double _106256; _106256 = _106255 * _106255; double _106251; _106251 = _106250 - -5.000000e-01; double _106252; _106252 = _106251 * _106251; double _106257; _106257 = _106252 + _106256; double _106262; _106262 = _106257 + _106261; length_106265 = sqrt(_106262); plength_106265 = length_106265; l106263: ; length_106265 = plength_106265; _106268 = fabs(length_106265); p_106268 = _106268; l106266: ; _106268 = p_106268; bool _106269; _106269 = 1.000000e-17 < _106268; if (_106269) goto l106270; else goto l107204; l107204: ; struct_vec_9645 n_107205; n_107205.e0 = _106251; n_107205.e1 = _106255; n_107205.e2 = _106260; pvnormalize_106273 = n_107205; goto l106271; l106270: ; double _107202; _107202 = _106260 / length_106265; double _107200; _107200 = _106251 / length_106265; double _107201; _107201 = _106255 / length_106265; struct_vec_9645 _107203; _107203.e0 = _107200; _107203.e1 = _107201; _107203.e2 = _107202; pvnormalize_106273 = _107203; goto l106271; l106271: ; vnormalize_106273 = pvnormalize_106273; struct_vec_9645 p_107198; p_107198.e0 = _106250; p_107198.e1 = _106254; p_107198.e2 = _106259; struct_Isect_9647 isect_107199; isect_107199.e0 = t_106243; isect_107199.e1 = p_107198; isect_107199.e2 = vnormalize_106273; isect_107199.e3 = 1; pray_sphere_intersect_106276 = isect_107199; goto l106274; l106274: ; ray_sphere_intersect_106276 = pray_sphere_intersect_106276; double _106277; _106277 = _105411 * rx_106174; double _106279; _106279 = _105414 * rz_106187; double _106278; _106278 = _106277 + _106181; double _106280; _106280 = _106278 + _106279; double _106281; _106281 = _106280 * _106280; double D_106282; D_106282 = _106281 - C_105422; bool _106283; _106283 = 0.000000e+00 < D_106282; if (_106283) goto l106284; else goto l107197; l107197: ; goto l107194; l106284: ; _106287 = sqrt(D_106282); p_106287 = _106287; l106285: ; _106287 = p_106287; double _106288; _106288 = -0.000000e+00 - _106280; double t_106289; t_106289 = _106288 - _106287; bool _106290; _106290 = 0.000000e+00 < t_106289; if (_106290) goto l106291; else goto l107196; l107196: ; goto l107193; l106291: ; double _106292; _106292 = ray_sphere_intersect_106276.e0; bool _106293; _106293 = t_106289 < _106292; if (_106293) goto l106294; else goto l107192; l107192: ; goto l107193; l107193: ; goto l107194; l107194: ; pray_sphere_intersect_106322 = ray_sphere_intersect_106276; goto l106320; l106294: ; double _106295; _106295 = rx_106174 * t_106289; double _106296; _106296 = _105275 + _106295; double _106297; _106297 = _106296 - 1.000000e+00; double _106298; _106298 = _106297 * _106297; double _106299; _106299 = ry_106180 * t_106289; double _106304; _106304 = rz_106187 * t_106289; double _106300; _106300 = _105288 + _106299; double _106305; _106305 = _105300 + _106304; double _106301; _106301 = _106300 - 0.000000e+00; double _106306; _106306 = _106305 - -2.200000e+00; double _106302; _106302 = _106301 * _106301; double _106307; _106307 = _106306 * _106306; double _106303; _106303 = _106298 + _106302; double _106308; _106308 = _106303 + _106307; length_106311 = sqrt(_106308); plength_106311 = length_106311; l106309: ; length_106311 = plength_106311; _106314 = fabs(length_106311); p_106314 = _106314; l106312: ; _106314 = p_106314; bool _106315; _106315 = 1.000000e-17 < _106314; if (_106315) goto l106316; else goto l107190; l107190: ; struct_vec_9645 n_107191; n_107191.e0 = _106297; n_107191.e1 = _106301; n_107191.e2 = _106306; pvnormalize_106319 = n_107191; goto l106317; l106316: ; double _107186; _107186 = _106297 / length_106311; double _107188; _107188 = _106306 / length_106311; double _107187; _107187 = _106301 / length_106311; struct_vec_9645 _107189; _107189.e0 = _107186; _107189.e1 = _107187; _107189.e2 = _107188; pvnormalize_106319 = _107189; goto l106317; l106317: ; vnormalize_106319 = pvnormalize_106319; struct_vec_9645 p_107184; p_107184.e0 = _106296; p_107184.e1 = _106300; p_107184.e2 = _106305; struct_Isect_9647 isect_107185; isect_107185.e0 = t_106289; isect_107185.e1 = p_107184; isect_107185.e2 = vnormalize_106319; isect_107185.e3 = 1; pray_sphere_intersect_106322 = isect_107185; goto l106320; l106320: ; ray_sphere_intersect_106322 = pray_sphere_intersect_106322; double _106326; _106326 = 0.000000e+00 * rz_106187; double _106323; _106323 = 0.000000e+00 * rx_106174; double _106324; _106324 = 1.000000e+00 * ry_106180; double _106325; _106325 = _106323 + _106324; double _106327; _106327 = _106325 + _106326; _106330 = fabs(_106327); p_106330 = _106330; l106328: ; _106330 = p_106330; bool _106331; _106331 = 1.000000e-17 <= _106330; if (_106331) goto l106332; else goto l107183; l107183: ; goto l107180; l106332: ; double t_106333; t_106333 = _105480 / _106327; bool _106334; _106334 = 0.000000e+00 < t_106333; if (_106334) goto l106335; else goto l107182; l107182: ; goto l107179; l106335: ; double _106336; _106336 = ray_sphere_intersect_106322.e0; bool _106337; _106337 = t_106333 < _106336; if (_106337) goto l106338; else goto l107178; l107178: ; goto l107179; l107179: ; goto l107180; l107180: ; pray_plane_intersect_106341 = ray_sphere_intersect_106322; goto l106339; l106338: ; double _107174; _107174 = rz_106187 * t_106333; double _107172; _107172 = ry_106180 * t_106333; double _107173; _107173 = _105288 + _107172; double _107170; _107170 = rx_106174 * t_106333; double _107175; _107175 = _105300 + _107174; double _107171; _107171 = _105275 + _107170; struct_vec_9645 p_107176; p_107176.e0 = _107171; p_107176.e1 = _107173; p_107176.e2 = _107175; struct_vec_9645 _106999_770; _106999_770.e0 = 0.000000e+00; _106999_770.e1 = 1.000000e+00; _106999_770.e2 = 0.000000e+00; struct_Isect_9647 isect_107177; isect_107177.e0 = t_106333; isect_107177.e1 = p_107176; isect_107177.e2 = _106999_770; isect_107177.e3 = 1; pray_plane_intersect_106341 = isect_107177; goto l106339; l106339: ; ray_plane_intersect_106341 = pray_plane_intersect_106341; int _106342; _106342 = ray_plane_intersect_106341.e3; bool _106343; _106343 = _106342 == 1; if (_106343) goto l106344; else goto l107169; l107169: ; pocclusion_106347 = occlusion_106134; goto l106345; l106344: ; double _107168; _107168 = 1.000000e+00 + occlusion_106134; pocclusion_106347 = _107168; goto l106345; l106345: ; occlusion_106347 = pocclusion_106347; unsigned long _106348; _106348 = 4294883355 * lo_106149; unsigned long _106349; _106349 = _106348 + hi_106151; unsigned long lo_106350; lo_106350 = 4294967295 & _106349; unsigned long hi_106352; hi_106352 = _106349 >> 32; unsigned int _106351; _106351 = (unsigned int)lo_106350; unsigned int _106353; _106353 = (unsigned int)hi_106352; unsigned int _106354; _106354 = _106351 ^ _106353; double _106355; _106355 = (double)_106354; double _106356; _106356 = 2.328306e-10 * _106355; theta_106359 = sqrt(_106356); ptheta_106359 = theta_106359; l106357: ; theta_106359 = ptheta_106359; unsigned long _106360; _106360 = 4294883355 * lo_106350; unsigned long _106361; _106361 = _106360 + hi_106352; unsigned long lo_106362; lo_106362 = 4294967295 & _106361; unsigned int _106363; _106363 = (unsigned int)lo_106362; unsigned long hi_106364; hi_106364 = _106361 >> 32; unsigned int _106365; _106365 = (unsigned int)hi_106364; unsigned int _106366; _106366 = _106363 ^ _106365; double _106367; _106367 = (double)_106366; double _106368; _106368 = 2.328306e-10 * _106367; double phi_106369; phi_106369 = 6.283185e+00 * _106368; _106372 = cos(phi_106369); p_106372 = _106372; l106370: ; _106372 = p_106372; _106375 = sin(phi_106369); p_106375 = _106375; l106373: ; _106375 = p_106375; double _106376; _106376 = theta_106359 * theta_106359; double _106377; _106377 = 1.000000e+00 - _106376; z_106380 = sqrt(_106377); pz_106380 = z_106380; l106378: ; z_106380 = pz_106380; double x_106381; x_106381 = _106372 * theta_106359; double y_106383; y_106383 = _106375 * theta_106359; double _106399; _106399 = z_106380 * _105163; double _106384; _106384 = y_106383 * _105280; double _106389; _106389 = x_106381 * _105192; double _106390; _106390 = y_106383 * _105291; double _106391; _106391 = _106389 + _106390; double _106386; _106386 = z_106380 * _105152; double _106392; _106392 = z_106380 * _105165; double _106396; _106396 = x_106381 * _105190; double _106382; _106382 = x_106381 * _105196; double _106397; _106397 = y_106383 * _105303; double _106385; _106385 = _106382 + _106384; double ry_106393; ry_106393 = _106391 + _106392; double rx_106387; rx_106387 = _106385 + _106386; double _106398; _106398 = _106396 + _106397; double _106394; _106394 = _105289 * ry_106393; double _106388; _106388 = _105276 * rx_106387; double rz_106400; rz_106400 = _106398 + _106399; double _106395; _106395 = _106388 + _106394; double _106401; _106401 = _105301 * rz_106400; double _106402; _106402 = _106395 + _106401; double _106403; _106403 = _106402 * _106402; double D_106404; D_106404 = _106403 - C_105317; bool _106405; _106405 = 0.000000e+00 < D_106404; if (_106405) goto l106406; else goto l107167; l107167: ; goto l107164; l106406: ; _106409 = sqrt(D_106404); p_106409 = _106409; l106407: ; _106409 = p_106409; double _106410; _106410 = -0.000000e+00 - _106402; double t_106411; t_106411 = _106410 - _106409; bool _106412; _106412 = 0.000000e+00 < t_106411; if (_106412) goto l106413; else goto l107166; l107166: ; goto l107163; l106413: ; bool _106414; _106414 = t_106411 < 1.000000e+17; if (_106414) goto l106415; else goto l107162; l107162: ; goto l107163; l107163: ; goto l107164; l107164: ; struct_Isect_9647 _107049_799; _107049_799.e0 = 1.000000e+17; // bottom: _107049_799.e1 = // bottom: struct_vec_9645 _107047_803;; // bottom: _107049_799.e2 = _107047_803; _107049_799.e3 = 0; pray_sphere_intersect_106443 = _107049_799; goto l106441; l106415: ; double _106425; _106425 = rz_106400 * t_106411; double _106416; _106416 = rx_106387 * t_106411; double _106417; _106417 = _105275 + _106416; double _106420; _106420 = ry_106393 * t_106411; double _106426; _106426 = _105300 + _106425; double _106418; _106418 = _106417 - -2.000000e+00; double _106421; _106421 = _105288 + _106420; double _106427; _106427 = _106426 - -3.500000e+00; double _106419; _106419 = _106418 * _106418; double _106422; _106422 = _106421 - 0.000000e+00; double _106428; _106428 = _106427 * _106427; double _106423; _106423 = _106422 * _106422; double _106424; _106424 = _106419 + _106423; double _106429; _106429 = _106424 + _106428; length_106432 = sqrt(_106429); plength_106432 = length_106432; l106430: ; length_106432 = plength_106432; _106435 = fabs(length_106432); p_106435 = _106435; l106433: ; _106435 = p_106435; bool _106436; _106436 = 1.000000e-17 < _106435; if (_106436) goto l106437; else goto l107160; l107160: ; struct_vec_9645 n_107161; n_107161.e0 = _106418; n_107161.e1 = _106422; n_107161.e2 = _106427; pvnormalize_106440 = n_107161; goto l106438; l106437: ; double _107157; _107157 = _106422 / length_106432; double _107158; _107158 = _106427 / length_106432; double _107156; _107156 = _106418 / length_106432; struct_vec_9645 _107159; _107159.e0 = _107156; _107159.e1 = _107157; _107159.e2 = _107158; pvnormalize_106440 = _107159; goto l106438; l106438: ; vnormalize_106440 = pvnormalize_106440; struct_vec_9645 p_107154; p_107154.e0 = _106417; p_107154.e1 = _106421; p_107154.e2 = _106426; struct_Isect_9647 isect_107155; isect_107155.e0 = t_106411; isect_107155.e1 = p_107154; isect_107155.e2 = vnormalize_106440; isect_107155.e3 = 1; pray_sphere_intersect_106443 = isect_107155; goto l106441; l106441: ; ray_sphere_intersect_106443 = pray_sphere_intersect_106443; double _106444; _106444 = _105358 * rx_106387; double _106446; _106446 = _105361 * rz_106400; double _106445; _106445 = _106444 + _106394; double _106447; _106447 = _106445 + _106446; double _106448; _106448 = _106447 * _106447; double D_106449; D_106449 = _106448 - C_105369; bool _106450; _106450 = 0.000000e+00 < D_106449; if (_106450) goto l106451; else goto l107153; l107153: ; goto l107150; l106451: ; _106454 = sqrt(D_106449); p_106454 = _106454; l106452: ; _106454 = p_106454; double _106455; _106455 = -0.000000e+00 - _106447; double t_106456; t_106456 = _106455 - _106454; bool _106457; _106457 = 0.000000e+00 < t_106456; if (_106457) goto l106458; else goto l107152; l107152: ; goto l107149; l106458: ; double _106459; _106459 = ray_sphere_intersect_106443.e0; bool _106460; _106460 = t_106456 < _106459; if (_106460) goto l106461; else goto l107148; l107148: ; goto l107149; l107149: ; goto l107150; l107150: ; pray_sphere_intersect_106489 = ray_sphere_intersect_106443; goto l106487; l106461: ; double _106462; _106462 = rx_106387 * t_106456; double _106471; _106471 = rz_106400 * t_106456; double _106463; _106463 = _105275 + _106462; double _106466; _106466 = ry_106393 * t_106456; double _106472; _106472 = _105300 + _106471; double _106467; _106467 = _105288 + _106466; double _106464; _106464 = _106463 - -5.000000e-01; double _106473; _106473 = _106472 - -3.000000e+00; double _106468; _106468 = _106467 - 0.000000e+00; double _106465; _106465 = _106464 * _106464; double _106474; _106474 = _106473 * _106473; double _106469; _106469 = _106468 * _106468; double _106470; _106470 = _106465 + _106469; double _106475; _106475 = _106470 + _106474; length_106478 = sqrt(_106475); plength_106478 = length_106478; l106476: ; length_106478 = plength_106478; _106481 = fabs(length_106478); p_106481 = _106481; l106479: ; _106481 = p_106481; bool _106482; _106482 = 1.000000e-17 < _106481; if (_106482) goto l106483; else goto l107146; l107146: ; struct_vec_9645 n_107147; n_107147.e0 = _106464; n_107147.e1 = _106468; n_107147.e2 = _106473; pvnormalize_106486 = n_107147; goto l106484; l106483: ; double _107143; _107143 = _106468 / length_106478; double _107144; _107144 = _106473 / length_106478; double _107142; _107142 = _106464 / length_106478; struct_vec_9645 _107145; _107145.e0 = _107142; _107145.e1 = _107143; _107145.e2 = _107144; pvnormalize_106486 = _107145; goto l106484; l106484: ; vnormalize_106486 = pvnormalize_106486; struct_vec_9645 p_107140; p_107140.e0 = _106463; p_107140.e1 = _106467; p_107140.e2 = _106472; struct_Isect_9647 isect_107141; isect_107141.e0 = t_106456; isect_107141.e1 = p_107140; isect_107141.e2 = vnormalize_106486; isect_107141.e3 = 1; pray_sphere_intersect_106489 = isect_107141; goto l106487; l106487: ; ray_sphere_intersect_106489 = pray_sphere_intersect_106489; double _106492; _106492 = _105414 * rz_106400; double _106490; _106490 = _105411 * rx_106387; double _106491; _106491 = _106490 + _106394; double _106493; _106493 = _106491 + _106492; double _106494; _106494 = _106493 * _106493; double D_106495; D_106495 = _106494 - C_105422; bool _106496; _106496 = 0.000000e+00 < D_106495; if (_106496) goto l106497; else goto l107139; l107139: ; goto l107136; l106497: ; _106500 = sqrt(D_106495); p_106500 = _106500; l106498: ; _106500 = p_106500; double _106501; _106501 = -0.000000e+00 - _106493; double t_106502; t_106502 = _106501 - _106500; bool _106503; _106503 = 0.000000e+00 < t_106502; if (_106503) goto l106504; else goto l107138; l107138: ; goto l107135; l106504: ; double _106505; _106505 = ray_sphere_intersect_106489.e0; bool _106506; _106506 = t_106502 < _106505; if (_106506) goto l106507; else goto l107134; l107134: ; goto l107135; l107135: ; goto l107136; l107136: ; pray_sphere_intersect_106535 = ray_sphere_intersect_106489; goto l106533; l106507: ; double _106517; _106517 = rz_106400 * t_106502; double _106518; _106518 = _105300 + _106517; double _106508; _106508 = rx_106387 * t_106502; double _106509; _106509 = _105275 + _106508; double _106512; _106512 = ry_106393 * t_106502; double _106513; _106513 = _105288 + _106512; double _106519; _106519 = _106518 - -2.200000e+00; double _106510; _106510 = _106509 - 1.000000e+00; double _106514; _106514 = _106513 - 0.000000e+00; double _106520; _106520 = _106519 * _106519; double _106511; _106511 = _106510 * _106510; double _106515; _106515 = _106514 * _106514; double _106516; _106516 = _106511 + _106515; double _106521; _106521 = _106516 + _106520; length_106524 = sqrt(_106521); plength_106524 = length_106524; l106522: ; length_106524 = plength_106524; _106527 = fabs(length_106524); p_106527 = _106527; l106525: ; _106527 = p_106527; bool _106528; _106528 = 1.000000e-17 < _106527; if (_106528) goto l106529; else goto l107132; l107132: ; struct_vec_9645 n_107133; n_107133.e0 = _106510; n_107133.e1 = _106514; n_107133.e2 = _106519; pvnormalize_106532 = n_107133; goto l106530; l106529: ; double _107129; _107129 = _106514 / length_106524; double _107128; _107128 = _106510 / length_106524; double _107130; _107130 = _106519 / length_106524; struct_vec_9645 _107131; _107131.e0 = _107128; _107131.e1 = _107129; _107131.e2 = _107130; pvnormalize_106532 = _107131; goto l106530; l106530: ; vnormalize_106532 = pvnormalize_106532; struct_vec_9645 p_107126; p_107126.e0 = _106509; p_107126.e1 = _106513; p_107126.e2 = _106518; struct_Isect_9647 isect_107127; isect_107127.e0 = t_106502; isect_107127.e1 = p_107126; isect_107127.e2 = vnormalize_106532; isect_107127.e3 = 1; pray_sphere_intersect_106535 = isect_107127; goto l106533; l106533: ; ray_sphere_intersect_106535 = pray_sphere_intersect_106535; double _106539; _106539 = 0.000000e+00 * rz_106400; double _106537; _106537 = 1.000000e+00 * ry_106393; double _106536; _106536 = 0.000000e+00 * rx_106387; double _106538; _106538 = _106536 + _106537; double _106540; _106540 = _106538 + _106539; _106543 = fabs(_106540); p_106543 = _106543; l106541: ; _106543 = p_106543; bool _106544; _106544 = 1.000000e-17 <= _106543; if (_106544) goto l106545; else goto l107125; l107125: ; goto l107122; l106545: ; double t_106546; t_106546 = _105480 / _106540; bool _106547; _106547 = 0.000000e+00 < t_106546; if (_106547) goto l106548; else goto l107124; l107124: ; goto l107121; l106548: ; double _106549; _106549 = ray_sphere_intersect_106535.e0; bool _106550; _106550 = t_106546 < _106549; if (_106550) goto l106551; else goto l107120; l107120: ; goto l107121; l107121: ; goto l107122; l107122: ; pray_plane_intersect_106554 = ray_sphere_intersect_106535; goto l106552; l106551: ; double _107116; _107116 = rz_106400 * t_106546; double _107112; _107112 = rx_106387 * t_106546; double _107114; _107114 = ry_106393 * t_106546; double _107113; _107113 = _105275 + _107112; double _107117; _107117 = _105300 + _107116; double _107115; _107115 = _105288 + _107114; struct_vec_9645 p_107118; p_107118.e0 = _107113; p_107118.e1 = _107115; p_107118.e2 = _107117; struct_vec_9645 _106999_878; _106999_878.e0 = 0.000000e+00; _106999_878.e1 = 1.000000e+00; _106999_878.e2 = 0.000000e+00; struct_Isect_9647 isect_107119; isect_107119.e0 = t_106546; isect_107119.e1 = p_107118; isect_107119.e2 = _106999_878; isect_107119.e3 = 1; pray_plane_intersect_106554 = isect_107119; goto l106552; l106552: ; ray_plane_intersect_106554 = pray_plane_intersect_106554; int _106555; _106555 = ray_plane_intersect_106554.e3; bool _106556; _106556 = _106555 == 1; if (_106556) goto l106557; else goto l107111; l107111: ; pocclusion_106560 = occlusion_106347; goto l106558; l106557: ; double _107110; _107110 = 1.000000e+00 + occlusion_106347; pocclusion_106560 = _107110; goto l106558; l106558: ; occlusion_106560 = pocclusion_106560; unsigned long _106561; _106561 = 4294883355 * lo_106362; unsigned long _106562; _106562 = _106561 + hi_106364; unsigned long lo_106563; lo_106563 = 4294967295 & _106562; unsigned long hi_106565; hi_106565 = _106562 >> 32; unsigned int _106564; _106564 = (unsigned int)lo_106563; unsigned int _106566; _106566 = (unsigned int)hi_106565; unsigned int _106567; _106567 = _106564 ^ _106566; double _106568; _106568 = (double)_106567; double _106569; _106569 = 2.328306e-10 * _106568; theta_106572 = sqrt(_106569); ptheta_106572 = theta_106572; l106570: ; theta_106572 = ptheta_106572; unsigned long _106573; _106573 = 4294883355 * lo_106563; unsigned long _106574; _106574 = _106573 + hi_106565; unsigned long lo_106575; lo_106575 = 4294967295 & _106574; unsigned long hi_106577; hi_106577 = _106574 >> 32; unsigned int _106576; _106576 = (unsigned int)lo_106575; unsigned int _106578; _106578 = (unsigned int)hi_106577; unsigned int _106579; _106579 = _106576 ^ _106578; double _106580; _106580 = (double)_106579; double _106581; _106581 = 2.328306e-10 * _106580; double phi_106582; phi_106582 = 6.283185e+00 * _106581; _106585 = cos(phi_106582); p_106585 = _106585; l106583: ; _106585 = p_106585; _106588 = sin(phi_106582); p_106588 = _106588; l106586: ; _106588 = p_106588; double _106589; _106589 = theta_106572 * theta_106572; double _106590; _106590 = 1.000000e+00 - _106589; z_106593 = sqrt(_106590); pz_106593 = z_106593; l106591: ; z_106593 = pz_106593; double _106612; _106612 = z_106593 * _105163; double y_106596; y_106596 = _106588 * theta_106572; double _106603; _106603 = y_106596 * _105291; double x_106594; x_106594 = _106585 * theta_106572; double _106599; _106599 = z_106593 * _105152; double _106605; _106605 = z_106593 * _105165; double _106610; _106610 = y_106596 * _105303; double _106597; _106597 = y_106596 * _105280; double _106609; _106609 = x_106594 * _105190; double _106595; _106595 = x_106594 * _105196; double _106602; _106602 = x_106594 * _105192; double _106611; _106611 = _106609 + _106610; double _106598; _106598 = _106595 + _106597; double _106604; _106604 = _106602 + _106603; double rz_106613; rz_106613 = _106611 + _106612; double rx_106600; rx_106600 = _106598 + _106599; double ry_106606; ry_106606 = _106604 + _106605; double _106614; _106614 = _105301 * rz_106613; double _106601; _106601 = _105276 * rx_106600; double _106607; _106607 = _105289 * ry_106606; double _106608; _106608 = _106601 + _106607; double _106615; _106615 = _106608 + _106614; double _106616; _106616 = _106615 * _106615; double D_106617; D_106617 = _106616 - C_105317; bool _106618; _106618 = 0.000000e+00 < D_106617; if (_106618) goto l106619; else goto l107109; l107109: ; goto l107106; l106619: ; _106622 = sqrt(D_106617); p_106622 = _106622; l106620: ; _106622 = p_106622; double _106623; _106623 = -0.000000e+00 - _106615; double t_106624; t_106624 = _106623 - _106622; bool _106625; _106625 = 0.000000e+00 < t_106624; if (_106625) goto l106626; else goto l107108; l107108: ; goto l107105; l106626: ; bool _106627; _106627 = t_106624 < 1.000000e+17; if (_106627) goto l106628; else goto l107104; l107104: ; goto l107105; l107105: ; goto l107106; l107106: ; struct_Isect_9647 _107049_907; _107049_907.e0 = 1.000000e+17; // bottom: _107049_907.e1 = // bottom: struct_vec_9645 _107047_911;; // bottom: _107049_907.e2 = _107047_911; _107049_907.e3 = 0; pray_sphere_intersect_106656 = _107049_907; goto l106654; l106628: ; double _106633; _106633 = ry_106606 * t_106624; double _106634; _106634 = _105288 + _106633; double _106629; _106629 = rx_106600 * t_106624; double _106638; _106638 = rz_106613 * t_106624; double _106635; _106635 = _106634 - 0.000000e+00; double _106630; _106630 = _105275 + _106629; double _106639; _106639 = _105300 + _106638; double _106636; _106636 = _106635 * _106635; double _106631; _106631 = _106630 - -2.000000e+00; double _106640; _106640 = _106639 - -3.500000e+00; double _106632; _106632 = _106631 * _106631; double _106641; _106641 = _106640 * _106640; double _106637; _106637 = _106632 + _106636; double _106642; _106642 = _106637 + _106641; length_106645 = sqrt(_106642); plength_106645 = length_106645; l106643: ; length_106645 = plength_106645; _106648 = fabs(length_106645); p_106648 = _106648; l106646: ; _106648 = p_106648; bool _106649; _106649 = 1.000000e-17 < _106648; if (_106649) goto l106650; else goto l107102; l107102: ; struct_vec_9645 n_107103; n_107103.e0 = _106631; n_107103.e1 = _106635; n_107103.e2 = _106640; pvnormalize_106653 = n_107103; goto l106651; l106650: ; double _107099; _107099 = _106635 / length_106645; double _107098; _107098 = _106631 / length_106645; double _107100; _107100 = _106640 / length_106645; struct_vec_9645 _107101; _107101.e0 = _107098; _107101.e1 = _107099; _107101.e2 = _107100; pvnormalize_106653 = _107101; goto l106651; l106651: ; vnormalize_106653 = pvnormalize_106653; struct_vec_9645 p_107096; p_107096.e0 = _106630; p_107096.e1 = _106634; p_107096.e2 = _106639; struct_Isect_9647 isect_107097; isect_107097.e0 = t_106624; isect_107097.e1 = p_107096; isect_107097.e2 = vnormalize_106653; isect_107097.e3 = 1; pray_sphere_intersect_106656 = isect_107097; goto l106654; l106654: ; ray_sphere_intersect_106656 = pray_sphere_intersect_106656; double _106659; _106659 = _105361 * rz_106613; double _106657; _106657 = _105358 * rx_106600; double _106658; _106658 = _106657 + _106607; double _106660; _106660 = _106658 + _106659; double _106661; _106661 = _106660 * _106660; double D_106662; D_106662 = _106661 - C_105369; bool _106663; _106663 = 0.000000e+00 < D_106662; if (_106663) goto l106664; else goto l107095; l107095: ; goto l107092; l106664: ; _106667 = sqrt(D_106662); p_106667 = _106667; l106665: ; _106667 = p_106667; double _106668; _106668 = -0.000000e+00 - _106660; double t_106669; t_106669 = _106668 - _106667; bool _106670; _106670 = 0.000000e+00 < t_106669; if (_106670) goto l106671; else goto l107094; l107094: ; goto l107091; l106671: ; double _106672; _106672 = ray_sphere_intersect_106656.e0; bool _106673; _106673 = t_106669 < _106672; if (_106673) goto l106674; else goto l107090; l107090: ; goto l107091; l107091: ; goto l107092; l107092: ; pray_sphere_intersect_106702 = ray_sphere_intersect_106656; goto l106700; l106674: ; double _106684; _106684 = rz_106613 * t_106669; double _106675; _106675 = rx_106600 * t_106669; double _106679; _106679 = ry_106606 * t_106669; double _106685; _106685 = _105300 + _106684; double _106676; _106676 = _105275 + _106675; double _106680; _106680 = _105288 + _106679; double _106686; _106686 = _106685 - -3.000000e+00; double _106677; _106677 = _106676 - -5.000000e-01; double _106681; _106681 = _106680 - 0.000000e+00; double _106687; _106687 = _106686 * _106686; double _106678; _106678 = _106677 * _106677; double _106682; _106682 = _106681 * _106681; double _106683; _106683 = _106678 + _106682; double _106688; _106688 = _106683 + _106687; length_106691 = sqrt(_106688); plength_106691 = length_106691; l106689: ; length_106691 = plength_106691; _106694 = fabs(length_106691); p_106694 = _106694; l106692: ; _106694 = p_106694; bool _106695; _106695 = 1.000000e-17 < _106694; if (_106695) goto l106696; else goto l107088; l107088: ; struct_vec_9645 n_107089; n_107089.e0 = _106677; n_107089.e1 = _106681; n_107089.e2 = _106686; pvnormalize_106699 = n_107089; goto l106697; l106696: ; double _107084; _107084 = _106677 / length_106691; double _107085; _107085 = _106681 / length_106691; double _107086; _107086 = _106686 / length_106691; struct_vec_9645 _107087; _107087.e0 = _107084; _107087.e1 = _107085; _107087.e2 = _107086; pvnormalize_106699 = _107087; goto l106697; l106697: ; vnormalize_106699 = pvnormalize_106699; struct_vec_9645 p_107082; p_107082.e0 = _106676; p_107082.e1 = _106680; p_107082.e2 = _106685; struct_Isect_9647 isect_107083; isect_107083.e0 = t_106669; isect_107083.e1 = p_107082; isect_107083.e2 = vnormalize_106699; isect_107083.e3 = 1; pray_sphere_intersect_106702 = isect_107083; goto l106700; l106700: ; ray_sphere_intersect_106702 = pray_sphere_intersect_106702; double _106705; _106705 = _105414 * rz_106613; double _106703; _106703 = _105411 * rx_106600; double _106704; _106704 = _106703 + _106607; double _106706; _106706 = _106704 + _106705; double _106707; _106707 = _106706 * _106706; double D_106708; D_106708 = _106707 - C_105422; bool _106709; _106709 = 0.000000e+00 < D_106708; if (_106709) goto l106710; else goto l107081; l107081: ; goto l107078; l106710: ; _106713 = sqrt(D_106708); p_106713 = _106713; l106711: ; _106713 = p_106713; double _106714; _106714 = -0.000000e+00 - _106706; double t_106715; t_106715 = _106714 - _106713; bool _106716; _106716 = 0.000000e+00 < t_106715; if (_106716) goto l106717; else goto l107080; l107080: ; goto l107077; l106717: ; double _106718; _106718 = ray_sphere_intersect_106702.e0; bool _106719; _106719 = t_106715 < _106718; if (_106719) goto l106720; else goto l107076; l107076: ; goto l107077; l107077: ; goto l107078; l107078: ; pray_sphere_intersect_106748 = ray_sphere_intersect_106702; goto l106746; l106720: ; double _106730; _106730 = rz_106613 * t_106715; double _106721; _106721 = rx_106600 * t_106715; double _106725; _106725 = ry_106606 * t_106715; double _106726; _106726 = _105288 + _106725; double _106727; _106727 = _106726 - 0.000000e+00; double _106722; _106722 = _105275 + _106721; double _106723; _106723 = _106722 - 1.000000e+00; double _106731; _106731 = _105300 + _106730; double _106732; _106732 = _106731 - -2.200000e+00; double _106728; _106728 = _106727 * _106727; double _106724; _106724 = _106723 * _106723; double _106733; _106733 = _106732 * _106732; double _106729; _106729 = _106724 + _106728; double _106734; _106734 = _106729 + _106733; length_106737 = sqrt(_106734); plength_106737 = length_106737; l106735: ; length_106737 = plength_106737; _106740 = fabs(length_106737); p_106740 = _106740; l106738: ; _106740 = p_106740; bool _106741; _106741 = 1.000000e-17 < _106740; if (_106741) goto l106742; else goto l107074; l107074: ; struct_vec_9645 n_107075; n_107075.e0 = _106723; n_107075.e1 = _106727; n_107075.e2 = _106732; pvnormalize_106745 = n_107075; goto l106743; l106742: ; double _107072; _107072 = _106732 / length_106737; double _107070; _107070 = _106723 / length_106737; double _107071; _107071 = _106727 / length_106737; struct_vec_9645 _107073; _107073.e0 = _107070; _107073.e1 = _107071; _107073.e2 = _107072; pvnormalize_106745 = _107073; goto l106743; l106743: ; vnormalize_106745 = pvnormalize_106745; struct_vec_9645 p_107068; p_107068.e0 = _106722; p_107068.e1 = _106726; p_107068.e2 = _106731; struct_Isect_9647 isect_107069; isect_107069.e0 = t_106715; isect_107069.e1 = p_107068; isect_107069.e2 = vnormalize_106745; isect_107069.e3 = 1; pray_sphere_intersect_106748 = isect_107069; goto l106746; l106746: ; ray_sphere_intersect_106748 = pray_sphere_intersect_106748; double _106749; _106749 = 0.000000e+00 * rx_106600; double _106752; _106752 = 0.000000e+00 * rz_106613; double _106750; _106750 = 1.000000e+00 * ry_106606; double _106751; _106751 = _106749 + _106750; double _106753; _106753 = _106751 + _106752; _106756 = fabs(_106753); p_106756 = _106756; l106754: ; _106756 = p_106756; bool _106757; _106757 = 1.000000e-17 <= _106756; if (_106757) goto l106758; else goto l107067; l107067: ; goto l107064; l106758: ; double t_106759; t_106759 = _105480 / _106753; bool _106760; _106760 = 0.000000e+00 < t_106759; if (_106760) goto l106761; else goto l107066; l107066: ; goto l107063; l106761: ; double _106762; _106762 = ray_sphere_intersect_106748.e0; bool _106763; _106763 = t_106759 < _106762; if (_106763) goto l106764; else goto l107062; l107062: ; goto l107063; l107063: ; goto l107064; l107064: ; pray_plane_intersect_106767 = ray_sphere_intersect_106748; goto l106765; l106764: ; double _107054; _107054 = rx_106600 * t_106759; double _107056; _107056 = ry_106606 * t_106759; double _107055; _107055 = _105275 + _107054; double _107057; _107057 = _105288 + _107056; double _107058; _107058 = rz_106613 * t_106759; double _107059; _107059 = _105300 + _107058; struct_vec_9645 p_107060; p_107060.e0 = _107055; p_107060.e1 = _107057; p_107060.e2 = _107059; struct_vec_9645 _106999_986; _106999_986.e0 = 0.000000e+00; _106999_986.e1 = 1.000000e+00; _106999_986.e2 = 0.000000e+00; struct_Isect_9647 isect_107061; isect_107061.e0 = t_106759; isect_107061.e1 = p_107060; isect_107061.e2 = _106999_986; isect_107061.e3 = 1; pray_plane_intersect_106767 = isect_107061; goto l106765; l106765: ; ray_plane_intersect_106767 = pray_plane_intersect_106767; int _106768; _106768 = ray_plane_intersect_106767.e3; bool _106769; _106769 = _106768 == 1; if (_106769) goto l106770; else goto l107053; l107053: ; pocclusion_106773 = occlusion_106560; goto l106771; l106770: ; double _107052; _107052 = 1.000000e+00 + occlusion_106560; pocclusion_106773 = _107052; goto l106771; l106771: ; occlusion_106773 = pocclusion_106773; unsigned long _106774; _106774 = 4294883355 * lo_106575; unsigned long _106775; _106775 = _106774 + hi_106577; unsigned long hi_106778; hi_106778 = _106775 >> 32; unsigned long lo_106776; lo_106776 = 4294967295 & _106775; unsigned int _106779; _106779 = (unsigned int)hi_106778; unsigned int _106777; _106777 = (unsigned int)lo_106776; unsigned int _106780; _106780 = _106777 ^ _106779; double _106781; _106781 = (double)_106780; double _106782; _106782 = 2.328306e-10 * _106781; theta_106785 = sqrt(_106782); ptheta_106785 = theta_106785; l106783: ; theta_106785 = ptheta_106785; unsigned long _106786; _106786 = 4294883355 * lo_106776; unsigned long _106787; _106787 = _106786 + hi_106778; unsigned long hi_106790; hi_106790 = _106787 >> 32; unsigned long lo_106788; lo_106788 = 4294967295 & _106787; unsigned int _106791; _106791 = (unsigned int)hi_106790; unsigned int _106789; _106789 = (unsigned int)lo_106788; unsigned int _106792; _106792 = _106789 ^ _106791; double _106793; _106793 = (double)_106792; double _106794; _106794 = 2.328306e-10 * _106793; double phi_106795; phi_106795 = 6.283185e+00 * _106794; _106798 = cos(phi_106795); p_106798 = _106798; l106796: ; _106798 = p_106798; _106801 = sin(phi_106795); p_106801 = _106801; l106799: ; _106801 = p_106801; double _106802; _106802 = theta_106785 * theta_106785; double _106803; _106803 = 1.000000e+00 - _106802; z_106806 = sqrt(_106803); pz_106806 = z_106806; l106804: ; z_106806 = pz_106806; double x_106807; x_106807 = _106798 * theta_106785; double y_106809; y_106809 = _106801 * theta_106785; double _106815; _106815 = x_106807 * _105192; double _106823; _106823 = y_106809 * _105303; double _106812; _106812 = z_106806 * _105152; double _106810; _106810 = y_106809 * _105280; double _106822; _106822 = x_106807 * _105190; double _106824; _106824 = _106822 + _106823; double _106825; _106825 = z_106806 * _105163; double _106818; _106818 = z_106806 * _105165; double _106816; _106816 = y_106809 * _105291; double _106808; _106808 = x_106807 * _105196; double _106817; _106817 = _106815 + _106816; double _106811; _106811 = _106808 + _106810; double rz_106826; rz_106826 = _106824 + _106825; double ry_106819; ry_106819 = _106817 + _106818; double rx_106813; rx_106813 = _106811 + _106812; double _106827; _106827 = _105301 * rz_106826; double _106820; _106820 = _105289 * ry_106819; double _106814; _106814 = _105276 * rx_106813; double _106821; _106821 = _106814 + _106820; double _106828; _106828 = _106821 + _106827; double _106829; _106829 = _106828 * _106828; double D_106830; D_106830 = _106829 - C_105317; bool _106831; _106831 = 0.000000e+00 < D_106830; if (_106831) goto l106832; else goto l107051; l107051: ; goto l107045; l106832: ; _106835 = sqrt(D_106830); p_106835 = _106835; l106833: ; _106835 = p_106835; double _106836; _106836 = -0.000000e+00 - _106828; double t_106837; t_106837 = _106836 - _106835; bool _106838; _106838 = 0.000000e+00 < t_106837; if (_106838) goto l106839; else goto l107050; l107050: ; goto l107044; l106839: ; bool _106840; _106840 = t_106837 < 1.000000e+17; if (_106840) goto l106841; else goto l107043; l107043: ; goto l107044; l107044: ; goto l107045; l107045: ; struct_Isect_9647 _107049_1015; _107049_1015.e0 = 1.000000e+17; // bottom: _107049_1015.e1 = // bottom: struct_vec_9645 _107047_1019;; // bottom: _107049_1015.e2 = _107047_1019; _107049_1015.e3 = 0; pray_sphere_intersect_106869 = _107049_1015; goto l106867; l106841: ; double _106846; _106846 = ry_106819 * t_106837; double _106847; _106847 = _105288 + _106846; double _106842; _106842 = rx_106813 * t_106837; double _106851; _106851 = rz_106826 * t_106837; double _106848; _106848 = _106847 - 0.000000e+00; double _106843; _106843 = _105275 + _106842; double _106852; _106852 = _105300 + _106851; double _106849; _106849 = _106848 * _106848; double _106844; _106844 = _106843 - -2.000000e+00; double _106853; _106853 = _106852 - -3.500000e+00; double _106845; _106845 = _106844 * _106844; double _106854; _106854 = _106853 * _106853; double _106850; _106850 = _106845 + _106849; double _106855; _106855 = _106850 + _106854; length_106858 = sqrt(_106855); plength_106858 = length_106858; l106856: ; length_106858 = plength_106858; _106861 = fabs(length_106858); p_106861 = _106861; l106859: ; _106861 = p_106861; bool _106862; _106862 = 1.000000e-17 < _106861; if (_106862) goto l106863; else goto l107041; l107041: ; struct_vec_9645 n_107042; n_107042.e0 = _106844; n_107042.e1 = _106848; n_107042.e2 = _106853; pvnormalize_106866 = n_107042; goto l106864; l106863: ; double _107038; _107038 = _106848 / length_106858; double _107039; _107039 = _106853 / length_106858; double _107037; _107037 = _106844 / length_106858; struct_vec_9645 _107040; _107040.e0 = _107037; _107040.e1 = _107038; _107040.e2 = _107039; pvnormalize_106866 = _107040; goto l106864; l106864: ; vnormalize_106866 = pvnormalize_106866; struct_vec_9645 p_107035; p_107035.e0 = _106843; p_107035.e1 = _106847; p_107035.e2 = _106852; struct_Isect_9647 isect_107036; isect_107036.e0 = t_106837; isect_107036.e1 = p_107035; isect_107036.e2 = vnormalize_106866; isect_107036.e3 = 1; pray_sphere_intersect_106869 = isect_107036; goto l106867; l106867: ; ray_sphere_intersect_106869 = pray_sphere_intersect_106869; double _106872; _106872 = _105361 * rz_106826; double _106870; _106870 = _105358 * rx_106813; double _106871; _106871 = _106870 + _106820; double _106873; _106873 = _106871 + _106872; double _106874; _106874 = _106873 * _106873; double D_106875; D_106875 = _106874 - C_105369; bool _106876; _106876 = 0.000000e+00 < D_106875; if (_106876) goto l106877; else goto l107034; l107034: ; goto l107031; l106877: ; _106880 = sqrt(D_106875); p_106880 = _106880; l106878: ; _106880 = p_106880; double _106881; _106881 = -0.000000e+00 - _106873; double t_106882; t_106882 = _106881 - _106880; bool _106883; _106883 = 0.000000e+00 < t_106882; if (_106883) goto l106884; else goto l107033; l107033: ; goto l107030; l106884: ; double _106885; _106885 = ray_sphere_intersect_106869.e0; bool _106886; _106886 = t_106882 < _106885; if (_106886) goto l106887; else goto l107029; l107029: ; goto l107030; l107030: ; goto l107031; l107031: ; pray_sphere_intersect_106915 = ray_sphere_intersect_106869; goto l106913; l106887: ; double _106892; _106892 = ry_106819 * t_106882; double _106888; _106888 = rx_106813 * t_106882; double _106889; _106889 = _105275 + _106888; double _106890; _106890 = _106889 - -5.000000e-01; double _106897; _106897 = rz_106826 * t_106882; double _106893; _106893 = _105288 + _106892; double _106891; _106891 = _106890 * _106890; double _106898; _106898 = _105300 + _106897; double _106894; _106894 = _106893 - 0.000000e+00; double _106899; _106899 = _106898 - -3.000000e+00; double _106895; _106895 = _106894 * _106894; double _106900; _106900 = _106899 * _106899; double _106896; _106896 = _106891 + _106895; double _106901; _106901 = _106896 + _106900; length_106904 = sqrt(_106901); plength_106904 = length_106904; l106902: ; length_106904 = plength_106904; _106907 = fabs(length_106904); p_106907 = _106907; l106905: ; _106907 = p_106907; bool _106908; _106908 = 1.000000e-17 < _106907; if (_106908) goto l106909; else goto l107027; l107027: ; struct_vec_9645 n_107028; n_107028.e0 = _106890; n_107028.e1 = _106894; n_107028.e2 = _106899; pvnormalize_106912 = n_107028; goto l106910; l106909: ; double _107023; _107023 = _106890 / length_106904; double _107024; _107024 = _106894 / length_106904; double _107025; _107025 = _106899 / length_106904; struct_vec_9645 _107026; _107026.e0 = _107023; _107026.e1 = _107024; _107026.e2 = _107025; pvnormalize_106912 = _107026; goto l106910; l106910: ; vnormalize_106912 = pvnormalize_106912; struct_vec_9645 p_107021; p_107021.e0 = _106889; p_107021.e1 = _106893; p_107021.e2 = _106898; struct_Isect_9647 isect_107022; isect_107022.e0 = t_106882; isect_107022.e1 = p_107021; isect_107022.e2 = vnormalize_106912; isect_107022.e3 = 1; pray_sphere_intersect_106915 = isect_107022; goto l106913; l106913: ; ray_sphere_intersect_106915 = pray_sphere_intersect_106915; double _106918; _106918 = _105414 * rz_106826; double _106916; _106916 = _105411 * rx_106813; double _106917; _106917 = _106916 + _106820; double _106919; _106919 = _106917 + _106918; double _106920; _106920 = _106919 * _106919; double D_106921; D_106921 = _106920 - C_105422; bool _106922; _106922 = 0.000000e+00 < D_106921; if (_106922) goto l106923; else goto l107020; l107020: ; goto l107017; l106923: ; _106926 = sqrt(D_106921); p_106926 = _106926; l106924: ; _106926 = p_106926; double _106927; _106927 = -0.000000e+00 - _106919; double t_106928; t_106928 = _106927 - _106926; bool _106929; _106929 = 0.000000e+00 < t_106928; if (_106929) goto l106930; else goto l107019; l107019: ; goto l107016; l106930: ; double _106931; _106931 = ray_sphere_intersect_106915.e0; bool _106932; _106932 = t_106928 < _106931; if (_106932) goto l106933; else goto l107015; l107015: ; goto l107016; l107016: ; goto l107017; l107017: ; pray_sphere_intersect_106961 = ray_sphere_intersect_106915; goto l106959; l106933: ; double _106934; _106934 = rx_106813 * t_106928; double _106943; _106943 = rz_106826 * t_106928; double _106938; _106938 = ry_106819 * t_106928; double _106944; _106944 = _105300 + _106943; double _106935; _106935 = _105275 + _106934; double _106939; _106939 = _105288 + _106938; double _106945; _106945 = _106944 - -2.200000e+00; double _106936; _106936 = _106935 - 1.000000e+00; double _106940; _106940 = _106939 - 0.000000e+00; double _106946; _106946 = _106945 * _106945; double _106937; _106937 = _106936 * _106936; double _106941; _106941 = _106940 * _106940; double _106942; _106942 = _106937 + _106941; double _106947; _106947 = _106942 + _106946; length_106950 = sqrt(_106947); plength_106950 = length_106950; l106948: ; length_106950 = plength_106950; _106953 = fabs(length_106950); p_106953 = _106953; l106951: ; _106953 = p_106953; bool _106954; _106954 = 1.000000e-17 < _106953; if (_106954) goto l106955; else goto l107013; l107013: ; struct_vec_9645 n_107014; n_107014.e0 = _106936; n_107014.e1 = _106940; n_107014.e2 = _106945; pvnormalize_106958 = n_107014; goto l106956; l106955: ; double _107011; _107011 = _106945 / length_106950; double _107010; _107010 = _106940 / length_106950; double _107009; _107009 = _106936 / length_106950; struct_vec_9645 _107012; _107012.e0 = _107009; _107012.e1 = _107010; _107012.e2 = _107011; pvnormalize_106958 = _107012; goto l106956; l106956: ; vnormalize_106958 = pvnormalize_106958; struct_vec_9645 p_107007; p_107007.e0 = _106935; p_107007.e1 = _106939; p_107007.e2 = _106944; struct_Isect_9647 isect_107008; isect_107008.e0 = t_106928; isect_107008.e1 = p_107007; isect_107008.e2 = vnormalize_106958; isect_107008.e3 = 1; pray_sphere_intersect_106961 = isect_107008; goto l106959; l106959: ; ray_sphere_intersect_106961 = pray_sphere_intersect_106961; double _106965; _106965 = 0.000000e+00 * rz_106826; double _106963; _106963 = 1.000000e+00 * ry_106819; double _106962; _106962 = 0.000000e+00 * rx_106813; double _106964; _106964 = _106962 + _106963; double _106966; _106966 = _106964 + _106965; _106969 = fabs(_106966); p_106969 = _106969; l106967: ; _106969 = p_106969; bool _106970; _106970 = 1.000000e-17 <= _106969; if (_106970) goto l106971; else goto l107006; l107006: ; goto l107003; l106971: ; double t_106972; t_106972 = _105480 / _106966; bool _106973; _106973 = 0.000000e+00 < t_106972; if (_106973) goto l106974; else goto l107005; l107005: ; goto l107002; l106974: ; double _106975; _106975 = ray_sphere_intersect_106961.e0; bool _106976; _106976 = t_106972 < _106975; if (_106976) goto l106977; else goto l107001; l107001: ; goto l107002; l107002: ; goto l107003; l107003: ; pray_plane_intersect_106980 = ray_sphere_intersect_106961; goto l106978; l106977: ; double _106996; _106996 = rz_106826 * t_106972; double _106992; _106992 = rx_106813 * t_106972; double _106997; _106997 = _105300 + _106996; double _106994; _106994 = ry_106819 * t_106972; double _106993; _106993 = _105275 + _106992; double _106995; _106995 = _105288 + _106994; struct_vec_9645 p_106998; p_106998.e0 = _106993; p_106998.e1 = _106995; p_106998.e2 = _106997; struct_vec_9645 _106999_1094; _106999_1094.e0 = 0.000000e+00; _106999_1094.e1 = 1.000000e+00; _106999_1094.e2 = 0.000000e+00; struct_Isect_9647 isect_107000; isect_107000.e0 = t_106972; isect_107000.e1 = p_106998; isect_107000.e2 = _106999_1094; isect_107000.e3 = 1; pray_plane_intersect_106980 = isect_107000; goto l106978; l106978: ; ray_plane_intersect_106980 = pray_plane_intersect_106980; int _106981; _106981 = ray_plane_intersect_106980.e3; bool _106982; _106982 = _106981 == 1; if (_106982) goto l106983; else goto l106991; l106991: ; pocclusion_106986 = occlusion_106773; goto l106984; l106983: ; double _106990; _106990 = 1.000000e+00 + occlusion_106773; pocclusion_106986 = _106990; goto l106984; l106984: ; occlusion_106986 = pocclusion_106986; int _106987; _106987 = lower_105220 + step_105222; unsigned long _106988; _106988 = 4294883355 * lo_106788; unsigned long _106989; _106989 = _106988 + hi_106790; plower_105220 = _106987; pupper_105221 = upper_105221; pstep_105222 = step_105222; pocclusion_105223 = occlusion_106986; pstate_105224 = _106989; goto l105218; } }
026e121806b77fc52421aa0b58c3805fc152ff24.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <stdlib.h> #include <math.h> #include <hip/hip_runtime.h> //#include "d_colorToGreyscale.h" #include "CHECK.h" #include "config.h" __global__ void d_convLayerForwardKernel(int, int, int, unsigned char *, int, float *, float *); __device__ void printVector(float * array, int width); __device__ void printCharVector(unsigned char * array, int width); /** * Performs one forward run through the network * @param Pin input image * @param resulting vector * @param size of input image */ void d_convLayerForward(unsigned char * inputMap, float * outputMap, float * weights, int inputLen, int numInput, int weightLen) { //Create device vectors unsigned char * d_inputMap; float * d_weights; float * d_outputMap; int inSize = sizeof(unsigned char)*inputLen*inputLen*numInput; int outputSize = sizeof(float)*(inputLen-weightLen-1)*(inputLen-weightLen-1); int weightSize = sizeof(float)*weightLen*weightLen; CHECK(hipMalloc((void **)&d_outputMap, outputSize)); CHECK(hipMalloc((void **)&d_weights, weightSize)); CHECK(hipMalloc((void **)&d_inputMap, inSize)); CHECK(hipMemcpy(d_inputMap, inputMap, inSize, hipMemcpyHostToDevice)); CHECK(hipMemcpy(d_weights, weights, weightSize, hipMemcpyHostToDevice)); //Launch int outSize = inputLen - (weightLen-1); int gridSize = ceil(outSize/TILEWIDTH); int gridZ = gridSize * gridSize; dim3 blockDim(TILEWIDTH, TILEWIDTH, 1); dim3 gridDim(gridSize, gridSize, gridZ); size_t shmemSize = sizeof(float) * ((TILEWIDTH + weightLen-1)*(TILEWIDTH + weightLen-1) + weightLen*weightLen); //Launch hipLaunchKernelGGL(( d_convLayerForwardKernel), dim3(gridDim), dim3(blockDim), shmemSize, 0, gridSize, numInput, weightLen, d_inputMap, inputLen, d_weights, d_outputMap); CHECK(hipDeviceSynchronize()); CHECK(hipMemcpy(outputMap, d_outputMap, outputSize, hipMemcpyDeviceToHost)); CHECK(hipFree(d_outputMap)); CHECK(hipFree(d_inputMap)); CHECK(hipFree(d_weights)); } /** * Convolutes a set of input feature maps into a set * of output feature maps * @param W_grid width of grid * @param numOutput number of output elements * @param numInput number of input elements * @param inputMap input feature maps * @param weights to apply to each input map * @param outputMap */ __global__ void d_convLayerForwardKernel(int gridWidth, int numInput, int weightLen, unsigned char * inputMap, int inputLen, float * weights, float * outputMap) { int n, m, h_base, w_base, h, w; int xTileWidth = TILEWIDTH + weightLen-1; int iWeight = xTileWidth * xTileWidth; extern __shared__ float shmem[]; float * inputShared = &shmem[0]; float * weightShared = &shmem[iWeight]; n = blockIdx.x; m = blockIdx.y; h_base = (blockIdx.z / gridWidth) * TILEWIDTH; //vertical base out data index for the block w_base = (blockIdx.z % gridWidth) * TILEWIDTH; // horizontal base out data index for the block h = h_base + threadIdx.x; w = w_base + threadIdx.y; float acc = 0.; int c, i, j, p, q; //Add over all channels for (c = 0; c < numInput; c++) { //Load weight vector into shared memory int wIndex = threadIdx.x*TILEWIDTH+threadIdx.y; if (wIndex < weightLen*weightLen) { weightShared[threadIdx.x*TILEWIDTH+threadIdx.y] = weights[(c+numInput*(threadIdx.x*TILEWIDTH+threadIdx.y))]; //m,c,tIdx,tIdy } __syncthreads(); //Load input map into shared memory for (i = h; i < h_base + xTileWidth; i += TILEWIDTH) { for (j = w; j < w_base + xTileWidth; j += TILEWIDTH){ inputShared[(i-h_base)*TILEWIDTH+(j-w_base)] = ((float) inputMap[n+gridWidth*(c+numInput*(h+TILEWIDTH*w))]); //n,c,h,w } } __syncthreads(); //Accumulate input and weight vectors for (p = 0; p < weightLen; p++) { for (q = 0; q < weightLen; q++) { acc += inputShared[(h+p)*TILEWIDTH+(w+q)] * weightShared[p*weightLen+q]; } } __syncthreads(); } //Load into output outputMap[n+gridWidth*(m+gridWidth*(h+TILEWIDTH*w))] = acc; //n,m,h,w } __device__ void printVector(float * array, int width) { for (int i = 0; i < width*width; i++) { if (!(i%width)) printf("\n%2d:", i/width); printf("%6.1f", array[i]); } printf("\n"); } __device__ void printCharVector(unsigned char * array, int width) { for (int i = 0; i < width*width; i++) { if (!(i%width)) printf("\n%2d:", i/width); printf("%4.1d", array[i]); } printf("\n"); }
026e121806b77fc52421aa0b58c3805fc152ff24.cu
#include <stdio.h> #include <stdlib.h> #include <math.h> #include <cuda_runtime.h> //#include "d_colorToGreyscale.h" #include "CHECK.h" #include "config.h" __global__ void d_convLayerForwardKernel(int, int, int, unsigned char *, int, float *, float *); __device__ void printVector(float * array, int width); __device__ void printCharVector(unsigned char * array, int width); /** * Performs one forward run through the network * @param Pin input image * @param resulting vector * @param size of input image */ void d_convLayerForward(unsigned char * inputMap, float * outputMap, float * weights, int inputLen, int numInput, int weightLen) { //Create device vectors unsigned char * d_inputMap; float * d_weights; float * d_outputMap; int inSize = sizeof(unsigned char)*inputLen*inputLen*numInput; int outputSize = sizeof(float)*(inputLen-weightLen-1)*(inputLen-weightLen-1); int weightSize = sizeof(float)*weightLen*weightLen; CHECK(cudaMalloc((void **)&d_outputMap, outputSize)); CHECK(cudaMalloc((void **)&d_weights, weightSize)); CHECK(cudaMalloc((void **)&d_inputMap, inSize)); CHECK(cudaMemcpy(d_inputMap, inputMap, inSize, cudaMemcpyHostToDevice)); CHECK(cudaMemcpy(d_weights, weights, weightSize, cudaMemcpyHostToDevice)); //Launch int outSize = inputLen - (weightLen-1); int gridSize = ceil(outSize/TILEWIDTH); int gridZ = gridSize * gridSize; dim3 blockDim(TILEWIDTH, TILEWIDTH, 1); dim3 gridDim(gridSize, gridSize, gridZ); size_t shmemSize = sizeof(float) * ((TILEWIDTH + weightLen-1)*(TILEWIDTH + weightLen-1) + weightLen*weightLen); //Launch d_convLayerForwardKernel<<<gridDim, blockDim, shmemSize>>>(gridSize, numInput, weightLen, d_inputMap, inputLen, d_weights, d_outputMap); CHECK(cudaDeviceSynchronize()); CHECK(cudaMemcpy(outputMap, d_outputMap, outputSize, cudaMemcpyDeviceToHost)); CHECK(cudaFree(d_outputMap)); CHECK(cudaFree(d_inputMap)); CHECK(cudaFree(d_weights)); } /** * Convolutes a set of input feature maps into a set * of output feature maps * @param W_grid width of grid * @param numOutput number of output elements * @param numInput number of input elements * @param inputMap input feature maps * @param weights to apply to each input map * @param outputMap */ __global__ void d_convLayerForwardKernel(int gridWidth, int numInput, int weightLen, unsigned char * inputMap, int inputLen, float * weights, float * outputMap) { int n, m, h_base, w_base, h, w; int xTileWidth = TILEWIDTH + weightLen-1; int iWeight = xTileWidth * xTileWidth; extern __shared__ float shmem[]; float * inputShared = &shmem[0]; float * weightShared = &shmem[iWeight]; n = blockIdx.x; m = blockIdx.y; h_base = (blockIdx.z / gridWidth) * TILEWIDTH; //vertical base out data index for the block w_base = (blockIdx.z % gridWidth) * TILEWIDTH; // horizontal base out data index for the block h = h_base + threadIdx.x; w = w_base + threadIdx.y; float acc = 0.; int c, i, j, p, q; //Add over all channels for (c = 0; c < numInput; c++) { //Load weight vector into shared memory int wIndex = threadIdx.x*TILEWIDTH+threadIdx.y; if (wIndex < weightLen*weightLen) { weightShared[threadIdx.x*TILEWIDTH+threadIdx.y] = weights[(c+numInput*(threadIdx.x*TILEWIDTH+threadIdx.y))]; //m,c,tIdx,tIdy } __syncthreads(); //Load input map into shared memory for (i = h; i < h_base + xTileWidth; i += TILEWIDTH) { for (j = w; j < w_base + xTileWidth; j += TILEWIDTH){ inputShared[(i-h_base)*TILEWIDTH+(j-w_base)] = ((float) inputMap[n+gridWidth*(c+numInput*(h+TILEWIDTH*w))]); //n,c,h,w } } __syncthreads(); //Accumulate input and weight vectors for (p = 0; p < weightLen; p++) { for (q = 0; q < weightLen; q++) { acc += inputShared[(h+p)*TILEWIDTH+(w+q)] * weightShared[p*weightLen+q]; } } __syncthreads(); } //Load into output outputMap[n+gridWidth*(m+gridWidth*(h+TILEWIDTH*w))] = acc; //n,m,h,w } __device__ void printVector(float * array, int width) { for (int i = 0; i < width*width; i++) { if (!(i%width)) printf("\n%2d:", i/width); printf("%6.1f", array[i]); } printf("\n"); } __device__ void printCharVector(unsigned char * array, int width) { for (int i = 0; i < width*width; i++) { if (!(i%width)) printf("\n%2d:", i/width); printf("%4.1d", array[i]); } printf("\n"); }
d51238c34650438997e7952382a13a211292446e.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* This is the central piece of code. This file implements a class (interface in gpuadder.hh) that takes data in on the cpu side, copies it to the gpu, and exposes functions (increment and retreive) that let you perform actions with the GPU This class will get translated into python via swig */ #include <kernel.cu> #include <AAK_manager.hh> #include <assert.h> #include <iostream> #include <stdlib.h> #include "hip/hip_complex.h" #include "rocblas.h" #include <hipfft.h> #include <complex.h> #include "Globals.h" #include "GKTrajFast.h" #include "KSParMap.h" #include "KSTools.h" #include "AAK.h" #include "interpolate.cu" using namespace std; #define BATCH 1 #define gpuErrchk(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); } } GPUAAK::GPUAAK (double T_fit_, int init_length_, int length_, double init_dt_, double dt_, bool LISA_, bool backint_, cmplx *data_channel1_, cmplx *data_channel2_, double *noise_channel1_inv_, double *noise_channel2_inv_){ T_fit = T_fit_; init_length = init_length_; length = length_; init_dt = init_dt_; dt = dt_; LISA = LISA_; backint = backint_; data_channel1 = data_channel1_; data_channel2 = data_channel2_; noise_channel1_inv = noise_channel1_inv_; noise_channel2_inv = noise_channel2_inv_; to_gpu = 1; fft_length = ((int) (length/2)) + 1; hipError_t err; // DECLARE ALL THE NECESSARY STRUCTS tvec = new double[init_length+1]; evec = new double[init_length+1]; vvec = new double[init_length+1]; Mvec = new double[init_length+1]; Svec = new double[init_length+1]; gimvec = new double[init_length+1]; Phivec = new double[init_length+1]; alpvec = new double[init_length+1]; nuvec = new double[init_length+1]; gimdotvec = new double[init_length+1]; size_t numBytes_ = 0; trajectories = createInterpArrayContainer(&numBytes_, 9, init_length+1); numBytes = numBytes_; d_trajectories = createInterpArrayContainer_gpu(numBytes); d_evec = trajectories[0]; d_vvec = trajectories[1]; d_Mvec = trajectories[2]; d_Svec = trajectories[3]; d_gimvec = trajectories[4]; d_Phivec = trajectories[5]; d_alpvec = trajectories[6]; d_nuvec = trajectories[7]; d_gimdotvec = trajectories[8]; double_size = length*sizeof(double); gpuErrchk(hipMalloc(&d_t, (length+2)*sizeof(double))); gpuErrchk(hipMalloc(&d_hI, (length+2)*sizeof(double))); gpuErrchk(hipMalloc(&d_hII, (length+2)*sizeof(double))); gpuErrchk(hipMalloc(&d_data_channel1, fft_length*sizeof(hipDoubleComplex))); gpuErrchk(hipMalloc(&d_data_channel2, fft_length*sizeof(hipDoubleComplex))); gpuErrchk(hipMemcpy(d_data_channel1, data_channel1, fft_length*sizeof(hipDoubleComplex), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_data_channel2, data_channel2, fft_length*sizeof(hipDoubleComplex), hipMemcpyHostToDevice)); gpuErrchk(hipMalloc(&d_noise_channel1_inv, fft_length*sizeof(double))); gpuErrchk(hipMalloc(&d_noise_channel2_inv, fft_length*sizeof(double))); gpuErrchk(hipMemcpy(d_noise_channel1_inv, noise_channel1_inv, fft_length*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_noise_channel2_inv, noise_channel2_inv, fft_length*sizeof(double), hipMemcpyHostToDevice)); double_plus_one_size = (length+1)*sizeof(double); // TODO reduce size properly gpuErrchk(hipMalloc(&d_tvec, (length+1)*sizeof(double))); NUM_THREADS = 256; num_blocks = ::ceil((init_length + 1 + NUM_THREADS -1)/NUM_THREADS); num_blocks_wave = ::ceil((length + 1 + NUM_THREADS -1)/NUM_THREADS); // hipfftHandle plan_; //plan = plan_; //hipfftComplex *data; if (hipfftPlan1d(&plan, length, HIPFFT_D2Z, BATCH) != HIPFFT_SUCCESS){ fprintf(stderr, "CUFFT error: Plan creation failed"); return; } stat = hipblasCreate(&handle); if (stat != HIPBLAS_STATUS_SUCCESS) { printf ("CUBLAS initialization failed\n"); exit(0); } interp.alloc_arrays(init_length + 1, 9); } void GPUAAK::gpu_gen_AAK( double iota_, double s_, double p_, double e_, double M_, double mu_, double gamma_, double psi_, double alph_, double theta_S_, double phi_S_, double theta_K_, double phi_K_, double D_){ /*hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); hipEventRecord(start);*/ GPUAAK::run_phase_trajectory( iota_, s_, p_, e_, M_, mu_, gamma_, psi_, alph_, theta_S_, phi_S_, theta_K_, phi_K_, D_); /*hipEventRecord(stop); hipEventSynchronize(stop); float milliseconds = 0; hipEventElapsedTime(&milliseconds, start, stop); printf("time cpu: %lf\n", milliseconds/1000.0);*/ //hipEventRecord(start); // Initialize inputs // ----- number of modes summed ----- int nmodes=(int)(30*par[3]); if (par[3]<0.135) nmodes=4; // ---------- zeta=par[0]/D/Gpc; // M/D hipError_t err; gpuErrchk(hipMemcpy(d_tvec, tvec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_evec.array, evec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_vvec.array, vvec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_Mvec.array, Mvec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_Svec.array, Svec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_gimvec.array, gimvec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_Phivec.array, Phivec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_alpvec.array, alpvec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_nuvec.array, nuvec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_gimdotvec.array, gimdotvec, (init_length+1)*sizeof(double), hipMemcpyHostToDevice)); gpuErrchk(hipMemcpy(d_trajectories, trajectories, numBytes, hipMemcpyHostToDevice)); //for (int i=0; i<100; i++) printf("%.18e\n", gimdotvec[i]); //printf("\n\n\nBREAK BREAK\n\n\n"); interp.setup(d_trajectories, (init_length + 1), 9); /* main: evaluate model at given frequencies */ hipLaunchKernelGGL(( kernel_create_waveform), dim3(num_blocks_wave), dim3(NUM_THREADS), 0, 0, d_t, d_hI, d_hII, d_tvec, d_evec, d_vvec, d_Mvec, d_Svec, d_gimvec, d_Phivec, d_alpvec, d_nuvec, d_gimdotvec, iota, theta_S, phi_S, theta_K, phi_K, LISA, init_length, length, nmodes, i_plunge, i_buffer, zeta, M, init_dt, dt); //iota = lam hipDeviceSynchronize(); gpuErrchk(hipGetLastError()); /*hipEventRecord(stop); hipEventSynchronize(stop); hipEventElapsedTime(&milliseconds, start, stop); printf("time gpu: %lf\n", milliseconds/1000.0);*/ /*double *hI = new double[length+2]; hipMemcpy(hI, d_data_channel1, (length+2)*sizeof(double), hipMemcpyDeviceToHost); for (int i=0; i<200; i+=1){ //if (i == fft_length-1) hI[2*i + 1] = 0.0; printf("%d after: , %e + %e j, %e + %e j\n", i, hI[2*i], hI[2*i + 1], data_channel1[i].real(), data_channel1[i].imag()); } delete[] hI;//*/ } void GPUAAK::run_phase_trajectory( double iota_, double s_, double p_, double e_, double M_, double mu_, double gamma_, double psi_, double alph_, double theta_S_, double phi_S_, double theta_K_, double phi_K_, double D_){ iota = iota_; s = s_; p = p_; e = e_; M = M_; mu = mu_; gamma = gamma_; psi = psi_; alph = alph_; theta_S = theta_S_; phi_S = phi_S_; theta_K = theta_K_; phi_K = phi_K_; D = D_; clock_t ticks=clock(); GKTrajFast gktraj3(cos(iota),s); gktraj3.p=p; gktraj3.ecc=e; int maxsteps=100; int steps=0; double dt_fit=min(T_fit,init_length*init_dt/SOLARMASSINSEC/M/M*mu)/(maxsteps-1); TrajData *traj3; traj3=(TrajData*)malloc((size_t)((maxsteps+1)*sizeof(TrajData))); gktraj3.Eccentric(dt_fit,traj3,maxsteps,steps); double Omega_t[3],ang[3],map_t[3],e_traj[steps],v_map[steps],M_map[steps],s_map[steps],dt_map[steps]; double Phi; for(int i=1;i<=steps;i++){ IEKG geodesic_t(traj3[i].p,traj3[i].ecc,traj3[i].cosiota,s); geodesic_t.Frequencies(Omega_t); if(i==1){ ParAng(ang,e,iota,gamma,psi,theta_S,phi_S,theta_K,phi_K,alph,geodesic_t.zedminus); Phi=ang[0]; // initial mean anomaly } ParMap(map_t,Omega_t,traj3[i].p,M,s,traj3[i].ecc,iota); e_traj[i-1]=traj3[i].ecc; v_map[i-1]=map_t[0]; // mapped initial velocity in c M_map[i-1]=map_t[1]; // mapped BH mass in solar masses s_map[i-1]=map_t[2]; // mapped spin parameter a/M = S/M^2 dt_map[i-1]=traj3[i].t*SOLARMASSINSEC*M*M/mu; } //GenWave(t,hI,hII,AAK.dt,AAK.length,e_traj,v_map,AAK.M,M_map,AAK.mu,AAK.s,s_map,AAK.D,AAK.iota,AAK.gamma,Phi,AAK.theta_S,AAK.phi_S,AAK.alpha,AAK.theta_K,AAK.phi_K,dt_map,steps,AAK.backint,AAK.LISA,false); par[0]=mu*SOLARMASSINSEC; par[1]=M_map[0]*SOLARMASSINSEC; par[2]=s_map[0]; par[3]=e_traj[0]; par[4]=iota; // TODO: check this par[5]=gamma; par[6]=Phi; par[7]=theta_S; par[8]=phi_S; par[9]=theta_K; par[10]=phi_K; par[11]=alph; PNevolution(tvec,evec,vvec,Mvec,Svec,gimvec,Phivec,alpvec,nuvec,gimdotvec,init_dt,init_length,par,e_traj,v_map,M,M_map,s,s_map,dt_map,steps,&i_plunge,&i_buffer,backint); } void GPUAAK::Likelihood (double *like_out_){ //hipMemcpy(hI, d_hI, (length+2)*sizeof(double), hipMemcpyDeviceToHost); /*hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); hipEventRecord(start);*/ if (hipfftExecD2Z(plan, d_hI, (hipfftDoubleComplex*)d_hI) != HIPFFT_SUCCESS){ fprintf(stderr, "CUFFT error: ExecC2C Forward failed"); return;} hipDeviceSynchronize(); gpuErrchk(hipGetLastError()); if (hipfftExecD2Z(plan, d_hII, (hipfftDoubleComplex*)d_hII) != HIPFFT_SUCCESS){ fprintf(stderr, "CUFFT error: ExecC2C Forward failed"); return;} hipDeviceSynchronize(); gpuErrchk(hipGetLastError()); hipLaunchKernelGGL(( likelihood_prep), dim3(num_blocks_wave), dim3(NUM_THREADS), 0, 0, (hipDoubleComplex*)d_hI, (hipDoubleComplex*)d_hII, d_noise_channel1_inv, d_noise_channel2_inv, fft_length); hipDeviceSynchronize(); gpuErrchk(hipGetLastError()); //printf("checkcheckcheck\n"); double d_h = 0.0; double h_h = 0.0; char * status; double res; hipDoubleComplex result; stat = hipblasZdotc(handle, fft_length, (hipDoubleComplex*)d_hI, 1, (hipDoubleComplex*)d_data_channel1, 1, &result); status = _cudaGetErrorEnum(stat); hipDeviceSynchronize(); if (stat != HIPBLAS_STATUS_SUCCESS) { exit(0); } d_h += cuCreal(result); //printf("channel1 d_h: %e\n", cuCreal(result)); stat = hipblasZdotc(handle, fft_length, (hipDoubleComplex*)d_hII, 1, (hipDoubleComplex*)d_data_channel2, 1, &result); status = _cudaGetErrorEnum(stat); hipDeviceSynchronize(); if (stat != HIPBLAS_STATUS_SUCCESS) { exit(0); } d_h += cuCreal(result); //printf("channel2 d_h: %e\n", cuCreal(result)); stat = hipblasZdotc(handle, fft_length, (hipDoubleComplex*)d_hI, 1, (hipDoubleComplex*)d_hI, 1, &result); status = _cudaGetErrorEnum(stat); hipDeviceSynchronize(); if (stat != HIPBLAS_STATUS_SUCCESS) { exit(0); } h_h += cuCreal(result); //printf("channel1 h_h: %e\n", cuCreal(result)); stat = hipblasZdotc(handle, fft_length, (hipDoubleComplex*)d_hII, 1, (hipDoubleComplex*)d_hII, 1, &result); status = _cudaGetErrorEnum(stat); hipDeviceSynchronize(); if (stat != HIPBLAS_STATUS_SUCCESS) { exit(0); } h_h += cuCreal(result); //printf("channel2 h_h: %e\n", cuCreal(result)); //printf("dh: %e, hh: %e\n", d_h, h_h); like_out_[0] = 4*d_h; like_out_[1] = 4*h_h; /*hipEventRecord(stop); hipEventSynchronize(stop); float milliseconds = 0; hipEventElapsedTime(&milliseconds, start, stop); printf("time like: %lf\n\n", milliseconds/1000.0);*/ } void GPUAAK::GetWaveform (double *t_, double* hI_, double* hII_) { gpuErrchk(hipMemcpy(t_, d_t, (length+2)*sizeof(double), hipMemcpyDeviceToHost)); gpuErrchk(hipMemcpy(hI_, d_hI, (length+2)*sizeof(double), hipMemcpyDeviceToHost)); gpuErrchk(hipMemcpy(hII_, d_hII, (length+2)*sizeof(double), hipMemcpyDeviceToHost)); }//*/ GPUAAK::~GPUAAK() { delete[] tvec; delete[] evec; delete[] vvec; delete[] Mvec; delete[] Svec; delete[] gimvec; delete[] Phivec; delete[] alpvec; delete[] nuvec; delete[] gimdotvec; hipFree(d_t); hipFree(d_hI); hipFree(d_hII); hipFree(d_tvec); destroyInterpArrayContainer(d_trajectories, trajectories, 9); hipFree(d_data_channel1); hipFree(d_data_channel2); hipFree(d_noise_channel1_inv); hipFree(d_noise_channel2_inv); hipfftDestroy(plan); hipblasDestroy(handle); }
d51238c34650438997e7952382a13a211292446e.cu
/* This is the central piece of code. This file implements a class (interface in gpuadder.hh) that takes data in on the cpu side, copies it to the gpu, and exposes functions (increment and retreive) that let you perform actions with the GPU This class will get translated into python via swig */ #include <kernel.cu> #include <AAK_manager.hh> #include <assert.h> #include <iostream> #include <stdlib.h> #include "cuComplex.h" #include "cublas_v2.h" #include <cufft.h> #include <complex.h> #include "Globals.h" #include "GKTrajFast.h" #include "KSParMap.h" #include "KSTools.h" #include "AAK.h" #include "interpolate.cu" using namespace std; #define BATCH 1 #define gpuErrchk(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true) { if (code != cudaSuccess) { fprintf(stderr,"GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } } GPUAAK::GPUAAK (double T_fit_, int init_length_, int length_, double init_dt_, double dt_, bool LISA_, bool backint_, cmplx *data_channel1_, cmplx *data_channel2_, double *noise_channel1_inv_, double *noise_channel2_inv_){ T_fit = T_fit_; init_length = init_length_; length = length_; init_dt = init_dt_; dt = dt_; LISA = LISA_; backint = backint_; data_channel1 = data_channel1_; data_channel2 = data_channel2_; noise_channel1_inv = noise_channel1_inv_; noise_channel2_inv = noise_channel2_inv_; to_gpu = 1; fft_length = ((int) (length/2)) + 1; cudaError_t err; // DECLARE ALL THE NECESSARY STRUCTS tvec = new double[init_length+1]; evec = new double[init_length+1]; vvec = new double[init_length+1]; Mvec = new double[init_length+1]; Svec = new double[init_length+1]; gimvec = new double[init_length+1]; Phivec = new double[init_length+1]; alpvec = new double[init_length+1]; nuvec = new double[init_length+1]; gimdotvec = new double[init_length+1]; size_t numBytes_ = 0; trajectories = createInterpArrayContainer(&numBytes_, 9, init_length+1); numBytes = numBytes_; d_trajectories = createInterpArrayContainer_gpu(numBytes); d_evec = trajectories[0]; d_vvec = trajectories[1]; d_Mvec = trajectories[2]; d_Svec = trajectories[3]; d_gimvec = trajectories[4]; d_Phivec = trajectories[5]; d_alpvec = trajectories[6]; d_nuvec = trajectories[7]; d_gimdotvec = trajectories[8]; double_size = length*sizeof(double); gpuErrchk(cudaMalloc(&d_t, (length+2)*sizeof(double))); gpuErrchk(cudaMalloc(&d_hI, (length+2)*sizeof(double))); gpuErrchk(cudaMalloc(&d_hII, (length+2)*sizeof(double))); gpuErrchk(cudaMalloc(&d_data_channel1, fft_length*sizeof(cuDoubleComplex))); gpuErrchk(cudaMalloc(&d_data_channel2, fft_length*sizeof(cuDoubleComplex))); gpuErrchk(cudaMemcpy(d_data_channel1, data_channel1, fft_length*sizeof(cuDoubleComplex), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_data_channel2, data_channel2, fft_length*sizeof(cuDoubleComplex), cudaMemcpyHostToDevice)); gpuErrchk(cudaMalloc(&d_noise_channel1_inv, fft_length*sizeof(double))); gpuErrchk(cudaMalloc(&d_noise_channel2_inv, fft_length*sizeof(double))); gpuErrchk(cudaMemcpy(d_noise_channel1_inv, noise_channel1_inv, fft_length*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_noise_channel2_inv, noise_channel2_inv, fft_length*sizeof(double), cudaMemcpyHostToDevice)); double_plus_one_size = (length+1)*sizeof(double); // TODO reduce size properly gpuErrchk(cudaMalloc(&d_tvec, (length+1)*sizeof(double))); NUM_THREADS = 256; num_blocks = std::ceil((init_length + 1 + NUM_THREADS -1)/NUM_THREADS); num_blocks_wave = std::ceil((length + 1 + NUM_THREADS -1)/NUM_THREADS); // cufftHandle plan_; //plan = plan_; //cufftComplex *data; if (cufftPlan1d(&plan, length, CUFFT_D2Z, BATCH) != CUFFT_SUCCESS){ fprintf(stderr, "CUFFT error: Plan creation failed"); return; } stat = cublasCreate(&handle); if (stat != CUBLAS_STATUS_SUCCESS) { printf ("CUBLAS initialization failed\n"); exit(0); } interp.alloc_arrays(init_length + 1, 9); } void GPUAAK::gpu_gen_AAK( double iota_, double s_, double p_, double e_, double M_, double mu_, double gamma_, double psi_, double alph_, double theta_S_, double phi_S_, double theta_K_, double phi_K_, double D_){ /*cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start);*/ GPUAAK::run_phase_trajectory( iota_, s_, p_, e_, M_, mu_, gamma_, psi_, alph_, theta_S_, phi_S_, theta_K_, phi_K_, D_); /*cudaEventRecord(stop); cudaEventSynchronize(stop); float milliseconds = 0; cudaEventElapsedTime(&milliseconds, start, stop); printf("time cpu: %lf\n", milliseconds/1000.0);*/ //cudaEventRecord(start); // Initialize inputs // ----- number of modes summed ----- int nmodes=(int)(30*par[3]); if (par[3]<0.135) nmodes=4; // ---------- zeta=par[0]/D/Gpc; // M/D cudaError_t err; gpuErrchk(cudaMemcpy(d_tvec, tvec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_evec.array, evec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_vvec.array, vvec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_Mvec.array, Mvec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_Svec.array, Svec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_gimvec.array, gimvec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_Phivec.array, Phivec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_alpvec.array, alpvec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_nuvec.array, nuvec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_gimdotvec.array, gimdotvec, (init_length+1)*sizeof(double), cudaMemcpyHostToDevice)); gpuErrchk(cudaMemcpy(d_trajectories, trajectories, numBytes, cudaMemcpyHostToDevice)); //for (int i=0; i<100; i++) printf("%.18e\n", gimdotvec[i]); //printf("\n\n\nBREAK BREAK\n\n\n"); interp.setup(d_trajectories, (init_length + 1), 9); /* main: evaluate model at given frequencies */ kernel_create_waveform<<<num_blocks_wave, NUM_THREADS>>>(d_t, d_hI, d_hII, d_tvec, d_evec, d_vvec, d_Mvec, d_Svec, d_gimvec, d_Phivec, d_alpvec, d_nuvec, d_gimdotvec, iota, theta_S, phi_S, theta_K, phi_K, LISA, init_length, length, nmodes, i_plunge, i_buffer, zeta, M, init_dt, dt); //iota = lam cudaDeviceSynchronize(); gpuErrchk(cudaGetLastError()); /*cudaEventRecord(stop); cudaEventSynchronize(stop); cudaEventElapsedTime(&milliseconds, start, stop); printf("time gpu: %lf\n", milliseconds/1000.0);*/ /*double *hI = new double[length+2]; cudaMemcpy(hI, d_data_channel1, (length+2)*sizeof(double), cudaMemcpyDeviceToHost); for (int i=0; i<200; i+=1){ //if (i == fft_length-1) hI[2*i + 1] = 0.0; printf("%d after: , %e + %e j, %e + %e j\n", i, hI[2*i], hI[2*i + 1], data_channel1[i].real(), data_channel1[i].imag()); } delete[] hI;//*/ } void GPUAAK::run_phase_trajectory( double iota_, double s_, double p_, double e_, double M_, double mu_, double gamma_, double psi_, double alph_, double theta_S_, double phi_S_, double theta_K_, double phi_K_, double D_){ iota = iota_; s = s_; p = p_; e = e_; M = M_; mu = mu_; gamma = gamma_; psi = psi_; alph = alph_; theta_S = theta_S_; phi_S = phi_S_; theta_K = theta_K_; phi_K = phi_K_; D = D_; clock_t ticks=clock(); GKTrajFast gktraj3(cos(iota),s); gktraj3.p=p; gktraj3.ecc=e; int maxsteps=100; int steps=0; double dt_fit=min(T_fit,init_length*init_dt/SOLARMASSINSEC/M/M*mu)/(maxsteps-1); TrajData *traj3; traj3=(TrajData*)malloc((size_t)((maxsteps+1)*sizeof(TrajData))); gktraj3.Eccentric(dt_fit,traj3,maxsteps,steps); double Omega_t[3],ang[3],map_t[3],e_traj[steps],v_map[steps],M_map[steps],s_map[steps],dt_map[steps]; double Phi; for(int i=1;i<=steps;i++){ IEKG geodesic_t(traj3[i].p,traj3[i].ecc,traj3[i].cosiota,s); geodesic_t.Frequencies(Omega_t); if(i==1){ ParAng(ang,e,iota,gamma,psi,theta_S,phi_S,theta_K,phi_K,alph,geodesic_t.zedminus); Phi=ang[0]; // initial mean anomaly } ParMap(map_t,Omega_t,traj3[i].p,M,s,traj3[i].ecc,iota); e_traj[i-1]=traj3[i].ecc; v_map[i-1]=map_t[0]; // mapped initial velocity in c M_map[i-1]=map_t[1]; // mapped BH mass in solar masses s_map[i-1]=map_t[2]; // mapped spin parameter a/M = S/M^2 dt_map[i-1]=traj3[i].t*SOLARMASSINSEC*M*M/mu; } //GenWave(t,hI,hII,AAK.dt,AAK.length,e_traj,v_map,AAK.M,M_map,AAK.mu,AAK.s,s_map,AAK.D,AAK.iota,AAK.gamma,Phi,AAK.theta_S,AAK.phi_S,AAK.alpha,AAK.theta_K,AAK.phi_K,dt_map,steps,AAK.backint,AAK.LISA,false); par[0]=mu*SOLARMASSINSEC; par[1]=M_map[0]*SOLARMASSINSEC; par[2]=s_map[0]; par[3]=e_traj[0]; par[4]=iota; // TODO: check this par[5]=gamma; par[6]=Phi; par[7]=theta_S; par[8]=phi_S; par[9]=theta_K; par[10]=phi_K; par[11]=alph; PNevolution(tvec,evec,vvec,Mvec,Svec,gimvec,Phivec,alpvec,nuvec,gimdotvec,init_dt,init_length,par,e_traj,v_map,M,M_map,s,s_map,dt_map,steps,&i_plunge,&i_buffer,backint); } void GPUAAK::Likelihood (double *like_out_){ //cudaMemcpy(hI, d_hI, (length+2)*sizeof(double), cudaMemcpyDeviceToHost); /*cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start);*/ if (cufftExecD2Z(plan, d_hI, (cufftDoubleComplex*)d_hI) != CUFFT_SUCCESS){ fprintf(stderr, "CUFFT error: ExecC2C Forward failed"); return;} cudaDeviceSynchronize(); gpuErrchk(cudaGetLastError()); if (cufftExecD2Z(plan, d_hII, (cufftDoubleComplex*)d_hII) != CUFFT_SUCCESS){ fprintf(stderr, "CUFFT error: ExecC2C Forward failed"); return;} cudaDeviceSynchronize(); gpuErrchk(cudaGetLastError()); likelihood_prep<<<num_blocks_wave, NUM_THREADS>>>((cuDoubleComplex*)d_hI, (cuDoubleComplex*)d_hII, d_noise_channel1_inv, d_noise_channel2_inv, fft_length); cudaDeviceSynchronize(); gpuErrchk(cudaGetLastError()); //printf("checkcheckcheck\n"); double d_h = 0.0; double h_h = 0.0; char * status; double res; cuDoubleComplex result; stat = cublasZdotc(handle, fft_length, (cuDoubleComplex*)d_hI, 1, (cuDoubleComplex*)d_data_channel1, 1, &result); status = _cudaGetErrorEnum(stat); cudaDeviceSynchronize(); if (stat != CUBLAS_STATUS_SUCCESS) { exit(0); } d_h += cuCreal(result); //printf("channel1 d_h: %e\n", cuCreal(result)); stat = cublasZdotc(handle, fft_length, (cuDoubleComplex*)d_hII, 1, (cuDoubleComplex*)d_data_channel2, 1, &result); status = _cudaGetErrorEnum(stat); cudaDeviceSynchronize(); if (stat != CUBLAS_STATUS_SUCCESS) { exit(0); } d_h += cuCreal(result); //printf("channel2 d_h: %e\n", cuCreal(result)); stat = cublasZdotc(handle, fft_length, (cuDoubleComplex*)d_hI, 1, (cuDoubleComplex*)d_hI, 1, &result); status = _cudaGetErrorEnum(stat); cudaDeviceSynchronize(); if (stat != CUBLAS_STATUS_SUCCESS) { exit(0); } h_h += cuCreal(result); //printf("channel1 h_h: %e\n", cuCreal(result)); stat = cublasZdotc(handle, fft_length, (cuDoubleComplex*)d_hII, 1, (cuDoubleComplex*)d_hII, 1, &result); status = _cudaGetErrorEnum(stat); cudaDeviceSynchronize(); if (stat != CUBLAS_STATUS_SUCCESS) { exit(0); } h_h += cuCreal(result); //printf("channel2 h_h: %e\n", cuCreal(result)); //printf("dh: %e, hh: %e\n", d_h, h_h); like_out_[0] = 4*d_h; like_out_[1] = 4*h_h; /*cudaEventRecord(stop); cudaEventSynchronize(stop); float milliseconds = 0; cudaEventElapsedTime(&milliseconds, start, stop); printf("time like: %lf\n\n", milliseconds/1000.0);*/ } void GPUAAK::GetWaveform (double *t_, double* hI_, double* hII_) { gpuErrchk(cudaMemcpy(t_, d_t, (length+2)*sizeof(double), cudaMemcpyDeviceToHost)); gpuErrchk(cudaMemcpy(hI_, d_hI, (length+2)*sizeof(double), cudaMemcpyDeviceToHost)); gpuErrchk(cudaMemcpy(hII_, d_hII, (length+2)*sizeof(double), cudaMemcpyDeviceToHost)); }//*/ GPUAAK::~GPUAAK() { delete[] tvec; delete[] evec; delete[] vvec; delete[] Mvec; delete[] Svec; delete[] gimvec; delete[] Phivec; delete[] alpvec; delete[] nuvec; delete[] gimdotvec; cudaFree(d_t); cudaFree(d_hI); cudaFree(d_hII); cudaFree(d_tvec); destroyInterpArrayContainer(d_trajectories, trajectories, 9); cudaFree(d_data_channel1); cudaFree(d_data_channel2); cudaFree(d_noise_channel1_inv); cudaFree(d_noise_channel2_inv); cufftDestroy(plan); cublasDestroy(handle); }
096c982697778355ab133c3ab8825f4cb638f306.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. Created by Pawan Harish. ************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <hip/hip_runtime.h> #include <sys/time.h> #define MAX_THREADS_PER_BLOCK 512 #define PROFILING 1 #ifdef PROFILING #include "RDTimer.h" #endif int no_of_nodes; int edge_list_size; FILE *fp; //Structure to hold a node information struct Node { int starting; int no_of_edges; }; #include "kernel.hip.cu" #include "kernel2.hip.cu" void BFSGraph(int argc, char** argv); //////////////////////////////////////////////////////////////////////////////// // Main Program //////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { no_of_nodes=0; edge_list_size=0; BFSGraph( argc, argv); } void Usage(int argc, char**argv){ fprintf(stderr,"Usage: %s <input_file>\n", argv[0]); } //////////////////////////////////////////////////////////////////////////////// //Apply BFS on a Graph using CUDA //////////////////////////////////////////////////////////////////////////////// void BFSGraph( int argc, char** argv) { char *input_f; if(argc!=2){ Usage(argc, argv); exit(0); } struct timeval start_time, end_time,start_time_kernel, end_time_kernel; /* overall time - start */ #ifdef PROFILING float alloc_t, cpu_to_gpu_t,kernel_t,gpu_to_cpu_t,overall_cpu_t; RDTimerCPU* rdtimerOverallCpu = new RDTimerCPU(); rdtimerOverallCpu->Reset("Overall CPU Time"); rdtimerOverallCpu->Start(); #endif input_f = argv[1]; printf("Reading File\n"); //Read in Graph from a file fp = fopen(input_f,"r"); if(!fp) { printf("Error Reading graph file\n"); return; } int source = 0; fscanf(fp,"%d",&no_of_nodes); int num_of_blocks = 1; int num_of_threads_per_block = no_of_nodes; //Make execution Parameters according to the number of nodes //Distribute threads across multiple Blocks if necessary if(no_of_nodes>MAX_THREADS_PER_BLOCK) { num_of_blocks = (int)ceil(no_of_nodes/(double)MAX_THREADS_PER_BLOCK); num_of_threads_per_block = MAX_THREADS_PER_BLOCK; } // allocate host memory Node* h_graph_nodes = (Node*) malloc(sizeof(Node)*no_of_nodes); bool *h_graph_mask = (bool*) malloc(sizeof(bool)*no_of_nodes); bool *h_updating_graph_mask = (bool*) malloc(sizeof(bool)*no_of_nodes); bool *h_graph_visited = (bool*) malloc(sizeof(bool)*no_of_nodes); int start, edgeno; // initalize the memory for( unsigned int i = 0; i < no_of_nodes; i++) { fscanf(fp,"%d %d",&start,&edgeno); h_graph_nodes[i].starting = start; h_graph_nodes[i].no_of_edges = edgeno; h_graph_mask[i]=false; h_updating_graph_mask[i]=false; h_graph_visited[i]=false; } //read the source node from the file fscanf(fp,"%d",&source); source=0; //set the source node as true in the mask h_graph_mask[source]=true; h_graph_visited[source]=true; fscanf(fp,"%d",&edge_list_size); int id,cost; int* h_graph_edges = (int*) malloc(sizeof(int)*edge_list_size); for(int i=0; i < edge_list_size ; i++) { fscanf(fp,"%d",&id); fscanf(fp,"%d",&cost); h_graph_edges[i] = id; } if(fp) fclose(fp); printf("Read File\n"); // allocate mem for the result on host side int* h_cost = (int*) malloc( sizeof(int)*no_of_nodes); for(int i=0;i<no_of_nodes;i++) h_cost[i]=-1; h_cost[source]=0; /* start time */ gettimeofday(&start_time, NULL); /* malloc time-start */ #ifdef PROFILING SimplePerfSerializer* serializeTime = new SimplePerfSerializer( argv[0] ); RDTimerCPU* rdtimercpu = new RDTimerCPU(); rdtimercpu->Reset("Malloc Time"); rdtimercpu->Start(); #endif //Copy the Node list to device memory Node* d_graph_nodes; hipMalloc( (void**) &d_graph_nodes, sizeof(Node)*no_of_nodes) ; //Copy the Edge List to device Memory int* d_graph_edges; hipMalloc( (void**) &d_graph_edges, sizeof(int)*edge_list_size) ; //Copy the Mask to device memory bool* d_graph_mask; hipMalloc( (void**) &d_graph_mask, sizeof(bool)*no_of_nodes) ; bool* d_updating_graph_mask; hipMalloc( (void**) &d_updating_graph_mask, sizeof(bool)*no_of_nodes) ; //Copy the Visited nodes array to device memory bool* d_graph_visited; hipMalloc( (void**) &d_graph_visited, sizeof(bool)*no_of_nodes) ; // allocate device memory for result int* d_cost; hipMalloc( (void**) &d_cost, sizeof(int)*no_of_nodes); //make a bool to check if the execution is over bool *d_over; hipMalloc( (void**) &d_over, sizeof(bool)); // copying to GPU /* malloc time-stop, cpu-gpu transfer start */ #ifdef PROFILING alloc_t = rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); rdtimercpu->Reset("CPU to GPU Transfer Time"); rdtimercpu->Start(); #endif // nodelist hipMemcpy( d_graph_nodes, h_graph_nodes, sizeof(Node)*no_of_nodes, hipMemcpyHostToDevice) ; //edgelist hipMemcpy( d_graph_edges, h_graph_edges, sizeof(int)*edge_list_size, hipMemcpyHostToDevice) ; //mask hipMemcpy( d_graph_mask, h_graph_mask, sizeof(bool)*no_of_nodes, hipMemcpyHostToDevice) ; hipMemcpy( d_updating_graph_mask, h_updating_graph_mask, sizeof(bool)*no_of_nodes, hipMemcpyHostToDevice) ; // visited nodes hipMemcpy( d_graph_visited, h_graph_visited, sizeof(bool)*no_of_nodes, hipMemcpyHostToDevice) ; // device memory for result hipMemcpy( d_cost, h_cost, sizeof(int)*no_of_nodes, hipMemcpyHostToDevice) ; printf("Copied Everything to GPU memory\n"); // setup execution parameters dim3 grid( num_of_blocks, 1, 1); dim3 threads( num_of_threads_per_block, 1, 1); int k=0; printf("Start traversing the tree\n"); bool stop; //Call the Kernel untill all the elements of Frontier are not false /* start time */ gettimeofday(&start_time_kernel, NULL); /*cpu-gpu transfer-stop, kernel exec-start */ #ifdef PROFILING cpu_to_gpu_t = rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); rdtimercpu->Reset("COMPUTE:Kernel Execution Time"); //hipDeviceSynchronize(); rdtimercpu->Start(); #endif do { //if no thread changes this value then the loop stops stop=false; hipMemcpy( d_over, &stop, sizeof(bool), hipMemcpyHostToDevice) ; hipLaunchKernelGGL(Kernel, dim3(grid), dim3(threads ), 0, 0, d_graph_nodes, d_graph_edges, d_graph_mask, d_updating_graph_mask, d_graph_visited, d_cost, no_of_nodes); // check if kernel execution generated and error hipLaunchKernelGGL(Kernel2, dim3(grid), dim3(threads ), 0, 0, d_graph_mask, d_updating_graph_mask, d_graph_visited, d_over, no_of_nodes); // check if kernel execution generated and error hipMemcpy( &stop, d_over, sizeof(bool), hipMemcpyDeviceToHost) ; k++; } while(stop); /* kernel exec-stop, gpu-cpu transfer-start */ #ifdef PROFILING kernel_t = rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); rdtimercpu->Reset("GPU to CPU Transfer Time"); rdtimercpu->Start(); #endif /* end time */ gettimeofday(&end_time_kernel, NULL); printf("Kernel Executed %d times\n",k); // copy result from device to host hipMemcpy( h_cost, d_cost, sizeof(int)*no_of_nodes, hipMemcpyDeviceToHost) ; /* gpu-cpu transfer- stop */ #ifdef PROFILING gpu_to_cpu_t= rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); #endif /* end time */ gettimeofday(&end_time, NULL); //Store the result into a file FILE *fpo = fopen("result.txt","w"); for(int i=0;i<no_of_nodes;i++) fprintf(fpo,"%d) cost:%d\n",i,h_cost[i]); fclose(fpo); printf("Result stored in result.txt\n"); /* printing runtime including mem alloc and copying */ /* printf("Runtime on GPU including memory allocations: %.4lf s\n", end_time.tv_sec + end_time.tv_usec / 1000000.0 - start_time.tv_sec - start_time.tv_usec / 1000000.0);*/ /* printing runtime of kernel execution */ /* printf("Runtime on GPU for kernel execution: %.4lf s\n", end_time_kernel.tv_sec + end_time_kernel.tv_usec / 1000000.0 - start_time_kernel.tv_sec - start_time_kernel.tv_usec / 1000000.0);*/ /* over all stop print all times delete timers */ #ifdef PROFILING overall_cpu_t = rdtimerOverallCpu->Stop(); serializeTime->Serialize(rdtimerOverallCpu); printf("time CPU to GPU memory copy = %lfs\n", cpu_to_gpu_t); printf("time GPU to CPU memory copy back = %lfs\n", gpu_to_cpu_t); printf("time GPU malloc = %lfs\n", alloc_t); printf("time kernel = %lfs\n", kernel_t); printf("Overall CPU time = %lfs\n", overall_cpu_t); delete rdtimercpu; delete serializeTime; delete rdtimerOverallCpu; #endif // cleanup memory free( h_graph_nodes); free( h_graph_edges); free( h_graph_mask); free( h_updating_graph_mask); free( h_graph_visited); free( h_cost); hipFree(d_graph_nodes); hipFree(d_graph_edges); hipFree(d_graph_mask); hipFree(d_updating_graph_mask); hipFree(d_graph_visited); hipFree(d_cost); }
096c982697778355ab133c3ab8825f4cb638f306.cu
#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. Created by Pawan Harish. ************************************************************************************/ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include <cuda.h> #include <sys/time.h> #define MAX_THREADS_PER_BLOCK 512 #define PROFILING 1 #ifdef PROFILING #include "RDTimer.h" #endif int no_of_nodes; int edge_list_size; FILE *fp; //Structure to hold a node information struct Node { int starting; int no_of_edges; }; #include "kernel.hip.cu" #include "kernel2.hip.cu" void BFSGraph(int argc, char** argv); //////////////////////////////////////////////////////////////////////////////// // Main Program //////////////////////////////////////////////////////////////////////////////// int main( int argc, char** argv) { no_of_nodes=0; edge_list_size=0; BFSGraph( argc, argv); } void Usage(int argc, char**argv){ fprintf(stderr,"Usage: %s <input_file>\n", argv[0]); } //////////////////////////////////////////////////////////////////////////////// //Apply BFS on a Graph using CUDA //////////////////////////////////////////////////////////////////////////////// void BFSGraph( int argc, char** argv) { char *input_f; if(argc!=2){ Usage(argc, argv); exit(0); } struct timeval start_time, end_time,start_time_kernel, end_time_kernel; /* overall time - start */ #ifdef PROFILING float alloc_t, cpu_to_gpu_t,kernel_t,gpu_to_cpu_t,overall_cpu_t; RDTimerCPU* rdtimerOverallCpu = new RDTimerCPU(); rdtimerOverallCpu->Reset("Overall CPU Time"); rdtimerOverallCpu->Start(); #endif input_f = argv[1]; printf("Reading File\n"); //Read in Graph from a file fp = fopen(input_f,"r"); if(!fp) { printf("Error Reading graph file\n"); return; } int source = 0; fscanf(fp,"%d",&no_of_nodes); int num_of_blocks = 1; int num_of_threads_per_block = no_of_nodes; //Make execution Parameters according to the number of nodes //Distribute threads across multiple Blocks if necessary if(no_of_nodes>MAX_THREADS_PER_BLOCK) { num_of_blocks = (int)ceil(no_of_nodes/(double)MAX_THREADS_PER_BLOCK); num_of_threads_per_block = MAX_THREADS_PER_BLOCK; } // allocate host memory Node* h_graph_nodes = (Node*) malloc(sizeof(Node)*no_of_nodes); bool *h_graph_mask = (bool*) malloc(sizeof(bool)*no_of_nodes); bool *h_updating_graph_mask = (bool*) malloc(sizeof(bool)*no_of_nodes); bool *h_graph_visited = (bool*) malloc(sizeof(bool)*no_of_nodes); int start, edgeno; // initalize the memory for( unsigned int i = 0; i < no_of_nodes; i++) { fscanf(fp,"%d %d",&start,&edgeno); h_graph_nodes[i].starting = start; h_graph_nodes[i].no_of_edges = edgeno; h_graph_mask[i]=false; h_updating_graph_mask[i]=false; h_graph_visited[i]=false; } //read the source node from the file fscanf(fp,"%d",&source); source=0; //set the source node as true in the mask h_graph_mask[source]=true; h_graph_visited[source]=true; fscanf(fp,"%d",&edge_list_size); int id,cost; int* h_graph_edges = (int*) malloc(sizeof(int)*edge_list_size); for(int i=0; i < edge_list_size ; i++) { fscanf(fp,"%d",&id); fscanf(fp,"%d",&cost); h_graph_edges[i] = id; } if(fp) fclose(fp); printf("Read File\n"); // allocate mem for the result on host side int* h_cost = (int*) malloc( sizeof(int)*no_of_nodes); for(int i=0;i<no_of_nodes;i++) h_cost[i]=-1; h_cost[source]=0; /* start time */ gettimeofday(&start_time, NULL); /* malloc time-start */ #ifdef PROFILING SimplePerfSerializer* serializeTime = new SimplePerfSerializer( argv[0] ); RDTimerCPU* rdtimercpu = new RDTimerCPU(); rdtimercpu->Reset("Malloc Time"); rdtimercpu->Start(); #endif //Copy the Node list to device memory Node* d_graph_nodes; hipMalloc( (void**) &d_graph_nodes, sizeof(Node)*no_of_nodes) ; //Copy the Edge List to device Memory int* d_graph_edges; hipMalloc( (void**) &d_graph_edges, sizeof(int)*edge_list_size) ; //Copy the Mask to device memory bool* d_graph_mask; hipMalloc( (void**) &d_graph_mask, sizeof(bool)*no_of_nodes) ; bool* d_updating_graph_mask; hipMalloc( (void**) &d_updating_graph_mask, sizeof(bool)*no_of_nodes) ; //Copy the Visited nodes array to device memory bool* d_graph_visited; hipMalloc( (void**) &d_graph_visited, sizeof(bool)*no_of_nodes) ; // allocate device memory for result int* d_cost; hipMalloc( (void**) &d_cost, sizeof(int)*no_of_nodes); //make a bool to check if the execution is over bool *d_over; hipMalloc( (void**) &d_over, sizeof(bool)); // copying to GPU /* malloc time-stop, cpu-gpu transfer start */ #ifdef PROFILING alloc_t = rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); rdtimercpu->Reset("CPU to GPU Transfer Time"); rdtimercpu->Start(); #endif // nodelist hipMemcpy( d_graph_nodes, h_graph_nodes, sizeof(Node)*no_of_nodes, hipMemcpyHostToDevice) ; //edgelist hipMemcpy( d_graph_edges, h_graph_edges, sizeof(int)*edge_list_size, hipMemcpyHostToDevice) ; //mask hipMemcpy( d_graph_mask, h_graph_mask, sizeof(bool)*no_of_nodes, hipMemcpyHostToDevice) ; hipMemcpy( d_updating_graph_mask, h_updating_graph_mask, sizeof(bool)*no_of_nodes, hipMemcpyHostToDevice) ; // visited nodes hipMemcpy( d_graph_visited, h_graph_visited, sizeof(bool)*no_of_nodes, hipMemcpyHostToDevice) ; // device memory for result hipMemcpy( d_cost, h_cost, sizeof(int)*no_of_nodes, hipMemcpyHostToDevice) ; printf("Copied Everything to GPU memory\n"); // setup execution parameters dim3 grid( num_of_blocks, 1, 1); dim3 threads( num_of_threads_per_block, 1, 1); int k=0; printf("Start traversing the tree\n"); bool stop; //Call the Kernel untill all the elements of Frontier are not false /* start time */ gettimeofday(&start_time_kernel, NULL); /*cpu-gpu transfer-stop, kernel exec-start */ #ifdef PROFILING cpu_to_gpu_t = rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); rdtimercpu->Reset("COMPUTE:Kernel Execution Time"); //hipDeviceSynchronize(); rdtimercpu->Start(); #endif do { //if no thread changes this value then the loop stops stop=false; hipMemcpy( d_over, &stop, sizeof(bool), hipMemcpyHostToDevice) ; hipLaunchKernelGGL(Kernel, dim3(grid), dim3(threads ), 0, 0, d_graph_nodes, d_graph_edges, d_graph_mask, d_updating_graph_mask, d_graph_visited, d_cost, no_of_nodes); // check if kernel execution generated and error hipLaunchKernelGGL(Kernel2, dim3(grid), dim3(threads ), 0, 0, d_graph_mask, d_updating_graph_mask, d_graph_visited, d_over, no_of_nodes); // check if kernel execution generated and error hipMemcpy( &stop, d_over, sizeof(bool), hipMemcpyDeviceToHost) ; k++; } while(stop); /* kernel exec-stop, gpu-cpu transfer-start */ #ifdef PROFILING kernel_t = rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); rdtimercpu->Reset("GPU to CPU Transfer Time"); rdtimercpu->Start(); #endif /* end time */ gettimeofday(&end_time_kernel, NULL); printf("Kernel Executed %d times\n",k); // copy result from device to host hipMemcpy( h_cost, d_cost, sizeof(int)*no_of_nodes, hipMemcpyDeviceToHost) ; /* gpu-cpu transfer- stop */ #ifdef PROFILING gpu_to_cpu_t= rdtimercpu->Stop(); serializeTime->Serialize(rdtimercpu); #endif /* end time */ gettimeofday(&end_time, NULL); //Store the result into a file FILE *fpo = fopen("result.txt","w"); for(int i=0;i<no_of_nodes;i++) fprintf(fpo,"%d) cost:%d\n",i,h_cost[i]); fclose(fpo); printf("Result stored in result.txt\n"); /* printing runtime including mem alloc and copying */ /* printf("Runtime on GPU including memory allocations: %.4lf s\n", end_time.tv_sec + end_time.tv_usec / 1000000.0 - start_time.tv_sec - start_time.tv_usec / 1000000.0);*/ /* printing runtime of kernel execution */ /* printf("Runtime on GPU for kernel execution: %.4lf s\n", end_time_kernel.tv_sec + end_time_kernel.tv_usec / 1000000.0 - start_time_kernel.tv_sec - start_time_kernel.tv_usec / 1000000.0);*/ /* over all stop print all times delete timers */ #ifdef PROFILING overall_cpu_t = rdtimerOverallCpu->Stop(); serializeTime->Serialize(rdtimerOverallCpu); printf("time CPU to GPU memory copy = %lfs\n", cpu_to_gpu_t); printf("time GPU to CPU memory copy back = %lfs\n", gpu_to_cpu_t); printf("time GPU malloc = %lfs\n", alloc_t); printf("time kernel = %lfs\n", kernel_t); printf("Overall CPU time = %lfs\n", overall_cpu_t); delete rdtimercpu; delete serializeTime; delete rdtimerOverallCpu; #endif // cleanup memory free( h_graph_nodes); free( h_graph_edges); free( h_graph_mask); free( h_updating_graph_mask); free( h_graph_visited); free( h_cost); hipFree(d_graph_nodes); hipFree(d_graph_edges); hipFree(d_graph_mask); hipFree(d_updating_graph_mask); hipFree(d_graph_visited); hipFree(d_cost); }
c72efd75f55a41572d72073702e2f22af9d0791f.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // ---------------------------------------------------------------------------- // CUDA code to compute minimun distance between n points // #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <time.h> #include <limits> #include <float.h> #define MAX_POINTS 1048576 #define block_size 1024 // ---------------------------------------------------------------------------- // Kernel Function to compute distance between all pairs of points // Input: // X: X[i] = x-coordinate of the ith point // Y: Y[i] = y-coordinate of the ith point // n: number of points // Output: // D: D[0] = minimum distance // __device__ unsigned int finished_blocks = 0; __global__ void minimum_distance_kernel(float * X, float * Y, volatile float * D, int n) { unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x; int i, z; float dx, dy, temp_distance; float minDist = FLT_MAX; bool finalBlockCheck; __shared__ float local_minimums[block_size]; if(idx < n - 1) { for(z = idx + 1; z<n; z++) { dx = X[z] - X[idx]; dy = Y[z] - Y[idx]; temp_distance = sqrtf(dx * dx + dy * dy); if(temp_distance < minDist) { minDist = temp_distance; } } local_minimums[threadIdx.x] = minDist; __syncthreads(); // Compute the block local minimum int max_index = (n % block_size); if(max_index == 0) { max_index = block_size; } else { if(blockIdx.x != n/block_size) { max_index = block_size; } } for(i = 1; i<max_index; i *= 2) { if(threadIdx.x % (2 * i) == 0 && (threadIdx.x + i) < max_index - 1) { if(local_minimums[threadIdx.x] > local_minimums[threadIdx.x + i]) { local_minimums[threadIdx.x] = local_minimums[threadIdx.x + i]; } __syncthreads(); } } if(threadIdx.x == 0) { D[blockIdx.x] = local_minimums[0]; int value = atomicInc(&finished_blocks, gridDim.x); finalBlockCheck = (value == (gridDim.x - 1)); } // Last thread in the list computes the global minimum and puts it in D[0] if(finalBlockCheck && threadIdx.x == 0) { int blocks = n / block_size + (n % block_size != 0); for(i = 1; i<blocks; i++) { if(D[0] > D[i]) { D[0] = D[i]; } } } } } // ---------------------------------------------------------------------------- // Host function to compute minimum distance between points // Input: // X: X[i] = x-coordinate of the ith point // Y: Y[i] = y-coordinate of the ith point // n: number of points // Output: // D: minimum distance // float minimum_distance_host(float * X, float * Y, int n) { float dx, dy, Dij, min_distance, min_distance_i; int i, j; dx = X[1]-X[0]; dy = Y[1]-Y[0]; min_distance = sqrtf(dx*dx+dy*dy); for (i = 0; i < n-1; i++) { for (j = i+1; j < i+2; j++) { dx = X[j]-X[i]; dy = Y[j]-Y[i]; min_distance_i = sqrtf(dx*dx+dy*dy); } for (j = i+1; j < n; j++) { dx = X[j]-X[i]; dy = Y[j]-Y[i]; Dij = sqrtf(dx*dx+dy*dy); if (min_distance_i > Dij) min_distance_i = Dij; } if (min_distance > min_distance_i) min_distance = min_distance_i; } return min_distance; } // ---------------------------------------------------------------------------- // Print device properties void print_device_properties() { int i, deviceCount; hipDeviceProp_t deviceProp; hipGetDeviceCount(&deviceCount); printf("------------------------------------------------------------\n"); printf("Number of GPU devices found = %d\n", deviceCount); for ( i = 0; i < deviceCount; ++i ) { hipGetDeviceProperties(&deviceProp, i); printf("[Device: %1d] Compute Capability %d.%d.\n", i, deviceProp.major, deviceProp.minor); printf(" ... multiprocessor count = %d\n", deviceProp.multiProcessorCount); printf(" ... max threads per multiprocessor = %d\n", deviceProp.maxThreadsPerMultiProcessor); printf(" ... max threads per block = %d\n", deviceProp.maxThreadsPerBlock); printf(" ... max block dimension = %d, %d, %d (along x, y, z)\n", deviceProp.maxThreadsDim[0], deviceProp.maxThreadsDim[1], deviceProp.maxThreadsDim[2]); printf(" ... max grid size = %d, %d, %d (along x, y, z)\n", deviceProp.maxGridSize[0], deviceProp.maxGridSize[1], deviceProp.maxGridSize[2]); printf(" ... warp size = %d\n", deviceProp.warpSize); printf(" ... clock rate = %d MHz\n", deviceProp.clockRate/1000); } printf("------------------------------------------------------------\n"); } // ---------------------------------------------------------------------------- // Main program - initializes points and computes minimum distance // between the points // int main(int argc, char* argv[]) { // Host Data float * hVx; // host x-coordinate array float * hVy; // host y-coordinate array float hmin_dist; // minimum value on host // Device Data float * dVx; // device x-coordinate array float * dVy; // device x-coordinate array float * dmin_dist; // minimum value on device // Device parameters //int MAX_BLOCK_SIZE; // Maximum number of threads allowed on the device int blocks; // Number of blocks in grid //int threads_per_block; // Number of threads per block // Timing variables hipEvent_t start, stop; // GPU timing variables struct timespec cpu_start, cpu_stop; // CPU timing variables float time_array[10]; // Other variables int i, size, num_points; float min_distance, sqrtn; int seed = 0; // Print device properties print_device_properties(); // Get device information and set device to use int deviceCount; hipDeviceProp_t deviceProp; hipGetDeviceCount(&deviceCount); if (deviceCount > 0) { hipSetDevice(0); hipGetDeviceProperties(&deviceProp, 0); //int MAX_BLOCK_SIZE = deviceProp.maxThreadsPerBlock; } else { printf("Warning: No GPU device found ... results may be incorrect\n"); } // Timing initializations hipEventCreate(&start); hipEventCreate(&stop); // Check input if (argc != 2) { printf("Use: %s <number of points>\n", argv[0]); exit(0); } if ((num_points = atoi(argv[argc-1])) < 2) { printf("Minimum number of points allowed: 2\n"); exit(0); } if ((num_points = atoi(argv[argc-1])) > MAX_POINTS) { printf("Maximum number of points allowed: %d\n", MAX_POINTS); exit(0); } // Allocate host coordinate arrays size = num_points * sizeof(float); hVx = (float *) malloc(size); hVy = (float *) malloc(size); // Initialize points srand48(seed); sqrtn = (float) sqrt(num_points); for (i = 0; i < num_points; i++) { hVx[i] = sqrtn * (float)drand48(); hVy[i] = sqrtn * (float)drand48(); } // Allocate device coordinate arrays hipMalloc(&dVx, size); hipMalloc(&dVy, size); hipMalloc(&dmin_dist, size); // Copy coordinate arrays from host memory to device memory hipEventRecord( start, 0 ); hipMemcpy(dVx, hVx, size, hipMemcpyHostToDevice); hipMemcpy(dVy, hVy, size, hipMemcpyHostToDevice); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&(time_array[0]), start, stop); // Invoke kernel hipEventRecord( start, 0 ); blocks = num_points / block_size + (num_points % block_size != 0); hipLaunchKernelGGL(( minimum_distance_kernel), dim3(blocks), dim3(block_size), 0, 0, dVx, dVy, dmin_dist, num_points); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&(time_array[1]), start, stop); // Copy result from device memory to host memory hipEventRecord( start, 0 ); hipMemcpy(&hmin_dist, dmin_dist, sizeof(float), hipMemcpyDeviceToHost); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&(time_array[2]), start, stop); // Compute minimum distance on host to check device computation clock_gettime(CLOCK_REALTIME, &cpu_start); min_distance = minimum_distance_host(hVx, hVy, num_points); clock_gettime(CLOCK_REALTIME, &cpu_stop); time_array[3] = 1000*((cpu_stop.tv_sec-cpu_start.tv_sec) +0.000000001*(cpu_stop.tv_nsec-cpu_start.tv_nsec)); // Print results printf("Number of Points = %d\n", num_points); printf("GPU Host-to-device = %f ms \n", time_array[0]); printf("GPU Device-to-host = %f ms \n", time_array[2]); printf("GPU execution time = %f ms \n", time_array[1]); printf("CPU execution time = %f ms\n", time_array[3]); printf("Min. distance (GPU) = %e\n", hmin_dist); printf("Min. distance (CPU) = %e\n", min_distance); printf("Relative error = %e\n", fabs(min_distance-hmin_dist)/min_distance); // Free device memory hipFree(dVx); hipFree(dVy); hipFree(dmin_dist); // Free host memory free(hVx); free(hVy); }
c72efd75f55a41572d72073702e2f22af9d0791f.cu
// ---------------------------------------------------------------------------- // CUDA code to compute minimun distance between n points // #include <stdio.h> #include <stdlib.h> #include <math.h> #include <time.h> #include <time.h> #include <limits> #include <float.h> #define MAX_POINTS 1048576 #define block_size 1024 // ---------------------------------------------------------------------------- // Kernel Function to compute distance between all pairs of points // Input: // X: X[i] = x-coordinate of the ith point // Y: Y[i] = y-coordinate of the ith point // n: number of points // Output: // D: D[0] = minimum distance // __device__ unsigned int finished_blocks = 0; __global__ void minimum_distance_kernel(float * X, float * Y, volatile float * D, int n) { unsigned int idx = blockIdx.x * blockDim.x + threadIdx.x; int i, z; float dx, dy, temp_distance; float minDist = FLT_MAX; bool finalBlockCheck; __shared__ float local_minimums[block_size]; if(idx < n - 1) { for(z = idx + 1; z<n; z++) { dx = X[z] - X[idx]; dy = Y[z] - Y[idx]; temp_distance = sqrtf(dx * dx + dy * dy); if(temp_distance < minDist) { minDist = temp_distance; } } local_minimums[threadIdx.x] = minDist; __syncthreads(); // Compute the block local minimum int max_index = (n % block_size); if(max_index == 0) { max_index = block_size; } else { if(blockIdx.x != n/block_size) { max_index = block_size; } } for(i = 1; i<max_index; i *= 2) { if(threadIdx.x % (2 * i) == 0 && (threadIdx.x + i) < max_index - 1) { if(local_minimums[threadIdx.x] > local_minimums[threadIdx.x + i]) { local_minimums[threadIdx.x] = local_minimums[threadIdx.x + i]; } __syncthreads(); } } if(threadIdx.x == 0) { D[blockIdx.x] = local_minimums[0]; int value = atomicInc(&finished_blocks, gridDim.x); finalBlockCheck = (value == (gridDim.x - 1)); } // Last thread in the list computes the global minimum and puts it in D[0] if(finalBlockCheck && threadIdx.x == 0) { int blocks = n / block_size + (n % block_size != 0); for(i = 1; i<blocks; i++) { if(D[0] > D[i]) { D[0] = D[i]; } } } } } // ---------------------------------------------------------------------------- // Host function to compute minimum distance between points // Input: // X: X[i] = x-coordinate of the ith point // Y: Y[i] = y-coordinate of the ith point // n: number of points // Output: // D: minimum distance // float minimum_distance_host(float * X, float * Y, int n) { float dx, dy, Dij, min_distance, min_distance_i; int i, j; dx = X[1]-X[0]; dy = Y[1]-Y[0]; min_distance = sqrtf(dx*dx+dy*dy); for (i = 0; i < n-1; i++) { for (j = i+1; j < i+2; j++) { dx = X[j]-X[i]; dy = Y[j]-Y[i]; min_distance_i = sqrtf(dx*dx+dy*dy); } for (j = i+1; j < n; j++) { dx = X[j]-X[i]; dy = Y[j]-Y[i]; Dij = sqrtf(dx*dx+dy*dy); if (min_distance_i > Dij) min_distance_i = Dij; } if (min_distance > min_distance_i) min_distance = min_distance_i; } return min_distance; } // ---------------------------------------------------------------------------- // Print device properties void print_device_properties() { int i, deviceCount; cudaDeviceProp deviceProp; cudaGetDeviceCount(&deviceCount); printf("------------------------------------------------------------\n"); printf("Number of GPU devices found = %d\n", deviceCount); for ( i = 0; i < deviceCount; ++i ) { cudaGetDeviceProperties(&deviceProp, i); printf("[Device: %1d] Compute Capability %d.%d.\n", i, deviceProp.major, deviceProp.minor); printf(" ... multiprocessor count = %d\n", deviceProp.multiProcessorCount); printf(" ... max threads per multiprocessor = %d\n", deviceProp.maxThreadsPerMultiProcessor); printf(" ... max threads per block = %d\n", deviceProp.maxThreadsPerBlock); printf(" ... max block dimension = %d, %d, %d (along x, y, z)\n", deviceProp.maxThreadsDim[0], deviceProp.maxThreadsDim[1], deviceProp.maxThreadsDim[2]); printf(" ... max grid size = %d, %d, %d (along x, y, z)\n", deviceProp.maxGridSize[0], deviceProp.maxGridSize[1], deviceProp.maxGridSize[2]); printf(" ... warp size = %d\n", deviceProp.warpSize); printf(" ... clock rate = %d MHz\n", deviceProp.clockRate/1000); } printf("------------------------------------------------------------\n"); } // ---------------------------------------------------------------------------- // Main program - initializes points and computes minimum distance // between the points // int main(int argc, char* argv[]) { // Host Data float * hVx; // host x-coordinate array float * hVy; // host y-coordinate array float hmin_dist; // minimum value on host // Device Data float * dVx; // device x-coordinate array float * dVy; // device x-coordinate array float * dmin_dist; // minimum value on device // Device parameters //int MAX_BLOCK_SIZE; // Maximum number of threads allowed on the device int blocks; // Number of blocks in grid //int threads_per_block; // Number of threads per block // Timing variables cudaEvent_t start, stop; // GPU timing variables struct timespec cpu_start, cpu_stop; // CPU timing variables float time_array[10]; // Other variables int i, size, num_points; float min_distance, sqrtn; int seed = 0; // Print device properties print_device_properties(); // Get device information and set device to use int deviceCount; cudaDeviceProp deviceProp; cudaGetDeviceCount(&deviceCount); if (deviceCount > 0) { cudaSetDevice(0); cudaGetDeviceProperties(&deviceProp, 0); //int MAX_BLOCK_SIZE = deviceProp.maxThreadsPerBlock; } else { printf("Warning: No GPU device found ... results may be incorrect\n"); } // Timing initializations cudaEventCreate(&start); cudaEventCreate(&stop); // Check input if (argc != 2) { printf("Use: %s <number of points>\n", argv[0]); exit(0); } if ((num_points = atoi(argv[argc-1])) < 2) { printf("Minimum number of points allowed: 2\n"); exit(0); } if ((num_points = atoi(argv[argc-1])) > MAX_POINTS) { printf("Maximum number of points allowed: %d\n", MAX_POINTS); exit(0); } // Allocate host coordinate arrays size = num_points * sizeof(float); hVx = (float *) malloc(size); hVy = (float *) malloc(size); // Initialize points srand48(seed); sqrtn = (float) sqrt(num_points); for (i = 0; i < num_points; i++) { hVx[i] = sqrtn * (float)drand48(); hVy[i] = sqrtn * (float)drand48(); } // Allocate device coordinate arrays cudaMalloc(&dVx, size); cudaMalloc(&dVy, size); cudaMalloc(&dmin_dist, size); // Copy coordinate arrays from host memory to device memory cudaEventRecord( start, 0 ); cudaMemcpy(dVx, hVx, size, cudaMemcpyHostToDevice); cudaMemcpy(dVy, hVy, size, cudaMemcpyHostToDevice); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&(time_array[0]), start, stop); // Invoke kernel cudaEventRecord( start, 0 ); blocks = num_points / block_size + (num_points % block_size != 0); minimum_distance_kernel<<<blocks, block_size>>>(dVx, dVy, dmin_dist, num_points); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&(time_array[1]), start, stop); // Copy result from device memory to host memory cudaEventRecord( start, 0 ); cudaMemcpy(&hmin_dist, dmin_dist, sizeof(float), cudaMemcpyDeviceToHost); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&(time_array[2]), start, stop); // Compute minimum distance on host to check device computation clock_gettime(CLOCK_REALTIME, &cpu_start); min_distance = minimum_distance_host(hVx, hVy, num_points); clock_gettime(CLOCK_REALTIME, &cpu_stop); time_array[3] = 1000*((cpu_stop.tv_sec-cpu_start.tv_sec) +0.000000001*(cpu_stop.tv_nsec-cpu_start.tv_nsec)); // Print results printf("Number of Points = %d\n", num_points); printf("GPU Host-to-device = %f ms \n", time_array[0]); printf("GPU Device-to-host = %f ms \n", time_array[2]); printf("GPU execution time = %f ms \n", time_array[1]); printf("CPU execution time = %f ms\n", time_array[3]); printf("Min. distance (GPU) = %e\n", hmin_dist); printf("Min. distance (CPU) = %e\n", min_distance); printf("Relative error = %e\n", fabs(min_distance-hmin_dist)/min_distance); // Free device memory cudaFree(dVx); cudaFree(dVy); cudaFree(dmin_dist); // Free host memory free(hVx); free(hVy); }
023727640a667afe55aba3db89505288442bd5f3.hip
// !!! This is a file automatically generated by hipify!!! #include "memory_operations.h" namespace Arnoldi { real* allocate_d(int N){ int size=N; real* array; array=(real*)malloc(sizeof(real)*size); if ( !array ){ fprintf(stderr,"\n unable to allocate real memeory!\n"); exit(-1); } else{ for(int i=0;i<N;i++) array[i]=0.0; } return array; } int* allocate_i(int N){ int size=(N); int* array; array=(int*)malloc(sizeof(int)*size); if ( !array ){ fprintf(stderr,"\n unable to allocate int memeory!\n"); exit(-1); } else{ for(int i=0;i<N;i++) array[i]=0; } return array; } real average(int count, ...) { va_list ap; int j; real tot = 0; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(j = 0; j < count; j++) tot += va_arg(ap, real); /* Increments ap to the next argument. */ va_end(ap); return tot / count; } void allocate_real(int Nx, int Ny, int Nz, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real** value= va_arg(ap, real**); /* Increments ap to the next argument. */ real* temp=allocate_d(Nx*Ny*Nz); value[0]=temp; } va_end(ap); } void allocate_real(int N, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real** value= va_arg(ap, real**); /* Increments ap to the next argument. */ real* temp=allocate_d(N); value[0]=temp; } va_end(ap); } void allocate_int(int Nx, int Ny, int Nz, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ int** value= va_arg(ap, int**); /* Increments ap to the next argument. */ int* temp=allocate_i(Nx*Ny*Nz); value[0]=temp; } va_end(ap); } void deallocate_real(int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real* value= va_arg(ap, real*); /* Increments ap to the next argument. */ free(value); } va_end(ap); } void deallocate_int(int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ int* value= va_arg(ap, int*); /* Increments ap to the next argument. */ free(value); } va_end(ap); } //for GPU: int* device_allocate_int(int Nx, int Ny, int Nz){ int* m_device; int mem_size=sizeof(int)*Nx*Ny*Nz; hipError_t cuerr=hipMalloc((void**)&m_device, mem_size); if (cuerr != hipSuccess) { fprintf(stderr, "Cannot allocate int device array because: %s\n", hipGetErrorString(cuerr)); exit(-1); } return m_device; } real* device_allocate_real(int Nx, int Ny, int Nz){ real* m_device; int mem_size=sizeof(real)*Nx*Ny*Nz; hipError_t cuerr=hipMalloc((void**)&m_device, mem_size); if (cuerr != hipSuccess) { fprintf(stderr, "Cannot allocate real device array because: %s\n", hipGetErrorString(cuerr)); exit(-1); } return m_device; } cublasComplex* device_allocate_complex(int Nx, int Ny, int Nz){ cublasComplex* m_device; int mem_size=sizeof(cublasComplex)*Nx*Ny*Nz; hipError_t cuerr=hipMalloc((void**)&m_device, mem_size); if (cuerr != hipSuccess) { fprintf(stderr, "Cannot allocate device complex array because: %s\n", hipGetErrorString(cuerr)); exit(-1); } return m_device; } void to_device_from_host_real_cpy(real* device, real* host, int Nx, int Ny, int Nz){ int mem_size=sizeof(real)*Nx*Ny*Nz; hipError_t cuerr=hipMemcpy(device, host, mem_size, hipMemcpyHostToDevice); if (cuerr != hipSuccess) { fprintf(stderr, "Cannot copy real array from host to device because: %s\n", hipGetErrorString(cuerr)); exit(-1); } } void to_host_from_device_real_cpy(real* host, real* device, int Nx, int Ny, int Nz){ int mem_size=sizeof(real)*Nx*Ny*Nz; hipError_t cuerr=hipMemcpy(host, device, mem_size, hipMemcpyDeviceToHost); if (cuerr != hipSuccess) { printf("Cannot copy real array from device to host because: %s\n", hipGetErrorString(cuerr)); exit(-1); } } void to_device_from_host_int_cpy(int* device, int* host, int Nx, int Ny, int Nz){ int mem_size=sizeof(int)*Nx*Ny*Nz; hipError_t cuerr=hipMemcpy(device, host, mem_size, hipMemcpyHostToDevice); if (cuerr != hipSuccess) { fprintf(stderr, "Cannot copy int array from host to device because: %s\n", hipGetErrorString(cuerr)); exit(-1); } } void to_host_from_device_int_cpy(int* host, int* device, int Nx, int Ny, int Nz){ int mem_size=sizeof(int)*Nx*Ny*Nz; hipError_t cuerr=hipMemcpy(host, device, mem_size, hipMemcpyDeviceToHost); if (cuerr != hipSuccess) { printf("Cannot copy real int from device to host because: %s\n", hipGetErrorString(cuerr)); exit(-1); } } void device_allocate_all_real(int Nx, int Ny, int Nz, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real** value=va_arg(ap, real**); /* Increments ap to the next argument. */ real* temp=device_allocate_real(Nx, Ny, Nz); value[0]=temp; } va_end(ap); } void device_deallocate_all_real(int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real* value=va_arg(ap, real*); /* Increments ap to the next argument. */ hipError_t cuerr = hipFree(value); if (cuerr != hipSuccess) { printf("Cannot copy real int from device to host because: %s\n", hipGetErrorString(cuerr)); } } va_end(ap); } }
023727640a667afe55aba3db89505288442bd5f3.cu
#include "memory_operations.h" namespace Arnoldi { real* allocate_d(int N){ int size=N; real* array; array=(real*)malloc(sizeof(real)*size); if ( !array ){ fprintf(stderr,"\n unable to allocate real memeory!\n"); exit(-1); } else{ for(int i=0;i<N;i++) array[i]=0.0; } return array; } int* allocate_i(int N){ int size=(N); int* array; array=(int*)malloc(sizeof(int)*size); if ( !array ){ fprintf(stderr,"\n unable to allocate int memeory!\n"); exit(-1); } else{ for(int i=0;i<N;i++) array[i]=0; } return array; } real average(int count, ...) { va_list ap; int j; real tot = 0; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(j = 0; j < count; j++) tot += va_arg(ap, real); /* Increments ap to the next argument. */ va_end(ap); return tot / count; } void allocate_real(int Nx, int Ny, int Nz, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real** value= va_arg(ap, real**); /* Increments ap to the next argument. */ real* temp=allocate_d(Nx*Ny*Nz); value[0]=temp; } va_end(ap); } void allocate_real(int N, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real** value= va_arg(ap, real**); /* Increments ap to the next argument. */ real* temp=allocate_d(N); value[0]=temp; } va_end(ap); } void allocate_int(int Nx, int Ny, int Nz, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ int** value= va_arg(ap, int**); /* Increments ap to the next argument. */ int* temp=allocate_i(Nx*Ny*Nz); value[0]=temp; } va_end(ap); } void deallocate_real(int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real* value= va_arg(ap, real*); /* Increments ap to the next argument. */ free(value); } va_end(ap); } void deallocate_int(int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ int* value= va_arg(ap, int*); /* Increments ap to the next argument. */ free(value); } va_end(ap); } //for GPU: int* device_allocate_int(int Nx, int Ny, int Nz){ int* m_device; int mem_size=sizeof(int)*Nx*Ny*Nz; cudaError_t cuerr=cudaMalloc((void**)&m_device, mem_size); if (cuerr != cudaSuccess) { fprintf(stderr, "Cannot allocate int device array because: %s\n", cudaGetErrorString(cuerr)); exit(-1); } return m_device; } real* device_allocate_real(int Nx, int Ny, int Nz){ real* m_device; int mem_size=sizeof(real)*Nx*Ny*Nz; cudaError_t cuerr=cudaMalloc((void**)&m_device, mem_size); if (cuerr != cudaSuccess) { fprintf(stderr, "Cannot allocate real device array because: %s\n", cudaGetErrorString(cuerr)); exit(-1); } return m_device; } cublasComplex* device_allocate_complex(int Nx, int Ny, int Nz){ cublasComplex* m_device; int mem_size=sizeof(cublasComplex)*Nx*Ny*Nz; cudaError_t cuerr=cudaMalloc((void**)&m_device, mem_size); if (cuerr != cudaSuccess) { fprintf(stderr, "Cannot allocate device complex array because: %s\n", cudaGetErrorString(cuerr)); exit(-1); } return m_device; } void to_device_from_host_real_cpy(real* device, real* host, int Nx, int Ny, int Nz){ int mem_size=sizeof(real)*Nx*Ny*Nz; cudaError_t cuerr=cudaMemcpy(device, host, mem_size, cudaMemcpyHostToDevice); if (cuerr != cudaSuccess) { fprintf(stderr, "Cannot copy real array from host to device because: %s\n", cudaGetErrorString(cuerr)); exit(-1); } } void to_host_from_device_real_cpy(real* host, real* device, int Nx, int Ny, int Nz){ int mem_size=sizeof(real)*Nx*Ny*Nz; cudaError_t cuerr=cudaMemcpy(host, device, mem_size, cudaMemcpyDeviceToHost); if (cuerr != cudaSuccess) { printf("Cannot copy real array from device to host because: %s\n", cudaGetErrorString(cuerr)); exit(-1); } } void to_device_from_host_int_cpy(int* device, int* host, int Nx, int Ny, int Nz){ int mem_size=sizeof(int)*Nx*Ny*Nz; cudaError_t cuerr=cudaMemcpy(device, host, mem_size, cudaMemcpyHostToDevice); if (cuerr != cudaSuccess) { fprintf(stderr, "Cannot copy int array from host to device because: %s\n", cudaGetErrorString(cuerr)); exit(-1); } } void to_host_from_device_int_cpy(int* host, int* device, int Nx, int Ny, int Nz){ int mem_size=sizeof(int)*Nx*Ny*Nz; cudaError_t cuerr=cudaMemcpy(host, device, mem_size, cudaMemcpyDeviceToHost); if (cuerr != cudaSuccess) { printf("Cannot copy real int from device to host because: %s\n", cudaGetErrorString(cuerr)); exit(-1); } } void device_allocate_all_real(int Nx, int Ny, int Nz, int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real** value=va_arg(ap, real**); /* Increments ap to the next argument. */ real* temp=device_allocate_real(Nx, Ny, Nz); value[0]=temp; } va_end(ap); } void device_deallocate_all_real(int count, ...){ va_list ap; va_start(ap, count); /* Requires the last fixed parameter (to get the address) */ for(int j = 0; j < count; j++){ real* value=va_arg(ap, real*); /* Increments ap to the next argument. */ cudaError_t cuerr = cudaFree(value); if (cuerr != cudaSuccess) { printf("Cannot copy real int from device to host because: %s\n", cudaGetErrorString(cuerr)); } } va_end(ap); } }
39a54e6bc6846ac6851e509897f2e74a6e59a1a5.hip
// !!! This is a file automatically generated by hipify!!! #include "H_Matrix.cuh" #include "D_Matrix.cuh" #include <algorithm> // returns a new random matrix of size nxn H_Matrix H_Matrix::random(const int n) { H_Matrix result(n); const unsigned int dec = ::max(static_cast<unsigned int>(ceilf(log2f(RAND_MAX)))-4u,4u); for (int i = 0; i < n*n; ++i) result.h_val[i] = std::rand() >> dec; return result; } // creates a D_Matrix from a H_Matrix D_Matrix H_Matrix::export2Device() const { D_Matrix result(m_n); thrust::copy(h_val.begin(), h_val.end(), result.d_val); return result; } // check equality (with an epsilon) bool H_Matrix::operator==(const H_Matrix& that) const { if (m_n != that.m_n) return false; for (int i = m_n*m_n; i-- > 0;) if (h_val[i] != that.h_val[i]) return false; return true; } // returns this times that ... H_Matrix H_Matrix::operator*(const H_Matrix& that) const { if (m_n != that.m_n) throw "bad product (incompatible matrices)"; H_Matrix result(m_n); for (int row = m_n; row--; ) { for (int col = m_n; col--; ) { int sum = 0; for (int k = m_n; k--; ) { // sum += A[row,k] * B[k,col] sum += h_val[row*m_n + k] * that.h_val[k*m_n + col]; } result.h_val[row*m_n + col] = sum; } } return result; } // returns this plus that ... H_Matrix H_Matrix::operator+(const H_Matrix& that) const { if (m_n != that.m_n) throw "bad product (incompatible matrices)"; H_Matrix result(m_n); for (int idx = m_n*m_n; idx-- > 0; ) { result.h_val[idx] = h_val[idx] + that.h_val[idx]; } return result; } // diffuse this matrix for a given line number ... void H_Matrix::diffusion(const int line, H_Matrix& that) const { for(int l=0; l<m_n; ++l) { // copies one line from position "line" to position l*m_n memcpy(&that.h_val[l*m_n], &h_val[line*m_n], m_n * sizeof(int)); } } // returns transposition of this H_Matrix H_Matrix::transpose() const { H_Matrix result(m_n); for (int row = 0; row < m_n; row++) for (int col = 0; col < m_n; col++) result.h_val[col*m_n + row] = h_val[row*m_n + col]; return result; }
39a54e6bc6846ac6851e509897f2e74a6e59a1a5.cu
#include "H_Matrix.cuh" #include "D_Matrix.cuh" #include <algorithm> // returns a new random matrix of size nxn H_Matrix H_Matrix::random(const int n) { H_Matrix result(n); const unsigned int dec = std::max(static_cast<unsigned int>(ceilf(log2f(RAND_MAX)))-4u,4u); for (int i = 0; i < n*n; ++i) result.h_val[i] = std::rand() >> dec; return result; } // creates a D_Matrix from a H_Matrix D_Matrix H_Matrix::export2Device() const { D_Matrix result(m_n); thrust::copy(h_val.begin(), h_val.end(), result.d_val); return result; } // check equality (with an epsilon) bool H_Matrix::operator==(const H_Matrix& that) const { if (m_n != that.m_n) return false; for (int i = m_n*m_n; i-- > 0;) if (h_val[i] != that.h_val[i]) return false; return true; } // returns this times that ... H_Matrix H_Matrix::operator*(const H_Matrix& that) const { if (m_n != that.m_n) throw "bad product (incompatible matrices)"; H_Matrix result(m_n); for (int row = m_n; row--; ) { for (int col = m_n; col--; ) { int sum = 0; for (int k = m_n; k--; ) { // sum += A[row,k] * B[k,col] sum += h_val[row*m_n + k] * that.h_val[k*m_n + col]; } result.h_val[row*m_n + col] = sum; } } return result; } // returns this plus that ... H_Matrix H_Matrix::operator+(const H_Matrix& that) const { if (m_n != that.m_n) throw "bad product (incompatible matrices)"; H_Matrix result(m_n); for (int idx = m_n*m_n; idx-- > 0; ) { result.h_val[idx] = h_val[idx] + that.h_val[idx]; } return result; } // diffuse this matrix for a given line number ... void H_Matrix::diffusion(const int line, H_Matrix& that) const { for(int l=0; l<m_n; ++l) { // copies one line from position "line" to position l*m_n memcpy(&that.h_val[l*m_n], &h_val[line*m_n], m_n * sizeof(int)); } } // returns transposition of this H_Matrix H_Matrix::transpose() const { H_Matrix result(m_n); for (int row = 0; row < m_n; row++) for (int col = 0; col < m_n; col++) result.h_val[col*m_n + row] = h_val[row*m_n + col]; return result; }
c28d939cb7803748aa69a2caeb8f97fa878de7b1.hip
// !!! This is a file automatically generated by hipify!!! /*------------------------------------------------------------------------- * * CUDA functions for ray-voxel intersection based projection * * This file has the necesary fucntiosn to perform X-ray parallel projection * operation given a geaometry, angles and image. It usesthe so-called * Jacobs algorithm to compute efficiently the length of the x-rays over * voxel space. Its called Siddon because Jacobs algorithm its just a small * improvement over the traditional Siddons method. * * CODE by Ander Biguri * --------------------------------------------------------------------------- --------------------------------------------------------------------------- Copyright (c) 2015, University of Bath and CERN- European Organization for Nuclear Research All rights reserved. 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. Neither the name of the copyright holder 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 HOLDER 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. --------------------------------------------------------------------------- Contact: tigre.toolbox@gmail.com Codes : https://github.com/CERN/TIGRE --------------------------------------------------------------------------- */ #include <algorithm> #include <hip/hip_runtime_api.h> #include <hip/hip_runtime.h> #include "Siddon_projection_parallel.hpp" #include "mex.h" #include <math.h> #define cudaCheckErrors(msg) \ do { \ hipError_t __err = hipGetLastError(); \ if (__err != hipSuccess) { \ mexPrintf("%s \n",msg);\ mexErrMsgIdAndTxt("CBCT:CUDA:Atb",hipGetErrorString(__err));\ } \ } while (0) // Declare the texture reference. texture<float, hipTextureType3D , hipReadModeElementType> tex; #define MAXTREADS 1024 /*GEOMETRY DEFINITION * * Detector plane, behind * |-----------------------------| * | | * | | * | | * | | * | +--------+ | * | / /| | * A Z | / / |*D | * | | +--------+ | | * | | | | | | * | | | *O | + | * --->y | | | / | * / | | |/ | * V X | +--------+ | * |-----------------------------| * * *S * * * * * **/ __global__ void kernelPixelDetector_parallel( Geometry geo, float* detector, Point3D source , Point3D deltaU, Point3D deltaV, Point3D uvOrigin){ // size_t idx = threadIdx.x + blockIdx.x * blockDim.x; unsigned long y = blockIdx.y * blockDim.y + threadIdx.y; unsigned long x = blockIdx.x * blockDim.x + threadIdx.x; unsigned long idx = x * geo.nDetecV + y; if ((x>= geo.nDetecU) | (y>= geo.nDetecV)) return; /////// Get coordinates XYZ of pixel UV int pixelV = geo.nDetecV-y-1; int pixelU = x; Point3D pixel1D; pixel1D.x=(uvOrigin.x+pixelU*deltaU.x+pixelV*deltaV.x); pixel1D.y=(uvOrigin.y+pixelU*deltaU.y+pixelV*deltaV.y); pixel1D.z=(uvOrigin.z+pixelU*deltaU.z+pixelV*deltaV.z); source.x=(source.x+pixelU*deltaU.x+pixelV*deltaV.x); source.y=(source.y+pixelU*deltaU.y+pixelV*deltaV.y); source.z=(source.z+pixelU*deltaU.z+pixelV*deltaV.z); /////// // Siddon's ray-voxel intersection, optimized as in doi=10.1.1.55.7516 ////// Point3D ray; // vector of Xray ray.x=pixel1D.x-source.x; ray.y=pixel1D.y-source.y; ray.z=pixel1D.z-source.z; // This variables are ommited because // bx,by,bz ={0,0,0} // dx,dy,dz ={1,1,1} // compute parameter values for x-ray parametric equation. eq(3-10) float axm,aym,azm; float axM,ayM,azM; /************************************** * * * Problem. In paralel beam, often ray.y or ray.x=0; * This leads to infinities progpagating and breaking everything. * * We need to fix it. * ***************************************/ // In the paper Nx= number of X planes-> Nvoxel+1 axm=min(-source.x/ray.x,(geo.nVoxelX-source.x)/ray.x); aym=min(-source.y/ray.y,(geo.nVoxelY-source.y)/ray.y); // azm=min(-source.z/ray.z,(geo.nVoxelZ-source.z)/ray.z); axM=max(-source.x/ray.x,(geo.nVoxelX-source.x)/ray.x); ayM=max(-source.y/ray.y,(geo.nVoxelY-source.y)/ray.y); // azM=max(-source.z/ray.z,(geo.nVoxelZ-source.z)/ray.z); float am=(max(axm,aym)); float aM=(min(axM,ayM)); // line intersects voxel space -> am<aM if (am>=aM) detector[idx]=0; // Compute max/min image INDEX for intersection eq(11-19) // Discussion about ternary operator in CUDA: https://stackoverflow.com/questions/7104384/in-cuda-why-is-a-b010-more-efficient-than-an-if-else-version float imin,imax,jmin,jmax; // for X if( source.x<pixel1D.x){ imin=(am==axm)? 1 : ceil (source.x+am*ray.x); imax=(aM==axM)? geo.nVoxelX : floor(source.x+aM*ray.x); }else{ imax=(am==axm)? geo.nVoxelX-1 : floor(source.x+am*ray.x); imin=(aM==axM)? 0 : ceil (source.x+aM*ray.x); } // for Y if( source.y<pixel1D.y){ jmin=(am==aym)? 1 : ceil (source.y+am*ray.y); jmax=(aM==ayM)? geo.nVoxelY : floor(source.y+aM*ray.y); }else{ jmax=(am==aym)? geo.nVoxelY-1 : floor(source.y+am*ray.y); jmin=(aM==ayM)? 0 : ceil (source.y+aM*ray.y); } // // for Z // if( source.z<pixel1D.z){ // kmin=(am==azm)? 1 : ceil (source.z+am*ray.z); // kmax=(aM==azM)? geo.nVoxelZ : floor(source.z+aM*ray.z); // }else{ // kmax=(am==azm)? geo.nVoxelZ-1 : floor(source.z+am*ray.z); // kmin=(aM==azM)? 0 : ceil (source.z+aM*ray.z); // } // get intersection point N1. eq(20-21) [(also eq 9-10)] float ax,ay; ax=(source.x<pixel1D.x)? (imin-source.x)/(ray.x+0.000000000001) : (imax-source.x)/(ray.x+0.000000000001); ay=(source.y<pixel1D.y)? (jmin-source.y)/(ray.y+0.000000000001) : (jmax-source.y)/(ray.y+0.000000000001); // az=(source.z<pixel1D.z)? (kmin-source.z)/ray.z : (kmax-source.z)/ray.z; // get index of first intersection. eq (26) and (19) int i,j,k; float aminc=min(ax,ay); i=(int)floor(source.x+ (aminc+am)/2*ray.x); j=(int)floor(source.y+ (aminc+am)/2*ray.y); k=(int)floor(source.z+ (aminc+am)/2*ray.z); // k=(int)source.z; // Initialize float ac=am; //eq (28), unit angles float axu,ayu; axu=1/abs(ray.x); ayu=1/abs(ray.y); // azu=1/abs(ray.z); // eq(29), direction of update float iu,ju; iu=(source.x< pixel1D.x)? 1 : -1; ju=(source.y< pixel1D.y)? 1 : -1; // ku=(source.z< pixel1D.z)? 1 : -1; float maxlength=sqrt(ray.x*ray.x*geo.dVoxelX*geo.dVoxelX+ray.y*ray.y*geo.dVoxelY*geo.dVoxelY);//+ray.z*ray.z*geo.dVoxelZ*geo.dVoxelZ); float sum=0; unsigned int Np=(imax-imin+1)+(jmax-jmin+1);//+(kmax-kmin+1); // Number of intersections // Go iterating over the line, intersection by intersection. If double point, no worries, 0 will be computed for (unsigned int ii=0;ii<Np;ii++){ if (ax==aminc){ sum+=(ax-ac)*tex3D(tex, i+0.5, j+0.5, k+0.5);//(ax-ac)* i=i+iu; ac=ax; ax+=axu; }else if(ay==aminc){ sum+=(ay-ac)*tex3D(tex, i+0.5, j+0.5, k+0.5);//(ay-ac)* j=j+ju; ac=ay; ay+=ayu; // }else if(az==aminc){ // sum+=(az-ac)*tex3D(tex, i+0.5, j+0.5, k+0.5); // k=k+ku; // ac=az; // az+=azu; } aminc=min(ay,ax); } detector[idx]=maxlength*sum; } int siddon_ray_projection_parallel(float const * const img, Geometry geo, float** result,float const * const angles,int nangles){ // copy data to CUDA memory hipArray *d_imagedata = 0; const hipExtent extent = make_hipExtent(geo.nVoxelX, geo.nVoxelY, geo.nVoxelZ); hipChannelFormatDesc channelDesc = hipCreateChannelDesc<float>(); hipMalloc3DArray(&d_imagedata, &channelDesc, extent); cudaCheckErrors("hipMalloc3D error 3D tex"); hipMemcpy3DParms copyParams = { 0 }; copyParams.srcPtr = make_hipPitchedPtr((void*)img, extent.width*sizeof(float), extent.width, extent.height); copyParams.dstArray = d_imagedata; copyParams.extent = extent; copyParams.kind = hipMemcpyHostToDevice; hipMemcpy3D(&copyParams); cudaCheckErrors("hipMemcpy3D fail"); // Configure texture options tex.normalized = false; tex.filterMode = hipFilterModePoint; //we dotn want itnerpolation tex.addressMode[0] = hipAddressModeBorder; tex.addressMode[1] = hipAddressModeBorder; tex.addressMode[2] = hipAddressModeBorder; hipBindTextureToArray(tex, d_imagedata, channelDesc); cudaCheckErrors("3D texture memory bind fail"); //Done! Image put into texture memory. size_t num_bytes = geo.nDetecU*geo.nDetecV * sizeof(float); float* dProjection; hipMalloc((void**)&dProjection, num_bytes); cudaCheckErrors("hipMalloc fail"); bool timekernel=false; hipEvent_t start, stop; float elapsedTime; if (timekernel){ hipEventCreate(&start); hipEventRecord(start,0); } Point3D source, deltaU, deltaV, uvOrigin; // 16x16 gave the best performance empirically // Funnily that makes it compatible with most GPUs..... int divU,divV; divU=16; divV=16; dim3 grid((geo.nDetecU+divU-1)/divU,(geo.nDetecV+divV-1)/divV,1); dim3 block(divU,divV,1); for (int i=0;i<nangles;i++){ geo.alpha=angles[i*3]; geo.theta=angles[i*3+1]; geo.psi =angles[i*3+2]; if(geo.alpha==0.0 || abs(geo.alpha-1.5707963267949)<0.0000001){ geo.alpha=geo.alpha+1.1920929e-07; } //precomute distances for faster execution //Precompute per angle constant stuff for speed computeDeltas_Siddon_parallel(geo,geo.alpha,i, &uvOrigin, &deltaU, &deltaV, &source); //Ray tracing! hipLaunchKernelGGL(( kernelPixelDetector_parallel), dim3(grid),dim3(block), 0, 0, geo,dProjection, source, deltaU, deltaV, uvOrigin); cudaCheckErrors("Kernel fail"); // copy result to host hipMemcpy(result[i], dProjection, num_bytes, hipMemcpyDeviceToHost); cudaCheckErrors("hipMemcpy fail"); } if (timekernel){ hipEventCreate(&stop); hipEventRecord(stop,0); hipEventSynchronize(stop); hipEventElapsedTime(&elapsedTime, start,stop); mexPrintf("%f\n" ,elapsedTime); } hipUnbindTexture(tex); cudaCheckErrors("Unbind fail"); hipFree(dProjection); hipFreeArray(d_imagedata); cudaCheckErrors("hipFree d_imagedata fail"); hipDeviceReset(); return 0; } /* This code precomputes The location of the source and the Delta U and delta V (in the warped space) * to compute the locations of the x-rays. While it seems verbose and overly-optimized, * it does saves about 30% of each of the kernel calls. Thats something! **/ void computeDeltas_Siddon_parallel(Geometry geo, float angles,int i, Point3D* uvorigin, Point3D* deltaU, Point3D* deltaV, Point3D* source){ Point3D S; S.x =geo.DSO[i]; S.y = geo.dDetecU*(0-((float)geo.nDetecU/2)+0.5); S.z = geo.dDetecV*(((float)geo.nDetecV/2)-0.5-0); //End point Point3D P,Pu0,Pv0; P.x =-(geo.DSD[i]-geo.DSO[i]); P.y = geo.dDetecU*(0-((float)geo.nDetecU/2)+0.5); P.z = geo.dDetecV*(((float)geo.nDetecV/2)-0.5-0); Pu0.x=-(geo.DSD[i]-geo.DSO[i]); Pu0.y= geo.dDetecU*(1-((float)geo.nDetecU/2)+0.5); Pu0.z= geo.dDetecV*(((float)geo.nDetecV/2)-0.5-0); Pv0.x=-(geo.DSD[i]-geo.DSO[i]); Pv0.y= geo.dDetecU*(0-((float)geo.nDetecU/2)+0.5); Pv0.z= geo.dDetecV*(((float)geo.nDetecV/2)-0.5-1); // Geomtric trasnformations: //1: Offset detector //P.x P.y =P.y +geo.offDetecU[i]; P.z =P.z +geo.offDetecV[i]; Pu0.y=Pu0.y+geo.offDetecU[i]; Pu0.z=Pu0.z+geo.offDetecV[i]; Pv0.y=Pv0.y+geo.offDetecU[i]; Pv0.z=Pv0.z+geo.offDetecV[i]; //S doesnt need to chagne //3: Rotate (around z)! Point3D Pfinal, Pfinalu0, Pfinalv0; Pfinal.x =P.x*cos(geo.alpha)-P.y*sin(geo.alpha); Pfinal.y =P.y*cos(geo.alpha)+P.x*sin(geo.alpha); Pfinal.z =P.z; Pfinalu0.x=Pu0.x*cos(geo.alpha)-Pu0.y*sin(geo.alpha); Pfinalu0.y=Pu0.y*cos(geo.alpha)+Pu0.x*sin(geo.alpha); Pfinalu0.z=Pu0.z; Pfinalv0.x=Pv0.x*cos(geo.alpha)-Pv0.y*sin(geo.alpha); Pfinalv0.y=Pv0.y*cos(geo.alpha)+Pv0.x*sin(geo.alpha); Pfinalv0.z=Pv0.z; Point3D S2; S2.x=S.x*cos(geo.alpha)-S.y*sin(geo.alpha); S2.y=S.y*cos(geo.alpha)+S.x*sin(geo.alpha); S2.z=S.z; //2: Offset image (instead of offseting image, -offset everything else) Pfinal.x =Pfinal.x-geo.offOrigX[i]; Pfinal.y =Pfinal.y-geo.offOrigY[i]; Pfinal.z =Pfinal.z-geo.offOrigZ[i]; Pfinalu0.x=Pfinalu0.x-geo.offOrigX[i]; Pfinalu0.y=Pfinalu0.y-geo.offOrigY[i]; Pfinalu0.z=Pfinalu0.z-geo.offOrigZ[i]; Pfinalv0.x=Pfinalv0.x-geo.offOrigX[i]; Pfinalv0.y=Pfinalv0.y-geo.offOrigY[i]; Pfinalv0.z=Pfinalv0.z-geo.offOrigZ[i]; S2.x=S2.x-geo.offOrigX[i]; S2.y=S2.y-geo.offOrigY[i]; S2.z=S2.z-geo.offOrigZ[i]; // As we want the (0,0,0) to be in a corner of the image, we need to translate everything (after rotation); Pfinal.x =Pfinal.x+geo.sVoxelX/2; Pfinal.y =Pfinal.y+geo.sVoxelY/2; Pfinal.z =Pfinal.z +geo.sVoxelZ/2; Pfinalu0.x=Pfinalu0.x+geo.sVoxelX/2; Pfinalu0.y=Pfinalu0.y+geo.sVoxelY/2; Pfinalu0.z=Pfinalu0.z+geo.sVoxelZ/2; Pfinalv0.x=Pfinalv0.x+geo.sVoxelX/2; Pfinalv0.y=Pfinalv0.y+geo.sVoxelY/2; Pfinalv0.z=Pfinalv0.z+geo.sVoxelZ/2; S2.x =S2.x+geo.sVoxelX/2; S2.y =S2.y+geo.sVoxelY/2; S2.z =S2.z +geo.sVoxelZ/2; //4. Scale everything so dVoxel==1 Pfinal.x =Pfinal.x/geo.dVoxelX; Pfinal.y =Pfinal.y/geo.dVoxelY; Pfinal.z =Pfinal.z/geo.dVoxelZ; Pfinalu0.x=Pfinalu0.x/geo.dVoxelX; Pfinalu0.y=Pfinalu0.y/geo.dVoxelY; Pfinalu0.z=Pfinalu0.z/geo.dVoxelZ; Pfinalv0.x=Pfinalv0.x/geo.dVoxelX; Pfinalv0.y=Pfinalv0.y/geo.dVoxelY; Pfinalv0.z=Pfinalv0.z/geo.dVoxelZ; S2.x =S2.x/geo.dVoxelX; S2.y =S2.y/geo.dVoxelY; S2.z =S2.z/geo.dVoxelZ; //5. apply COR. Wherever everything was, now its offesetd by a bit float CORx, CORy; CORx=-geo.COR[i]*sin(geo.alpha)/geo.dVoxelX; CORy= geo.COR[i]*cos(geo.alpha)/geo.dVoxelY; Pfinal.x+=CORx; Pfinal.y+=CORy; Pfinalu0.x+=CORx; Pfinalu0.y+=CORy; Pfinalv0.x+=CORx; Pfinalv0.y+=CORy; S2.x+=CORx; S2.y+=CORy; // return *uvorigin=Pfinal; deltaU->x=Pfinalu0.x-Pfinal.x; deltaU->y=Pfinalu0.y-Pfinal.y; deltaU->z=Pfinalu0.z-Pfinal.z; deltaV->x=Pfinalv0.x-Pfinal.x; deltaV->y=Pfinalv0.y-Pfinal.y; deltaV->z=Pfinalv0.z-Pfinal.z; *source=S2; } #ifndef PROJECTION_HPP float maxDistanceCubeXY(Geometry geo, float angles,int i){ /////////// // Compute initial "t" so we access safely as less as out of bounds as possible. ////////// float maxCubX,maxCubY; // Forgetting Z, compute max distance: diagonal+offset maxCubX=(geo.sVoxelX/2+ abs(geo.offOrigX[i]))/geo.dVoxelX; maxCubY=(geo.sVoxelY/2+ abs(geo.offOrigY[i]))/geo.dVoxelY; return geo.DSO[i]/geo.dVoxelX-sqrt(maxCubX*maxCubX+maxCubY*maxCubY); } #endif
c28d939cb7803748aa69a2caeb8f97fa878de7b1.cu
/*------------------------------------------------------------------------- * * CUDA functions for ray-voxel intersection based projection * * This file has the necesary fucntiosn to perform X-ray parallel projection * operation given a geaometry, angles and image. It usesthe so-called * Jacobs algorithm to compute efficiently the length of the x-rays over * voxel space. Its called Siddon because Jacobs algorithm its just a small * improvement over the traditional Siddons method. * * CODE by Ander Biguri * --------------------------------------------------------------------------- --------------------------------------------------------------------------- Copyright (c) 2015, University of Bath and CERN- European Organization for Nuclear Research All rights reserved. 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. Neither the name of the copyright holder 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 HOLDER 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. --------------------------------------------------------------------------- Contact: tigre.toolbox@gmail.com Codes : https://github.com/CERN/TIGRE --------------------------------------------------------------------------- */ #include <algorithm> #include <cuda_runtime_api.h> #include <cuda.h> #include "Siddon_projection_parallel.hpp" #include "mex.h" #include <math.h> #define cudaCheckErrors(msg) \ do { \ cudaError_t __err = cudaGetLastError(); \ if (__err != cudaSuccess) { \ mexPrintf("%s \n",msg);\ mexErrMsgIdAndTxt("CBCT:CUDA:Atb",cudaGetErrorString(__err));\ } \ } while (0) // Declare the texture reference. texture<float, cudaTextureType3D , cudaReadModeElementType> tex; #define MAXTREADS 1024 /*GEOMETRY DEFINITION * * Detector plane, behind * |-----------------------------| * | | * | | * | | * | | * | +--------+ | * | / /| | * A Z | / / |*D | * | | +--------+ | | * | | | | | | * | | | *O | + | * --->y | | | / | * / | | |/ | * V X | +--------+ | * |-----------------------------| * * *S * * * * * **/ __global__ void kernelPixelDetector_parallel( Geometry geo, float* detector, Point3D source , Point3D deltaU, Point3D deltaV, Point3D uvOrigin){ // size_t idx = threadIdx.x + blockIdx.x * blockDim.x; unsigned long y = blockIdx.y * blockDim.y + threadIdx.y; unsigned long x = blockIdx.x * blockDim.x + threadIdx.x; unsigned long idx = x * geo.nDetecV + y; if ((x>= geo.nDetecU) | (y>= geo.nDetecV)) return; /////// Get coordinates XYZ of pixel UV int pixelV = geo.nDetecV-y-1; int pixelU = x; Point3D pixel1D; pixel1D.x=(uvOrigin.x+pixelU*deltaU.x+pixelV*deltaV.x); pixel1D.y=(uvOrigin.y+pixelU*deltaU.y+pixelV*deltaV.y); pixel1D.z=(uvOrigin.z+pixelU*deltaU.z+pixelV*deltaV.z); source.x=(source.x+pixelU*deltaU.x+pixelV*deltaV.x); source.y=(source.y+pixelU*deltaU.y+pixelV*deltaV.y); source.z=(source.z+pixelU*deltaU.z+pixelV*deltaV.z); /////// // Siddon's ray-voxel intersection, optimized as in doi=10.1.1.55.7516 ////// Point3D ray; // vector of Xray ray.x=pixel1D.x-source.x; ray.y=pixel1D.y-source.y; ray.z=pixel1D.z-source.z; // This variables are ommited because // bx,by,bz ={0,0,0} // dx,dy,dz ={1,1,1} // compute parameter values for x-ray parametric equation. eq(3-10) float axm,aym,azm; float axM,ayM,azM; /************************************** * * * Problem. In paralel beam, often ray.y or ray.x=0; * This leads to infinities progpagating and breaking everything. * * We need to fix it. * ***************************************/ // In the paper Nx= number of X planes-> Nvoxel+1 axm=min(-source.x/ray.x,(geo.nVoxelX-source.x)/ray.x); aym=min(-source.y/ray.y,(geo.nVoxelY-source.y)/ray.y); // azm=min(-source.z/ray.z,(geo.nVoxelZ-source.z)/ray.z); axM=max(-source.x/ray.x,(geo.nVoxelX-source.x)/ray.x); ayM=max(-source.y/ray.y,(geo.nVoxelY-source.y)/ray.y); // azM=max(-source.z/ray.z,(geo.nVoxelZ-source.z)/ray.z); float am=(max(axm,aym)); float aM=(min(axM,ayM)); // line intersects voxel space -> am<aM if (am>=aM) detector[idx]=0; // Compute max/min image INDEX for intersection eq(11-19) // Discussion about ternary operator in CUDA: https://stackoverflow.com/questions/7104384/in-cuda-why-is-a-b010-more-efficient-than-an-if-else-version float imin,imax,jmin,jmax; // for X if( source.x<pixel1D.x){ imin=(am==axm)? 1 : ceil (source.x+am*ray.x); imax=(aM==axM)? geo.nVoxelX : floor(source.x+aM*ray.x); }else{ imax=(am==axm)? geo.nVoxelX-1 : floor(source.x+am*ray.x); imin=(aM==axM)? 0 : ceil (source.x+aM*ray.x); } // for Y if( source.y<pixel1D.y){ jmin=(am==aym)? 1 : ceil (source.y+am*ray.y); jmax=(aM==ayM)? geo.nVoxelY : floor(source.y+aM*ray.y); }else{ jmax=(am==aym)? geo.nVoxelY-1 : floor(source.y+am*ray.y); jmin=(aM==ayM)? 0 : ceil (source.y+aM*ray.y); } // // for Z // if( source.z<pixel1D.z){ // kmin=(am==azm)? 1 : ceil (source.z+am*ray.z); // kmax=(aM==azM)? geo.nVoxelZ : floor(source.z+aM*ray.z); // }else{ // kmax=(am==azm)? geo.nVoxelZ-1 : floor(source.z+am*ray.z); // kmin=(aM==azM)? 0 : ceil (source.z+aM*ray.z); // } // get intersection point N1. eq(20-21) [(also eq 9-10)] float ax,ay; ax=(source.x<pixel1D.x)? (imin-source.x)/(ray.x+0.000000000001) : (imax-source.x)/(ray.x+0.000000000001); ay=(source.y<pixel1D.y)? (jmin-source.y)/(ray.y+0.000000000001) : (jmax-source.y)/(ray.y+0.000000000001); // az=(source.z<pixel1D.z)? (kmin-source.z)/ray.z : (kmax-source.z)/ray.z; // get index of first intersection. eq (26) and (19) int i,j,k; float aminc=min(ax,ay); i=(int)floor(source.x+ (aminc+am)/2*ray.x); j=(int)floor(source.y+ (aminc+am)/2*ray.y); k=(int)floor(source.z+ (aminc+am)/2*ray.z); // k=(int)source.z; // Initialize float ac=am; //eq (28), unit angles float axu,ayu; axu=1/abs(ray.x); ayu=1/abs(ray.y); // azu=1/abs(ray.z); // eq(29), direction of update float iu,ju; iu=(source.x< pixel1D.x)? 1 : -1; ju=(source.y< pixel1D.y)? 1 : -1; // ku=(source.z< pixel1D.z)? 1 : -1; float maxlength=sqrt(ray.x*ray.x*geo.dVoxelX*geo.dVoxelX+ray.y*ray.y*geo.dVoxelY*geo.dVoxelY);//+ray.z*ray.z*geo.dVoxelZ*geo.dVoxelZ); float sum=0; unsigned int Np=(imax-imin+1)+(jmax-jmin+1);//+(kmax-kmin+1); // Number of intersections // Go iterating over the line, intersection by intersection. If double point, no worries, 0 will be computed for (unsigned int ii=0;ii<Np;ii++){ if (ax==aminc){ sum+=(ax-ac)*tex3D(tex, i+0.5, j+0.5, k+0.5);//(ax-ac)* i=i+iu; ac=ax; ax+=axu; }else if(ay==aminc){ sum+=(ay-ac)*tex3D(tex, i+0.5, j+0.5, k+0.5);//(ay-ac)* j=j+ju; ac=ay; ay+=ayu; // }else if(az==aminc){ // sum+=(az-ac)*tex3D(tex, i+0.5, j+0.5, k+0.5); // k=k+ku; // ac=az; // az+=azu; } aminc=min(ay,ax); } detector[idx]=maxlength*sum; } int siddon_ray_projection_parallel(float const * const img, Geometry geo, float** result,float const * const angles,int nangles){ // copy data to CUDA memory cudaArray *d_imagedata = 0; const cudaExtent extent = make_cudaExtent(geo.nVoxelX, geo.nVoxelY, geo.nVoxelZ); cudaChannelFormatDesc channelDesc = cudaCreateChannelDesc<float>(); cudaMalloc3DArray(&d_imagedata, &channelDesc, extent); cudaCheckErrors("cudaMalloc3D error 3D tex"); cudaMemcpy3DParms copyParams = { 0 }; copyParams.srcPtr = make_cudaPitchedPtr((void*)img, extent.width*sizeof(float), extent.width, extent.height); copyParams.dstArray = d_imagedata; copyParams.extent = extent; copyParams.kind = cudaMemcpyHostToDevice; cudaMemcpy3D(&copyParams); cudaCheckErrors("cudaMemcpy3D fail"); // Configure texture options tex.normalized = false; tex.filterMode = cudaFilterModePoint; //we dotn want itnerpolation tex.addressMode[0] = cudaAddressModeBorder; tex.addressMode[1] = cudaAddressModeBorder; tex.addressMode[2] = cudaAddressModeBorder; cudaBindTextureToArray(tex, d_imagedata, channelDesc); cudaCheckErrors("3D texture memory bind fail"); //Done! Image put into texture memory. size_t num_bytes = geo.nDetecU*geo.nDetecV * sizeof(float); float* dProjection; cudaMalloc((void**)&dProjection, num_bytes); cudaCheckErrors("cudaMalloc fail"); bool timekernel=false; cudaEvent_t start, stop; float elapsedTime; if (timekernel){ cudaEventCreate(&start); cudaEventRecord(start,0); } Point3D source, deltaU, deltaV, uvOrigin; // 16x16 gave the best performance empirically // Funnily that makes it compatible with most GPUs..... int divU,divV; divU=16; divV=16; dim3 grid((geo.nDetecU+divU-1)/divU,(geo.nDetecV+divV-1)/divV,1); dim3 block(divU,divV,1); for (int i=0;i<nangles;i++){ geo.alpha=angles[i*3]; geo.theta=angles[i*3+1]; geo.psi =angles[i*3+2]; if(geo.alpha==0.0 || abs(geo.alpha-1.5707963267949)<0.0000001){ geo.alpha=geo.alpha+1.1920929e-07; } //precomute distances for faster execution //Precompute per angle constant stuff for speed computeDeltas_Siddon_parallel(geo,geo.alpha,i, &uvOrigin, &deltaU, &deltaV, &source); //Ray tracing! kernelPixelDetector_parallel<<<grid,block>>>(geo,dProjection, source, deltaU, deltaV, uvOrigin); cudaCheckErrors("Kernel fail"); // copy result to host cudaMemcpy(result[i], dProjection, num_bytes, cudaMemcpyDeviceToHost); cudaCheckErrors("cudaMemcpy fail"); } if (timekernel){ cudaEventCreate(&stop); cudaEventRecord(stop,0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsedTime, start,stop); mexPrintf("%f\n" ,elapsedTime); } cudaUnbindTexture(tex); cudaCheckErrors("Unbind fail"); cudaFree(dProjection); cudaFreeArray(d_imagedata); cudaCheckErrors("cudaFree d_imagedata fail"); cudaDeviceReset(); return 0; } /* This code precomputes The location of the source and the Delta U and delta V (in the warped space) * to compute the locations of the x-rays. While it seems verbose and overly-optimized, * it does saves about 30% of each of the kernel calls. Thats something! **/ void computeDeltas_Siddon_parallel(Geometry geo, float angles,int i, Point3D* uvorigin, Point3D* deltaU, Point3D* deltaV, Point3D* source){ Point3D S; S.x =geo.DSO[i]; S.y = geo.dDetecU*(0-((float)geo.nDetecU/2)+0.5); S.z = geo.dDetecV*(((float)geo.nDetecV/2)-0.5-0); //End point Point3D P,Pu0,Pv0; P.x =-(geo.DSD[i]-geo.DSO[i]); P.y = geo.dDetecU*(0-((float)geo.nDetecU/2)+0.5); P.z = geo.dDetecV*(((float)geo.nDetecV/2)-0.5-0); Pu0.x=-(geo.DSD[i]-geo.DSO[i]); Pu0.y= geo.dDetecU*(1-((float)geo.nDetecU/2)+0.5); Pu0.z= geo.dDetecV*(((float)geo.nDetecV/2)-0.5-0); Pv0.x=-(geo.DSD[i]-geo.DSO[i]); Pv0.y= geo.dDetecU*(0-((float)geo.nDetecU/2)+0.5); Pv0.z= geo.dDetecV*(((float)geo.nDetecV/2)-0.5-1); // Geomtric trasnformations: //1: Offset detector //P.x P.y =P.y +geo.offDetecU[i]; P.z =P.z +geo.offDetecV[i]; Pu0.y=Pu0.y+geo.offDetecU[i]; Pu0.z=Pu0.z+geo.offDetecV[i]; Pv0.y=Pv0.y+geo.offDetecU[i]; Pv0.z=Pv0.z+geo.offDetecV[i]; //S doesnt need to chagne //3: Rotate (around z)! Point3D Pfinal, Pfinalu0, Pfinalv0; Pfinal.x =P.x*cos(geo.alpha)-P.y*sin(geo.alpha); Pfinal.y =P.y*cos(geo.alpha)+P.x*sin(geo.alpha); Pfinal.z =P.z; Pfinalu0.x=Pu0.x*cos(geo.alpha)-Pu0.y*sin(geo.alpha); Pfinalu0.y=Pu0.y*cos(geo.alpha)+Pu0.x*sin(geo.alpha); Pfinalu0.z=Pu0.z; Pfinalv0.x=Pv0.x*cos(geo.alpha)-Pv0.y*sin(geo.alpha); Pfinalv0.y=Pv0.y*cos(geo.alpha)+Pv0.x*sin(geo.alpha); Pfinalv0.z=Pv0.z; Point3D S2; S2.x=S.x*cos(geo.alpha)-S.y*sin(geo.alpha); S2.y=S.y*cos(geo.alpha)+S.x*sin(geo.alpha); S2.z=S.z; //2: Offset image (instead of offseting image, -offset everything else) Pfinal.x =Pfinal.x-geo.offOrigX[i]; Pfinal.y =Pfinal.y-geo.offOrigY[i]; Pfinal.z =Pfinal.z-geo.offOrigZ[i]; Pfinalu0.x=Pfinalu0.x-geo.offOrigX[i]; Pfinalu0.y=Pfinalu0.y-geo.offOrigY[i]; Pfinalu0.z=Pfinalu0.z-geo.offOrigZ[i]; Pfinalv0.x=Pfinalv0.x-geo.offOrigX[i]; Pfinalv0.y=Pfinalv0.y-geo.offOrigY[i]; Pfinalv0.z=Pfinalv0.z-geo.offOrigZ[i]; S2.x=S2.x-geo.offOrigX[i]; S2.y=S2.y-geo.offOrigY[i]; S2.z=S2.z-geo.offOrigZ[i]; // As we want the (0,0,0) to be in a corner of the image, we need to translate everything (after rotation); Pfinal.x =Pfinal.x+geo.sVoxelX/2; Pfinal.y =Pfinal.y+geo.sVoxelY/2; Pfinal.z =Pfinal.z +geo.sVoxelZ/2; Pfinalu0.x=Pfinalu0.x+geo.sVoxelX/2; Pfinalu0.y=Pfinalu0.y+geo.sVoxelY/2; Pfinalu0.z=Pfinalu0.z+geo.sVoxelZ/2; Pfinalv0.x=Pfinalv0.x+geo.sVoxelX/2; Pfinalv0.y=Pfinalv0.y+geo.sVoxelY/2; Pfinalv0.z=Pfinalv0.z+geo.sVoxelZ/2; S2.x =S2.x+geo.sVoxelX/2; S2.y =S2.y+geo.sVoxelY/2; S2.z =S2.z +geo.sVoxelZ/2; //4. Scale everything so dVoxel==1 Pfinal.x =Pfinal.x/geo.dVoxelX; Pfinal.y =Pfinal.y/geo.dVoxelY; Pfinal.z =Pfinal.z/geo.dVoxelZ; Pfinalu0.x=Pfinalu0.x/geo.dVoxelX; Pfinalu0.y=Pfinalu0.y/geo.dVoxelY; Pfinalu0.z=Pfinalu0.z/geo.dVoxelZ; Pfinalv0.x=Pfinalv0.x/geo.dVoxelX; Pfinalv0.y=Pfinalv0.y/geo.dVoxelY; Pfinalv0.z=Pfinalv0.z/geo.dVoxelZ; S2.x =S2.x/geo.dVoxelX; S2.y =S2.y/geo.dVoxelY; S2.z =S2.z/geo.dVoxelZ; //5. apply COR. Wherever everything was, now its offesetd by a bit float CORx, CORy; CORx=-geo.COR[i]*sin(geo.alpha)/geo.dVoxelX; CORy= geo.COR[i]*cos(geo.alpha)/geo.dVoxelY; Pfinal.x+=CORx; Pfinal.y+=CORy; Pfinalu0.x+=CORx; Pfinalu0.y+=CORy; Pfinalv0.x+=CORx; Pfinalv0.y+=CORy; S2.x+=CORx; S2.y+=CORy; // return *uvorigin=Pfinal; deltaU->x=Pfinalu0.x-Pfinal.x; deltaU->y=Pfinalu0.y-Pfinal.y; deltaU->z=Pfinalu0.z-Pfinal.z; deltaV->x=Pfinalv0.x-Pfinal.x; deltaV->y=Pfinalv0.y-Pfinal.y; deltaV->z=Pfinalv0.z-Pfinal.z; *source=S2; } #ifndef PROJECTION_HPP float maxDistanceCubeXY(Geometry geo, float angles,int i){ /////////// // Compute initial "t" so we access safely as less as out of bounds as possible. ////////// float maxCubX,maxCubY; // Forgetting Z, compute max distance: diagonal+offset maxCubX=(geo.sVoxelX/2+ abs(geo.offOrigX[i]))/geo.dVoxelX; maxCubY=(geo.sVoxelY/2+ abs(geo.offOrigY[i]))/geo.dVoxelY; return geo.DSO[i]/geo.dVoxelX-sqrt(maxCubX*maxCubX+maxCubY*maxCubY); } #endif
1de5338f1201f3317d921f128f8387f115e55bfc.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #if !defined CUDA_DISABLER #include "opencv2/core/cuda/common.hpp" #include "opencv2/core/cuda/vec_traits.hpp" #include "opencv2/core/cuda/vec_math.hpp" #include "opencv2/core/cuda/functional.hpp" #include "opencv2/core/cuda/reduce.hpp" #include "opencv2/core/cuda/emulation.hpp" #include "opencv2/core/cuda/limits.hpp" #include "opencv2/core/cuda/utility.hpp" using namespace cv::cuda; using namespace cv::cuda::device; namespace minMaxLoc { // To avoid shared bank conflicts we convert each value into value of // appropriate type (32 bits minimum) template <typename T> struct MinMaxTypeTraits; template <> struct MinMaxTypeTraits<unsigned char> { typedef int best_type; }; template <> struct MinMaxTypeTraits<signed char> { typedef int best_type; }; template <> struct MinMaxTypeTraits<unsigned short> { typedef int best_type; }; template <> struct MinMaxTypeTraits<short> { typedef int best_type; }; template <> struct MinMaxTypeTraits<int> { typedef int best_type; }; template <> struct MinMaxTypeTraits<float> { typedef float best_type; }; template <> struct MinMaxTypeTraits<double> { typedef double best_type; }; template <int BLOCK_SIZE, typename T, class Mask> __global__ void kernel_pass_1(const PtrStepSz<T> src, const Mask mask, T* minval, T* maxval, unsigned int* minloc, unsigned int* maxloc, const int twidth, const int theight) { typedef typename MinMaxTypeTraits<T>::best_type work_type; __shared__ work_type sminval[BLOCK_SIZE]; __shared__ work_type smaxval[BLOCK_SIZE]; __shared__ unsigned int sminloc[BLOCK_SIZE]; __shared__ unsigned int smaxloc[BLOCK_SIZE]; const int x0 = blockIdx.x * blockDim.x * twidth + threadIdx.x; const int y0 = blockIdx.y * blockDim.y * theight + threadIdx.y; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int bid = blockIdx.y * gridDim.x + blockIdx.x; work_type mymin = numeric_limits<work_type>::max(); work_type mymax = -numeric_limits<work_type>::max(); unsigned int myminloc = 0; unsigned int mymaxloc = 0; for (int i = 0, y = y0; i < theight && y < src.rows; ++i, y += blockDim.y) { const T* ptr = src.ptr(y); for (int j = 0, x = x0; j < twidth && x < src.cols; ++j, x += blockDim.x) { if (mask(y, x)) { const work_type srcVal = ptr[x]; if (srcVal < mymin) { mymin = srcVal; myminloc = y * src.cols + x; } if (srcVal > mymax) { mymax = srcVal; mymaxloc = y * src.cols + x; } } } } reduceKeyVal<BLOCK_SIZE>(smem_tuple(sminval, smaxval), thrust::tie(mymin, mymax), smem_tuple(sminloc, smaxloc), thrust::tie(myminloc, mymaxloc), tid, thrust::make_tuple(less<work_type>(), greater<work_type>())); if (tid == 0) { minval[bid] = (T) mymin; maxval[bid] = (T) mymax; minloc[bid] = myminloc; maxloc[bid] = mymaxloc; } } template <int BLOCK_SIZE, typename T> __global__ void kernel_pass_2(T* minval, T* maxval, unsigned int* minloc, unsigned int* maxloc, int count) { typedef typename MinMaxTypeTraits<T>::best_type work_type; __shared__ work_type sminval[BLOCK_SIZE]; __shared__ work_type smaxval[BLOCK_SIZE]; __shared__ unsigned int sminloc[BLOCK_SIZE]; __shared__ unsigned int smaxloc[BLOCK_SIZE]; unsigned int idx = ::min(threadIdx.x, count - 1); work_type mymin = minval[idx]; work_type mymax = maxval[idx]; unsigned int myminloc = minloc[idx]; unsigned int mymaxloc = maxloc[idx]; reduceKeyVal<BLOCK_SIZE>(smem_tuple(sminval, smaxval), thrust::tie(mymin, mymax), smem_tuple(sminloc, smaxloc), thrust::tie(myminloc, mymaxloc), threadIdx.x, thrust::make_tuple(less<work_type>(), greater<work_type>())); if (threadIdx.x == 0) { minval[0] = (T) mymin; maxval[0] = (T) mymax; minloc[0] = myminloc; maxloc[0] = mymaxloc; } } const int threads_x = 32; const int threads_y = 8; void getLaunchCfg(int cols, int rows, dim3& block, dim3& grid) { block = dim3(threads_x, threads_y); grid = dim3(divUp(cols, block.x * block.y), divUp(rows, block.y * block.x)); grid.x = ::min(grid.x, block.x); grid.y = ::min(grid.y, block.y); } void getBufSize(int cols, int rows, size_t elem_size, int& b1cols, int& b1rows, int& b2cols, int& b2rows) { dim3 block, grid; getLaunchCfg(cols, rows, block, grid); // For values b1cols = (int)(grid.x * grid.y * elem_size); b1rows = 2; // For locations b2cols = grid.x * grid.y * sizeof(int); b2rows = 2; } template <typename T> void run(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf) { dim3 block, grid; getLaunchCfg(src.cols, src.rows, block, grid); const int twidth = divUp(divUp(src.cols, grid.x), block.x); const int theight = divUp(divUp(src.rows, grid.y), block.y); T* minval_buf = (T*) valbuf.ptr(0); T* maxval_buf = (T*) valbuf.ptr(1); unsigned int* minloc_buf = locbuf.ptr(0); unsigned int* maxloc_buf = locbuf.ptr(1); if (mask.data) hipLaunchKernelGGL(( kernel_pass_1<threads_x * threads_y>), dim3(grid), dim3(block), 0, 0, (PtrStepSz<T>) src, SingleMask(mask), minval_buf, maxval_buf, minloc_buf, maxloc_buf, twidth, theight); else hipLaunchKernelGGL(( kernel_pass_1<threads_x * threads_y>), dim3(grid), dim3(block), 0, 0, (PtrStepSz<T>) src, WithOutMask(), minval_buf, maxval_buf, minloc_buf, maxloc_buf, twidth, theight); cudaSafeCall( hipGetLastError() ); hipLaunchKernelGGL(( kernel_pass_2<threads_x * threads_y>), dim3(1), dim3(threads_x * threads_y), 0, 0, minval_buf, maxval_buf, minloc_buf, maxloc_buf, grid.x * grid.y); cudaSafeCall( hipGetLastError() ); cudaSafeCall( hipDeviceSynchronize() ); T minval_, maxval_; cudaSafeCall( hipMemcpy(&minval_, minval_buf, sizeof(T), hipMemcpyDeviceToHost) ); cudaSafeCall( hipMemcpy(&maxval_, maxval_buf, sizeof(T), hipMemcpyDeviceToHost) ); *minval = minval_; *maxval = maxval_; unsigned int minloc_, maxloc_; cudaSafeCall( hipMemcpy(&minloc_, minloc_buf, sizeof(unsigned int), hipMemcpyDeviceToHost) ); cudaSafeCall( hipMemcpy(&maxloc_, maxloc_buf, sizeof(unsigned int), hipMemcpyDeviceToHost) ); minloc[1] = minloc_ / src.cols; minloc[0] = minloc_ - minloc[1] * src.cols; maxloc[1] = maxloc_ / src.cols; maxloc[0] = maxloc_ - maxloc[1] * src.cols; } template void run<unsigned char >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<signed char >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<unsigned short>(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<short >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<int >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<float >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<double>(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); } #endif // CUDA_DISABLER
1de5338f1201f3317d921f128f8387f115e55bfc.cu
/*M/////////////////////////////////////////////////////////////////////////////////////// // // IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING. // // By downloading, copying, installing or using the software you agree to this license. // If you do not agree to this license, do not download, install, // copy or use the software. // // // License Agreement // For Open Source Computer Vision Library // // Copyright (C) 2000-2008, Intel Corporation, all rights reserved. // Copyright (C) 2009, Willow Garage Inc., all rights reserved. // Third party copyrights are property of their respective owners. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistribution's of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistribution's 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. // // * The name of the copyright holders may not 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 Intel Corporation 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. // //M*/ #if !defined CUDA_DISABLER #include "opencv2/core/cuda/common.hpp" #include "opencv2/core/cuda/vec_traits.hpp" #include "opencv2/core/cuda/vec_math.hpp" #include "opencv2/core/cuda/functional.hpp" #include "opencv2/core/cuda/reduce.hpp" #include "opencv2/core/cuda/emulation.hpp" #include "opencv2/core/cuda/limits.hpp" #include "opencv2/core/cuda/utility.hpp" using namespace cv::cuda; using namespace cv::cuda::device; namespace minMaxLoc { // To avoid shared bank conflicts we convert each value into value of // appropriate type (32 bits minimum) template <typename T> struct MinMaxTypeTraits; template <> struct MinMaxTypeTraits<unsigned char> { typedef int best_type; }; template <> struct MinMaxTypeTraits<signed char> { typedef int best_type; }; template <> struct MinMaxTypeTraits<unsigned short> { typedef int best_type; }; template <> struct MinMaxTypeTraits<short> { typedef int best_type; }; template <> struct MinMaxTypeTraits<int> { typedef int best_type; }; template <> struct MinMaxTypeTraits<float> { typedef float best_type; }; template <> struct MinMaxTypeTraits<double> { typedef double best_type; }; template <int BLOCK_SIZE, typename T, class Mask> __global__ void kernel_pass_1(const PtrStepSz<T> src, const Mask mask, T* minval, T* maxval, unsigned int* minloc, unsigned int* maxloc, const int twidth, const int theight) { typedef typename MinMaxTypeTraits<T>::best_type work_type; __shared__ work_type sminval[BLOCK_SIZE]; __shared__ work_type smaxval[BLOCK_SIZE]; __shared__ unsigned int sminloc[BLOCK_SIZE]; __shared__ unsigned int smaxloc[BLOCK_SIZE]; const int x0 = blockIdx.x * blockDim.x * twidth + threadIdx.x; const int y0 = blockIdx.y * blockDim.y * theight + threadIdx.y; const int tid = threadIdx.y * blockDim.x + threadIdx.x; const int bid = blockIdx.y * gridDim.x + blockIdx.x; work_type mymin = numeric_limits<work_type>::max(); work_type mymax = -numeric_limits<work_type>::max(); unsigned int myminloc = 0; unsigned int mymaxloc = 0; for (int i = 0, y = y0; i < theight && y < src.rows; ++i, y += blockDim.y) { const T* ptr = src.ptr(y); for (int j = 0, x = x0; j < twidth && x < src.cols; ++j, x += blockDim.x) { if (mask(y, x)) { const work_type srcVal = ptr[x]; if (srcVal < mymin) { mymin = srcVal; myminloc = y * src.cols + x; } if (srcVal > mymax) { mymax = srcVal; mymaxloc = y * src.cols + x; } } } } reduceKeyVal<BLOCK_SIZE>(smem_tuple(sminval, smaxval), thrust::tie(mymin, mymax), smem_tuple(sminloc, smaxloc), thrust::tie(myminloc, mymaxloc), tid, thrust::make_tuple(less<work_type>(), greater<work_type>())); if (tid == 0) { minval[bid] = (T) mymin; maxval[bid] = (T) mymax; minloc[bid] = myminloc; maxloc[bid] = mymaxloc; } } template <int BLOCK_SIZE, typename T> __global__ void kernel_pass_2(T* minval, T* maxval, unsigned int* minloc, unsigned int* maxloc, int count) { typedef typename MinMaxTypeTraits<T>::best_type work_type; __shared__ work_type sminval[BLOCK_SIZE]; __shared__ work_type smaxval[BLOCK_SIZE]; __shared__ unsigned int sminloc[BLOCK_SIZE]; __shared__ unsigned int smaxloc[BLOCK_SIZE]; unsigned int idx = ::min(threadIdx.x, count - 1); work_type mymin = minval[idx]; work_type mymax = maxval[idx]; unsigned int myminloc = minloc[idx]; unsigned int mymaxloc = maxloc[idx]; reduceKeyVal<BLOCK_SIZE>(smem_tuple(sminval, smaxval), thrust::tie(mymin, mymax), smem_tuple(sminloc, smaxloc), thrust::tie(myminloc, mymaxloc), threadIdx.x, thrust::make_tuple(less<work_type>(), greater<work_type>())); if (threadIdx.x == 0) { minval[0] = (T) mymin; maxval[0] = (T) mymax; minloc[0] = myminloc; maxloc[0] = mymaxloc; } } const int threads_x = 32; const int threads_y = 8; void getLaunchCfg(int cols, int rows, dim3& block, dim3& grid) { block = dim3(threads_x, threads_y); grid = dim3(divUp(cols, block.x * block.y), divUp(rows, block.y * block.x)); grid.x = ::min(grid.x, block.x); grid.y = ::min(grid.y, block.y); } void getBufSize(int cols, int rows, size_t elem_size, int& b1cols, int& b1rows, int& b2cols, int& b2rows) { dim3 block, grid; getLaunchCfg(cols, rows, block, grid); // For values b1cols = (int)(grid.x * grid.y * elem_size); b1rows = 2; // For locations b2cols = grid.x * grid.y * sizeof(int); b2rows = 2; } template <typename T> void run(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf) { dim3 block, grid; getLaunchCfg(src.cols, src.rows, block, grid); const int twidth = divUp(divUp(src.cols, grid.x), block.x); const int theight = divUp(divUp(src.rows, grid.y), block.y); T* minval_buf = (T*) valbuf.ptr(0); T* maxval_buf = (T*) valbuf.ptr(1); unsigned int* minloc_buf = locbuf.ptr(0); unsigned int* maxloc_buf = locbuf.ptr(1); if (mask.data) kernel_pass_1<threads_x * threads_y><<<grid, block>>>((PtrStepSz<T>) src, SingleMask(mask), minval_buf, maxval_buf, minloc_buf, maxloc_buf, twidth, theight); else kernel_pass_1<threads_x * threads_y><<<grid, block>>>((PtrStepSz<T>) src, WithOutMask(), minval_buf, maxval_buf, minloc_buf, maxloc_buf, twidth, theight); cudaSafeCall( cudaGetLastError() ); kernel_pass_2<threads_x * threads_y><<<1, threads_x * threads_y>>>(minval_buf, maxval_buf, minloc_buf, maxloc_buf, grid.x * grid.y); cudaSafeCall( cudaGetLastError() ); cudaSafeCall( cudaDeviceSynchronize() ); T minval_, maxval_; cudaSafeCall( cudaMemcpy(&minval_, minval_buf, sizeof(T), cudaMemcpyDeviceToHost) ); cudaSafeCall( cudaMemcpy(&maxval_, maxval_buf, sizeof(T), cudaMemcpyDeviceToHost) ); *minval = minval_; *maxval = maxval_; unsigned int minloc_, maxloc_; cudaSafeCall( cudaMemcpy(&minloc_, minloc_buf, sizeof(unsigned int), cudaMemcpyDeviceToHost) ); cudaSafeCall( cudaMemcpy(&maxloc_, maxloc_buf, sizeof(unsigned int), cudaMemcpyDeviceToHost) ); minloc[1] = minloc_ / src.cols; minloc[0] = minloc_ - minloc[1] * src.cols; maxloc[1] = maxloc_ / src.cols; maxloc[0] = maxloc_ - maxloc[1] * src.cols; } template void run<unsigned char >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<signed char >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<unsigned short>(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<short >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<int >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<float >(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); template void run<double>(const PtrStepSzb src, const PtrStepb mask, double* minval, double* maxval, int* minloc, int* maxloc, PtrStepb valbuf, PtrStep<unsigned int> locbuf); } #endif // CUDA_DISABLER
2562bd490e1a39ef7b86f5c51fd8108a14b12c7e.hip
// !!! This is a file automatically generated by hipify!!! /** * Octree Partitioning * Benchmark for dynamic load balancing using * work-stealing on graphics processors. * -------------------------------------------------------- * Copyright 2011 Daniel Cederman and Philippas Tsigas * * This work is licensed under the Creative Commons * Attribution 3.0 Unported (CC BY 3.0) License. * To view a copy of this license, visit * http://creativecommons.org/licenses/by/3.0 . * **/ #include "lbabp.h" #include "helper.h" LBABP::~LBABP() { if(init) { hipFree(dwq); hipFree(wq->deq); hipFree(wq->dh); } } bool LBABP::setQueueSize(unsigned int dequelength, unsigned int blocks) { init = true; wq = (DLBABP*)malloc(sizeof(DLBABP)); CUDA_SAFE_CALL(hipMalloc((void**)&dwq,sizeof(DLBABP))); CUDA_SAFE_CALL(hipMalloc((void**)&(wq->deq),sizeof(Task)*dequelength*blocks)); CUDA_SAFE_CALL(hipMalloc((void**)&(wq->dh),sizeof(DequeHeader)*blocks)); CUDA_SAFE_CALL(hipMemset(wq->deq,0,sizeof(Task)*dequelength*blocks)); CUDA_SAFE_CALL(hipMemset(wq->dh,0,sizeof(DequeHeader)*blocks)); wq->maxlength = dequelength; CUDA_SAFE_CALL(hipMemcpy(dwq,wq,sizeof(DLBABP),hipMemcpyHostToDevice)); return true; } int LBABP::getMaxMem() { int maxle; CUDA_SAFE_CALL(hipMemcpyFromSymbol(&maxle,maxl,sizeof(int),0,hipMemcpyDeviceToHost)); return maxle; }
2562bd490e1a39ef7b86f5c51fd8108a14b12c7e.cu
/** * Octree Partitioning * Benchmark for dynamic load balancing using * work-stealing on graphics processors. * -------------------------------------------------------- * Copyright 2011 Daniel Cederman and Philippas Tsigas * * This work is licensed under the Creative Commons * Attribution 3.0 Unported (CC BY 3.0) License. * To view a copy of this license, visit * http://creativecommons.org/licenses/by/3.0 . * **/ #include "lbabp.h" #include "helper.h" LBABP::~LBABP() { if(init) { cudaFree(dwq); cudaFree(wq->deq); cudaFree(wq->dh); } } bool LBABP::setQueueSize(unsigned int dequelength, unsigned int blocks) { init = true; wq = (DLBABP*)malloc(sizeof(DLBABP)); CUDA_SAFE_CALL(cudaMalloc((void**)&dwq,sizeof(DLBABP))); CUDA_SAFE_CALL(cudaMalloc((void**)&(wq->deq),sizeof(Task)*dequelength*blocks)); CUDA_SAFE_CALL(cudaMalloc((void**)&(wq->dh),sizeof(DequeHeader)*blocks)); CUDA_SAFE_CALL(cudaMemset(wq->deq,0,sizeof(Task)*dequelength*blocks)); CUDA_SAFE_CALL(cudaMemset(wq->dh,0,sizeof(DequeHeader)*blocks)); wq->maxlength = dequelength; CUDA_SAFE_CALL(cudaMemcpy(dwq,wq,sizeof(DLBABP),cudaMemcpyHostToDevice)); return true; } int LBABP::getMaxMem() { int maxle; CUDA_SAFE_CALL(cudaMemcpyFromSymbol(&maxle,maxl,sizeof(int),0,cudaMemcpyDeviceToHost)); return maxle; }
addMatrix.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void addMatrix(int *a, int *b, int *res, int n) { int tidx = blockDim.x * blockIdx.x + threadIdx.x; int tidy = blockDim.y * blockIdx.y + threadIdx.y; if (tidx >= n || tidy >= n) { return; } int tid = tidx * n + tidy; res[tid] = a[tid] + b[tid]; }
addMatrix.cu
#include "includes.h" __global__ void addMatrix(int *a, int *b, int *res, int n) { int tidx = blockDim.x * blockIdx.x + threadIdx.x; int tidy = blockDim.y * blockIdx.y + threadIdx.y; if (tidx >= n || tidy >= n) { return; } int tid = tidx * n + tidy; res[tid] = a[tid] + b[tid]; }
65d3b2b150d2d2b1546d0d73460116a2c71e59bc.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // Copyright 2014 George Papandreou #include "caffe/common.hpp" #include "caffe/common.cuh" #include "caffe/util/interp.hpp" namespace caffe { // Bi-linear interpolation // IN : [channels height1 width1] cropped from a bigger [Height1 Width1] image // OUT: [channels height2 width2] cropped from a bigger [Height2 Width2] image template <typename Dtype, bool packed> __global__ void caffe_gpu_interp2_kernel(const int n, const float rheight, const float rwidth, const int channels, const Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < n) { const int w2 = index % width2; // 0:width2-1 const int h2 = index / width2; // 0:height2-1 // special case: just copy if (height1 == height2 && width1 == width2) { const int h1 = h2; const int w1 = w2; if (packed) { const Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { pos2[0] = pos1[0]; pos1++; pos2++; } } else { const Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { pos2[0] = pos1[0]; pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } return; } // const float h1r = rheight * h2; const int h1 = h1r; const int h1p = (h1 < height1 - 1) ? 1 : 0; const Dtype h1lambda = h1r - h1; const Dtype h0lambda = Dtype(1.) - h1lambda; // const float w1r = rwidth * w2; const int w1 = w1r; const int w1p = (w1 < width1 - 1) ? 1 : 0; const Dtype w1lambda = w1r - w1; const Dtype w0lambda = Dtype(1.) - w1lambda; // if (packed) { const Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { pos2[0] = h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[channels * w1p]) + h1lambda * (w0lambda * pos1[channels * h1p * Width1] + w1lambda * pos1[channels * (h1p * Width1 + w1p)]); pos1++; pos2++; } } else { const Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { pos2[0] = h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[w1p]) + h1lambda * (w0lambda * pos1[h1p * Width1] + w1lambda * pos1[h1p * Width1 + w1p]); pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } } } template <typename Dtype, bool packed> void caffe_gpu_interp2(const int channels, const Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { CHECK(x1 >= 0 && y1 >= 0 && height1 > 0 && width1 > 0 && x2 >= 0 && y2 >= 0 && height2 > 0 && width2 > 0); CHECK(Width1 >= width1 + x1 && Height1 >= height1 + y1 && Width2 >= width2 + x2 && Height2 >= height2 + y2); const float rheight = (height2 > 1) ? static_cast<float>(height1 - 1) / (height2 - 1) : 0.f; const float rwidth = (width2 > 1) ? static_cast<float>(width1 - 1) / (width2 - 1) : 0.f; const int num_kernels = height2 * width2; hipLaunchKernelGGL(( caffe_gpu_interp2_kernel<Dtype,packed>), dim3(CAFFE_GET_BLOCKS(num_kernels)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, num_kernels, rheight, rwidth, channels, data1, x1, y1, height1, width1, Height1, Width1, data2, x2, y2, height2, width2, Height2, Width2); CUDA_POST_KERNEL_CHECK; } // Backward (adjoint) operation 1 <- 2 (accumulates) template <typename Dtype, bool packed> __global__ void caffe_gpu_interp2_kernel_backward(const int n, const float rheight, const float rwidth, const int channels, Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, const Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < n) { const int w2 = index % width2; // 0:width2-1 const int h2 = index / width2; // 0:height2-1 // special case: just copy if (height1 == height2 && width1 == width2) { const int h1 = h2; const int w1 = w2; if (packed) { Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; const Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { pos1[0] += pos2[0]; pos1++; pos2++; } } else { Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; const Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { pos1[0] += pos2[0]; pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } return; } // const float h1r = rheight * h2; const int h1 = h1r; const int h1p = (h1 < height1 - 1) ? 1 : 0; const Dtype h1lambda = h1r - h1; const Dtype h0lambda = Dtype(1.) - h1lambda; // const float w1r = rwidth * w2; const int w1 = w1r; const int w1p = (w1 < width1 - 1) ? 1 : 0; const Dtype w1lambda = w1r - w1; const Dtype w0lambda = Dtype(1.) - w1lambda; // if (packed) { Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; const Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { atomicAdd(&pos1[0], h0lambda * w0lambda * pos2[0]); atomicAdd(&pos1[channels * w1p], h0lambda * w1lambda * pos2[0]); atomicAdd(&pos1[channels * h1p * Width1], h1lambda * w0lambda * pos2[0]); atomicAdd(&pos1[channels * (h1p * Width1 + w1p)], h1lambda * w1lambda * pos2[0]); pos1++; pos2++; } } else { Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; const Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { atomicAdd(&pos1[0], h0lambda * w0lambda * pos2[0]); atomicAdd(&pos1[w1p], h0lambda * w1lambda * pos2[0]); atomicAdd(&pos1[h1p * Width1], h1lambda * w0lambda * pos2[0]); atomicAdd(&pos1[h1p * Width1 + w1p], h1lambda * w1lambda * pos2[0]); pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } } } template <typename Dtype, bool packed> void caffe_gpu_interp2_backward(const int channels, Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, const Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { CHECK(x1 >= 0 && y1 >= 0 && height1 > 0 && width1 > 0 && x2 >= 0 && y2 >= 0 && height2 > 0 && width2 > 0); CHECK(Width1 >= width1 + x1 && Height1 >= height1 + y1 && Width2 >= width2 + x2 && Height2 >= height2 + y2); const float rheight = (height2 > 1) ? static_cast<float>(height1 - 1) / (height2 - 1) : 0.f; const float rwidth = (width2 > 1) ? static_cast<float>(width1 - 1) / (width2 - 1) : 0.f; const int num_kernels = height2 * width2; hipLaunchKernelGGL(( caffe_gpu_interp2_kernel_backward<Dtype,packed>), dim3(CAFFE_GET_BLOCKS(num_kernels)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, num_kernels, rheight, rwidth, channels, data1, x1, y1, height1, width1, Height1, Width1, data2, x2, y2, height2, width2, Height2, Width2); CUDA_POST_KERNEL_CHECK; } // Create Gaussian pyramid of an image. Assume output space is pre-allocated. // IN : [channels height width] template <typename Dtype, bool packed> __global__ void caffe_gpu_pyramid2_kernel(const int n, const int channels, const Dtype *data1, const int height1, const int width1, Dtype *data2, const int height2, const int width2) { int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < n) { const int w2 = index % width2; // 0:width2-1 const int h2 = index / width2; // 0:height2-1 const int w1 = 2 * w2; const int h1 = 2 * h2; if (packed) { const Dtype* pos1 = &data1[channels * (h1 * width1 + w1)]; Dtype* pos2 = &data2[channels * (h2 * width2 + w2)]; for (int c = 0; c < channels; ++c) { pos2[0] = static_cast<Dtype>(.25) * (pos1[0] + pos1[channels] + pos1[channels * width1] + pos1[channels * (width1 + 1)]); pos1++; pos2++; } } else { const Dtype* pos1 = &data1[h1 * width1 + w1]; Dtype* pos2 = &data2[h2 * width2 + w2]; for (int c = 0; c < channels; ++c) { pos2[0] = static_cast<Dtype>(.25) * (pos1[0] + pos1[1] + pos1[width1] + pos1[width1 + 1]); pos1 += width1 * height1; pos2 += width2 * height2; } } } } template <typename Dtype, bool packed> void caffe_gpu_pyramid2(const int channels, const Dtype *data, const int height, const int width, Dtype *data_pyr, const int levels) { CHECK(height > 0 && width > 0 && levels >= 0); int height1 = height, width1 = width; int height2 = height, width2 = width; const Dtype *data1 = data; Dtype *data2 = data_pyr; for (int l = 0; l < levels; ++l) { height2 /= 2; width2 /= 2; if (height2 == 0 || width2 == 0) { break; } const int num_kernels = height2 * width2; hipLaunchKernelGGL(( caffe_gpu_pyramid2_kernel<Dtype,packed>), dim3(CAFFE_GET_BLOCKS(num_kernels)), dim3(CAFFE_CUDA_NUM_THREADS), 0, 0, num_kernels, channels, data1, height1, width1, data2, height2, width2); CUDA_POST_KERNEL_CHECK; data1 = data2; height1 = height2; width1 = width2; data2 += channels * height2 * width2; } } // Explicit instances template void caffe_gpu_interp2<float,false>(const int, const float *, const int, const int, const int, const int, const int, const int, float *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2<float,true>(const int, const float *, const int, const int, const int, const int, const int, const int, float *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2<double,false>(const int, const double *, const int, const int, const int, const int, const int, const int, double *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2<double,true>(const int, const double *, const int, const int, const int, const int, const int, const int, double *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2_backward<float,false>(const int, float *, const int, const int, const int, const int, const int, const int, const float *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2_backward<double,false>(const int, double *, const int, const int, const int, const int, const int, const int, const double *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_pyramid2<float,false>(const int, const float *, const int, const int, float *, const int); template void caffe_gpu_pyramid2<float,true>(const int, const float *, const int, const int, float *, const int); template void caffe_gpu_pyramid2<double,false>(const int, const double *, const int, const int, double *, const int); template void caffe_gpu_pyramid2<double,true>(const int, const double *, const int, const int, double *, const int); } // namespace caffe
65d3b2b150d2d2b1546d0d73460116a2c71e59bc.cu
// Copyright 2014 George Papandreou #include "caffe/common.hpp" #include "caffe/common.cuh" #include "caffe/util/interp.hpp" namespace caffe { // Bi-linear interpolation // IN : [channels height1 width1] cropped from a bigger [Height1 Width1] image // OUT: [channels height2 width2] cropped from a bigger [Height2 Width2] image template <typename Dtype, bool packed> __global__ void caffe_gpu_interp2_kernel(const int n, const float rheight, const float rwidth, const int channels, const Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < n) { const int w2 = index % width2; // 0:width2-1 const int h2 = index / width2; // 0:height2-1 // special case: just copy if (height1 == height2 && width1 == width2) { const int h1 = h2; const int w1 = w2; if (packed) { const Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { pos2[0] = pos1[0]; pos1++; pos2++; } } else { const Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { pos2[0] = pos1[0]; pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } return; } // const float h1r = rheight * h2; const int h1 = h1r; const int h1p = (h1 < height1 - 1) ? 1 : 0; const Dtype h1lambda = h1r - h1; const Dtype h0lambda = Dtype(1.) - h1lambda; // const float w1r = rwidth * w2; const int w1 = w1r; const int w1p = (w1 < width1 - 1) ? 1 : 0; const Dtype w1lambda = w1r - w1; const Dtype w0lambda = Dtype(1.) - w1lambda; // if (packed) { const Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { pos2[0] = h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[channels * w1p]) + h1lambda * (w0lambda * pos1[channels * h1p * Width1] + w1lambda * pos1[channels * (h1p * Width1 + w1p)]); pos1++; pos2++; } } else { const Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { pos2[0] = h0lambda * (w0lambda * pos1[0] + w1lambda * pos1[w1p]) + h1lambda * (w0lambda * pos1[h1p * Width1] + w1lambda * pos1[h1p * Width1 + w1p]); pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } } } template <typename Dtype, bool packed> void caffe_gpu_interp2(const int channels, const Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { CHECK(x1 >= 0 && y1 >= 0 && height1 > 0 && width1 > 0 && x2 >= 0 && y2 >= 0 && height2 > 0 && width2 > 0); CHECK(Width1 >= width1 + x1 && Height1 >= height1 + y1 && Width2 >= width2 + x2 && Height2 >= height2 + y2); const float rheight = (height2 > 1) ? static_cast<float>(height1 - 1) / (height2 - 1) : 0.f; const float rwidth = (width2 > 1) ? static_cast<float>(width1 - 1) / (width2 - 1) : 0.f; const int num_kernels = height2 * width2; caffe_gpu_interp2_kernel<Dtype,packed><<<CAFFE_GET_BLOCKS(num_kernels), CAFFE_CUDA_NUM_THREADS>>> (num_kernels, rheight, rwidth, channels, data1, x1, y1, height1, width1, Height1, Width1, data2, x2, y2, height2, width2, Height2, Width2); CUDA_POST_KERNEL_CHECK; } // Backward (adjoint) operation 1 <- 2 (accumulates) template <typename Dtype, bool packed> __global__ void caffe_gpu_interp2_kernel_backward(const int n, const float rheight, const float rwidth, const int channels, Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, const Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < n) { const int w2 = index % width2; // 0:width2-1 const int h2 = index / width2; // 0:height2-1 // special case: just copy if (height1 == height2 && width1 == width2) { const int h1 = h2; const int w1 = w2; if (packed) { Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; const Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { pos1[0] += pos2[0]; pos1++; pos2++; } } else { Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; const Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { pos1[0] += pos2[0]; pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } return; } // const float h1r = rheight * h2; const int h1 = h1r; const int h1p = (h1 < height1 - 1) ? 1 : 0; const Dtype h1lambda = h1r - h1; const Dtype h0lambda = Dtype(1.) - h1lambda; // const float w1r = rwidth * w2; const int w1 = w1r; const int w1p = (w1 < width1 - 1) ? 1 : 0; const Dtype w1lambda = w1r - w1; const Dtype w0lambda = Dtype(1.) - w1lambda; // if (packed) { Dtype* pos1 = &data1[channels * ((y1 + h1) * Width1 + (x1 + w1))]; const Dtype* pos2 = &data2[channels * ((y2 + h2) * Width2 + (x2 + w2))]; for (int c = 0; c < channels; ++c) { atomicAdd(&pos1[0], h0lambda * w0lambda * pos2[0]); atomicAdd(&pos1[channels * w1p], h0lambda * w1lambda * pos2[0]); atomicAdd(&pos1[channels * h1p * Width1], h1lambda * w0lambda * pos2[0]); atomicAdd(&pos1[channels * (h1p * Width1 + w1p)], h1lambda * w1lambda * pos2[0]); pos1++; pos2++; } } else { Dtype* pos1 = &data1[(y1 + h1) * Width1 + (x1 + w1)]; const Dtype* pos2 = &data2[(y2 + h2) * Width2 + (x2 + w2)]; for (int c = 0; c < channels; ++c) { atomicAdd(&pos1[0], h0lambda * w0lambda * pos2[0]); atomicAdd(&pos1[w1p], h0lambda * w1lambda * pos2[0]); atomicAdd(&pos1[h1p * Width1], h1lambda * w0lambda * pos2[0]); atomicAdd(&pos1[h1p * Width1 + w1p], h1lambda * w1lambda * pos2[0]); pos1 += Width1 * Height1; pos2 += Width2 * Height2; } } } } template <typename Dtype, bool packed> void caffe_gpu_interp2_backward(const int channels, Dtype *data1, const int x1, const int y1, const int height1, const int width1, const int Height1, const int Width1, const Dtype *data2, const int x2, const int y2, const int height2, const int width2, const int Height2, const int Width2) { CHECK(x1 >= 0 && y1 >= 0 && height1 > 0 && width1 > 0 && x2 >= 0 && y2 >= 0 && height2 > 0 && width2 > 0); CHECK(Width1 >= width1 + x1 && Height1 >= height1 + y1 && Width2 >= width2 + x2 && Height2 >= height2 + y2); const float rheight = (height2 > 1) ? static_cast<float>(height1 - 1) / (height2 - 1) : 0.f; const float rwidth = (width2 > 1) ? static_cast<float>(width1 - 1) / (width2 - 1) : 0.f; const int num_kernels = height2 * width2; caffe_gpu_interp2_kernel_backward<Dtype,packed><<<CAFFE_GET_BLOCKS(num_kernels), CAFFE_CUDA_NUM_THREADS>>> (num_kernels, rheight, rwidth, channels, data1, x1, y1, height1, width1, Height1, Width1, data2, x2, y2, height2, width2, Height2, Width2); CUDA_POST_KERNEL_CHECK; } // Create Gaussian pyramid of an image. Assume output space is pre-allocated. // IN : [channels height width] template <typename Dtype, bool packed> __global__ void caffe_gpu_pyramid2_kernel(const int n, const int channels, const Dtype *data1, const int height1, const int width1, Dtype *data2, const int height2, const int width2) { int index = threadIdx.x + blockIdx.x * blockDim.x; if (index < n) { const int w2 = index % width2; // 0:width2-1 const int h2 = index / width2; // 0:height2-1 const int w1 = 2 * w2; const int h1 = 2 * h2; if (packed) { const Dtype* pos1 = &data1[channels * (h1 * width1 + w1)]; Dtype* pos2 = &data2[channels * (h2 * width2 + w2)]; for (int c = 0; c < channels; ++c) { pos2[0] = static_cast<Dtype>(.25) * (pos1[0] + pos1[channels] + pos1[channels * width1] + pos1[channels * (width1 + 1)]); pos1++; pos2++; } } else { const Dtype* pos1 = &data1[h1 * width1 + w1]; Dtype* pos2 = &data2[h2 * width2 + w2]; for (int c = 0; c < channels; ++c) { pos2[0] = static_cast<Dtype>(.25) * (pos1[0] + pos1[1] + pos1[width1] + pos1[width1 + 1]); pos1 += width1 * height1; pos2 += width2 * height2; } } } } template <typename Dtype, bool packed> void caffe_gpu_pyramid2(const int channels, const Dtype *data, const int height, const int width, Dtype *data_pyr, const int levels) { CHECK(height > 0 && width > 0 && levels >= 0); int height1 = height, width1 = width; int height2 = height, width2 = width; const Dtype *data1 = data; Dtype *data2 = data_pyr; for (int l = 0; l < levels; ++l) { height2 /= 2; width2 /= 2; if (height2 == 0 || width2 == 0) { break; } const int num_kernels = height2 * width2; caffe_gpu_pyramid2_kernel<Dtype,packed><<<CAFFE_GET_BLOCKS(num_kernels), CAFFE_CUDA_NUM_THREADS>>> (num_kernels, channels, data1, height1, width1, data2, height2, width2); CUDA_POST_KERNEL_CHECK; data1 = data2; height1 = height2; width1 = width2; data2 += channels * height2 * width2; } } // Explicit instances template void caffe_gpu_interp2<float,false>(const int, const float *, const int, const int, const int, const int, const int, const int, float *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2<float,true>(const int, const float *, const int, const int, const int, const int, const int, const int, float *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2<double,false>(const int, const double *, const int, const int, const int, const int, const int, const int, double *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2<double,true>(const int, const double *, const int, const int, const int, const int, const int, const int, double *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2_backward<float,false>(const int, float *, const int, const int, const int, const int, const int, const int, const float *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_interp2_backward<double,false>(const int, double *, const int, const int, const int, const int, const int, const int, const double *, const int, const int, const int, const int, const int, const int); template void caffe_gpu_pyramid2<float,false>(const int, const float *, const int, const int, float *, const int); template void caffe_gpu_pyramid2<float,true>(const int, const float *, const int, const int, float *, const int); template void caffe_gpu_pyramid2<double,false>(const int, const double *, const int, const int, double *, const int); template void caffe_gpu_pyramid2<double,true>(const int, const double *, const int, const int, double *, const int); } // namespace caffe
7d5c52e6704f66e219e97c2a2cdbca80fafbf9db.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /** * Copyright 2019 Arne Petersen, Kiel University * * 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 "DisparityRefinement_Crosscheck.hh" #include "PIPInterOpCUDA/CUDAImageArray.hh" #include "PIPInterOpCUDA/CUDAImageTexture.hh" #if !defined(WIN32) && !defined(_WIN32) && !defined(__WIN32) #include <unistd.h> #endif // not WIN32 using namespace PIP; __device__ __constant__ SPlenCamDescription globalMlaDescr; //#define SECONDLENSLEVEL //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template<const EGridType t_eGridType> __global__ void computeCrosscheck(float* outputDisparities, hipTextureObject_t texInputDisparities, const unsigned nWidth, const unsigned nHeight, const float fMaxDispDiff) { // Get pixel position and test 'in image' vec2<float> vPixelPos_px; vPixelPos_px.Set(blockIdx.x*blockDim.x + threadIdx.x, blockIdx.y*blockDim.y + threadIdx.y); // reject out of bounds pixels if (((vPixelPos_px.x < float(nWidth)-1) && (vPixelPos_px.y < float(nHeight)-1)) == false) { return; } // Initial disparity normalized with lens diameter (inter-lens distance) float fInitialDisparity_px = tex2D<float>(texInputDisparities, vPixelPos_px.x + 0.5f, vPixelPos_px.y + 0.5f); // Zero-disparity is invalid estimation if (fInitialDisparity_px == 0.0f) return; // Disparity in pixel relative to target lenses (2. level distance = 1.73205... micro lens distances) #ifdef SECONDLENSLEVEL if (t_eGridType == EGridType::HEXAGONAL) { fInitialDisparity_px = fInitialDisparity_px*(1.73205f * globalMlaDescr.fMicroLensDistance_px); } else { fInitialDisparity_px = fInitialDisparity_px*(2.0f * globalMlaDescr.fMicroLensDistance_px); } #else // SECONDLENSLEVEL fInitialDisparity_px = fInitialDisparity_px*(globalMlaDescr.fMicroLensDistance_px); #endif // SECONDLENSLEVEL // Get index of source lens in grid vec2<float> vReferenceGridIndex; // comming from plenoptic image implies using mirco-image grid vReferenceGridIndex = globalMlaDescr.PixelToLensImageGrid<t_eGridType>(vPixelPos_px); // round to integral lens index vReferenceGridIndex = globalMlaDescr.GridRound<t_eGridType>(vReferenceGridIndex); // Get baselines from target lens 'ring' vec2<float> vs[6]; vec2<float> vTargetLensIdcs[6]; vec2<float> vMicroLensCenter_px = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vReferenceGridIndex); { #ifdef SECONDLENSLEVEL vTargetLensIdcs[0].Set(vReferenceGridIndex.x - 1.0f, vReferenceGridIndex.y + 2.0f); vs[0] = globalMlaDescr.GetMicroLensCenter_px(vTargetLensIdcs[0]) - vMicroLensCenter_px; vs[0].normalize(); vTargetLensIdcs[1].Set(vReferenceGridIndex.x - 1.0f, vReferenceGridIndex.y - 1.0f); vs[1] = globalMlaDescr.GetMicroLensCenter_px(vTargetLensIdcs[1]) - vMicroLensCenter_px; vs[1].normalize(); vTargetLensIdcs[2].Set(vReferenceGridIndex.x + 2.0f, vReferenceGridIndex.y - 1.0f); vs[2] = globalMlaDescr.GetMicroLensCenter_px(vTargetLensIdcs[2]) - vMicroLensCenter_px; vs[2].normalize(); #else // SECONDLENSLEVEL vTargetLensIdcs[0].x = vReferenceGridIndex.x + 0; vTargetLensIdcs[0].y = vReferenceGridIndex.y - 1.0f; vs[0] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[0]) - vMicroLensCenter_px; vs[0].normalize(); vTargetLensIdcs[1].x = vReferenceGridIndex.x + 1.0f; vTargetLensIdcs[1].y = vReferenceGridIndex.y - 1.0f; vs[1] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[1]) - vMicroLensCenter_px; vs[1].normalize(); vTargetLensIdcs[2].x = vReferenceGridIndex.x + 1.0f; vTargetLensIdcs[2].y = vReferenceGridIndex.y + 0; vs[2] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[2]) - vMicroLensCenter_px; vs[2].normalize(); vTargetLensIdcs[3].x = vReferenceGridIndex.x + 0; vTargetLensIdcs[3].y = vReferenceGridIndex.y + 1.0f; vs[3] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[3]) - vMicroLensCenter_px; vs[3].normalize(); vTargetLensIdcs[4].x = vReferenceGridIndex.x - 1.0f; vTargetLensIdcs[4].y = vReferenceGridIndex.y + 1.0f; vs[4] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[4]) - vMicroLensCenter_px; vs[4].normalize(); vTargetLensIdcs[5].x = vReferenceGridIndex.x - 1.0f; vTargetLensIdcs[5].y = vReferenceGridIndex.y + 0; vs[5] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[5]) - vMicroLensCenter_px; vs[5].normalize(); #endif // SECONDLENSLEVEL } // for all target lenses... int cntValid = 1; int cntOutOfBounds = 0; float fAvgDisp = fInitialDisparity_px; #ifdef SECONDLENSLEVEL for (int i=0; i<3; i++) #else // SECONDLENSLEVEL for (int i=0; i<6; i++) #endif //SECONDLENSLEVEL { // pixel relative to reference lens -> corresponding pixel in target lens -> add epiline * disp vec2<float> vTargetPixel_px = (vPixelPos_px - vMicroLensCenter_px) + globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[i]) - fInitialDisparity_px * vs[i]; // Get disparity estimated in other lens const float fTargetDisparity_px = tex2D<float>(texInputDisparities, vTargetPixel_px.x + 0.5f, vTargetPixel_px.y + 0.5f) #ifdef SECONDLENSLEVEL * ( ((t_eGridType==EGridType::HEXAGONAL)?1.73205f:2.0f) * globalMlaDescr.fMicroLensDistance_px); #else // SECONDLENSLEVEL *globalMlaDescr.fMicroLensDistance_px; #endif // SECONDLENSLEVEL if (fTargetDisparity_px == 0) continue; // Check validity and update mean if ((vTargetPixel_px - globalMlaDescr.GetMicroImageCenter_px<t_eGridType>(vTargetLensIdcs[i])).length() //+ 1.0f < globalMlaDescr.GetMicroImageRadius_px()) { cntValid += int(fabsf(fTargetDisparity_px - fInitialDisparity_px) < fMaxDispDiff); fAvgDisp += float(fabsf(fTargetDisparity_px - fInitialDisparity_px) < fMaxDispDiff) * fTargetDisparity_px; } else { cntOutOfBounds++; } } fAvgDisp /= float(cntValid); // set output outputDisparities[ unsigned(vPixelPos_px.y)*nWidth + unsigned(vPixelPos_px.x)] #ifdef SECONDLENSLEVEL // needs 1 additional valid neighbor = float(cntValid > 2 - cntOutOfBounds) * fAvgDisp / (((t_eGridType==EGridType::HEXAGONAL)?1.73205f:2.0f) * globalMlaDescr.fMicroLensDistance_px); #else // SECONDLENSLEVEL // needs 3 additional valid neighbor = float(cntValid > 2) * fAvgDisp / (globalMlaDescr.fMicroLensDistance_px); #endif // SECONDLENSLEVEL } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCUDADisparityRefinement_Crosscheck::RefineDisparities(CVImage_sptr& spDispartiesOut, const CVImage_sptr& spDispartiesIn) { hipError_t e; // Allocate and bind texture for input CCUDAImageTexture texInput(spDispartiesIn, false); // Allocate destination image if neccessary spDispartiesOut->Reinit(spDispartiesIn->GetImageDataDescriptor()); CCUDAImageArray<float> arrOutput(spDispartiesOut); // !!! ATTENTION : CUDA SPECIAL, if set to 0 memory is compromised ('random' values occur) hipMemset(arrOutput.GetDevicePointer(), 255, spDispartiesIn->bytecount()); if ((e = hipGetLastError()) != 0) { // Avoid copying empty CUDA array to output image (maybe same reference as input image) arrOutput.SkipDeviceCopy(); throw CRuntimeException(std::string("PIP::CCUDADisparityCrosscheck::Estimate : CUDA memset error : \"") + std::string(hipGetErrorString(e))); } // Call kernel // Each block represents a lens, each thread processes one pixel dim3 threadsPerBlock = dim3(32, 32); dim3 blocks = dim3( spDispartiesIn->cols() / 32 + 1, spDispartiesIn->rows() / 32 + 1 ); hipMemcpyToSymbol(globalMlaDescr, &m_descMla, sizeof(SPlenCamDescription)); if ((e = hipGetLastError()) != 0) { throw CRuntimeException(std::string("PIP::CCUDADisparityCrosscheck::Estimate : CUDA copy-to-symbol : \"") + std::string(hipGetErrorString(e))); } // create and start timer hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); hipEventRecord(start); if (m_descMla.eGridType == EGridType::HEXAGONAL) hipLaunchKernelGGL(( computeCrosscheck<EGridType::HEXAGONAL>), dim3(blocks), dim3(threadsPerBlock), 0, 0, arrOutput.GetDevicePointer(), texInput.GetTextureObject(), texInput.GetImageWidth(), texInput.GetImageHeight(), m_fMaxNormalizedDispDeviation); else hipLaunchKernelGGL(( computeCrosscheck<EGridType::RECTANGULAR>), dim3(blocks), dim3(threadsPerBlock), 0, 0, arrOutput.GetDevicePointer(), texInput.GetTextureObject(), texInput.GetImageWidth(), texInput.GetImageHeight(), m_fMaxNormalizedDispDeviation); // synchronize with kernels and check for errors hipDeviceSynchronize(); // Query runtime hipEventRecord(stop); hipEventSynchronize(stop); float milliseconds = 0; hipEventElapsedTime(&milliseconds, start, stop); printf("disparity crosscheck %g [ms]\n", milliseconds); if ((e = hipGetLastError()) != 0) { throw CRuntimeException(std::string("PIP::CCUDADisparityCrosscheck::Estimate : CUDA kernel launch error : \"") + std::string(hipGetErrorString(e))); } // exit : all CCUDAImage* will be destroyed and data is copied }
7d5c52e6704f66e219e97c2a2cdbca80fafbf9db.cu
/** * Copyright 2019 Arne Petersen, Kiel University * * 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 "DisparityRefinement_Crosscheck.hh" #include "PIPInterOpCUDA/CUDAImageArray.hh" #include "PIPInterOpCUDA/CUDAImageTexture.hh" #if !defined(WIN32) && !defined(_WIN32) && !defined(__WIN32) #include <unistd.h> #endif // not WIN32 using namespace PIP; __device__ __constant__ SPlenCamDescription globalMlaDescr; //#define SECONDLENSLEVEL //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// template<const EGridType t_eGridType> __global__ void computeCrosscheck(float* outputDisparities, cudaTextureObject_t texInputDisparities, const unsigned nWidth, const unsigned nHeight, const float fMaxDispDiff) { // Get pixel position and test 'in image' vec2<float> vPixelPos_px; vPixelPos_px.Set(blockIdx.x*blockDim.x + threadIdx.x, blockIdx.y*blockDim.y + threadIdx.y); // reject out of bounds pixels if (((vPixelPos_px.x < float(nWidth)-1) && (vPixelPos_px.y < float(nHeight)-1)) == false) { return; } // Initial disparity normalized with lens diameter (inter-lens distance) float fInitialDisparity_px = tex2D<float>(texInputDisparities, vPixelPos_px.x + 0.5f, vPixelPos_px.y + 0.5f); // Zero-disparity is invalid estimation if (fInitialDisparity_px == 0.0f) return; // Disparity in pixel relative to target lenses (2. level distance = 1.73205... micro lens distances) #ifdef SECONDLENSLEVEL if (t_eGridType == EGridType::HEXAGONAL) { fInitialDisparity_px = fInitialDisparity_px*(1.73205f * globalMlaDescr.fMicroLensDistance_px); } else { fInitialDisparity_px = fInitialDisparity_px*(2.0f * globalMlaDescr.fMicroLensDistance_px); } #else // SECONDLENSLEVEL fInitialDisparity_px = fInitialDisparity_px*(globalMlaDescr.fMicroLensDistance_px); #endif // SECONDLENSLEVEL // Get index of source lens in grid vec2<float> vReferenceGridIndex; // comming from plenoptic image implies using mirco-image grid vReferenceGridIndex = globalMlaDescr.PixelToLensImageGrid<t_eGridType>(vPixelPos_px); // round to integral lens index vReferenceGridIndex = globalMlaDescr.GridRound<t_eGridType>(vReferenceGridIndex); // Get baselines from target lens 'ring' vec2<float> vs[6]; vec2<float> vTargetLensIdcs[6]; vec2<float> vMicroLensCenter_px = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vReferenceGridIndex); { #ifdef SECONDLENSLEVEL vTargetLensIdcs[0].Set(vReferenceGridIndex.x - 1.0f, vReferenceGridIndex.y + 2.0f); vs[0] = globalMlaDescr.GetMicroLensCenter_px(vTargetLensIdcs[0]) - vMicroLensCenter_px; vs[0].normalize(); vTargetLensIdcs[1].Set(vReferenceGridIndex.x - 1.0f, vReferenceGridIndex.y - 1.0f); vs[1] = globalMlaDescr.GetMicroLensCenter_px(vTargetLensIdcs[1]) - vMicroLensCenter_px; vs[1].normalize(); vTargetLensIdcs[2].Set(vReferenceGridIndex.x + 2.0f, vReferenceGridIndex.y - 1.0f); vs[2] = globalMlaDescr.GetMicroLensCenter_px(vTargetLensIdcs[2]) - vMicroLensCenter_px; vs[2].normalize(); #else // SECONDLENSLEVEL vTargetLensIdcs[0].x = vReferenceGridIndex.x + 0; vTargetLensIdcs[0].y = vReferenceGridIndex.y - 1.0f; vs[0] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[0]) - vMicroLensCenter_px; vs[0].normalize(); vTargetLensIdcs[1].x = vReferenceGridIndex.x + 1.0f; vTargetLensIdcs[1].y = vReferenceGridIndex.y - 1.0f; vs[1] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[1]) - vMicroLensCenter_px; vs[1].normalize(); vTargetLensIdcs[2].x = vReferenceGridIndex.x + 1.0f; vTargetLensIdcs[2].y = vReferenceGridIndex.y + 0; vs[2] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[2]) - vMicroLensCenter_px; vs[2].normalize(); vTargetLensIdcs[3].x = vReferenceGridIndex.x + 0; vTargetLensIdcs[3].y = vReferenceGridIndex.y + 1.0f; vs[3] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[3]) - vMicroLensCenter_px; vs[3].normalize(); vTargetLensIdcs[4].x = vReferenceGridIndex.x - 1.0f; vTargetLensIdcs[4].y = vReferenceGridIndex.y + 1.0f; vs[4] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[4]) - vMicroLensCenter_px; vs[4].normalize(); vTargetLensIdcs[5].x = vReferenceGridIndex.x - 1.0f; vTargetLensIdcs[5].y = vReferenceGridIndex.y + 0; vs[5] = globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[5]) - vMicroLensCenter_px; vs[5].normalize(); #endif // SECONDLENSLEVEL } // for all target lenses... int cntValid = 1; int cntOutOfBounds = 0; float fAvgDisp = fInitialDisparity_px; #ifdef SECONDLENSLEVEL for (int i=0; i<3; i++) #else // SECONDLENSLEVEL for (int i=0; i<6; i++) #endif //SECONDLENSLEVEL { // pixel relative to reference lens -> corresponding pixel in target lens -> add epiline * disp vec2<float> vTargetPixel_px = (vPixelPos_px - vMicroLensCenter_px) + globalMlaDescr.GetMicroLensCenter_px<t_eGridType>(vTargetLensIdcs[i]) - fInitialDisparity_px * vs[i]; // Get disparity estimated in other lens const float fTargetDisparity_px = tex2D<float>(texInputDisparities, vTargetPixel_px.x + 0.5f, vTargetPixel_px.y + 0.5f) #ifdef SECONDLENSLEVEL * ( ((t_eGridType==EGridType::HEXAGONAL)?1.73205f:2.0f) * globalMlaDescr.fMicroLensDistance_px); #else // SECONDLENSLEVEL *globalMlaDescr.fMicroLensDistance_px; #endif // SECONDLENSLEVEL if (fTargetDisparity_px == 0) continue; // Check validity and update mean if ((vTargetPixel_px - globalMlaDescr.GetMicroImageCenter_px<t_eGridType>(vTargetLensIdcs[i])).length() //+ 1.0f < globalMlaDescr.GetMicroImageRadius_px()) { cntValid += int(fabsf(fTargetDisparity_px - fInitialDisparity_px) < fMaxDispDiff); fAvgDisp += float(fabsf(fTargetDisparity_px - fInitialDisparity_px) < fMaxDispDiff) * fTargetDisparity_px; } else { cntOutOfBounds++; } } fAvgDisp /= float(cntValid); // set output outputDisparities[ unsigned(vPixelPos_px.y)*nWidth + unsigned(vPixelPos_px.x)] #ifdef SECONDLENSLEVEL // needs 1 additional valid neighbor = float(cntValid > 2 - cntOutOfBounds) * fAvgDisp / (((t_eGridType==EGridType::HEXAGONAL)?1.73205f:2.0f) * globalMlaDescr.fMicroLensDistance_px); #else // SECONDLENSLEVEL // needs 3 additional valid neighbor = float(cntValid > 2) * fAvgDisp / (globalMlaDescr.fMicroLensDistance_px); #endif // SECONDLENSLEVEL } //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// void CCUDADisparityRefinement_Crosscheck::RefineDisparities(CVImage_sptr& spDispartiesOut, const CVImage_sptr& spDispartiesIn) { cudaError_t e; // Allocate and bind texture for input CCUDAImageTexture texInput(spDispartiesIn, false); // Allocate destination image if neccessary spDispartiesOut->Reinit(spDispartiesIn->GetImageDataDescriptor()); CCUDAImageArray<float> arrOutput(spDispartiesOut); // !!! ATTENTION : CUDA SPECIAL, if set to 0 memory is compromised ('random' values occur) cudaMemset(arrOutput.GetDevicePointer(), 255, spDispartiesIn->bytecount()); if ((e = cudaGetLastError()) != 0) { // Avoid copying empty CUDA array to output image (maybe same reference as input image) arrOutput.SkipDeviceCopy(); throw CRuntimeException(std::string("PIP::CCUDADisparityCrosscheck::Estimate : CUDA memset error : \"") + std::string(cudaGetErrorString(e))); } // Call kernel // Each block represents a lens, each thread processes one pixel dim3 threadsPerBlock = dim3(32, 32); dim3 blocks = dim3( spDispartiesIn->cols() / 32 + 1, spDispartiesIn->rows() / 32 + 1 ); cudaMemcpyToSymbol(globalMlaDescr, &m_descMla, sizeof(SPlenCamDescription)); if ((e = cudaGetLastError()) != 0) { throw CRuntimeException(std::string("PIP::CCUDADisparityCrosscheck::Estimate : CUDA copy-to-symbol : \"") + std::string(cudaGetErrorString(e))); } // create and start timer cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start); if (m_descMla.eGridType == EGridType::HEXAGONAL) computeCrosscheck<EGridType::HEXAGONAL><<<blocks, threadsPerBlock>>>(arrOutput.GetDevicePointer(), texInput.GetTextureObject(), texInput.GetImageWidth(), texInput.GetImageHeight(), m_fMaxNormalizedDispDeviation); else computeCrosscheck<EGridType::RECTANGULAR><<<blocks, threadsPerBlock>>>(arrOutput.GetDevicePointer(), texInput.GetTextureObject(), texInput.GetImageWidth(), texInput.GetImageHeight(), m_fMaxNormalizedDispDeviation); // synchronize with kernels and check for errors cudaDeviceSynchronize(); // Query runtime cudaEventRecord(stop); cudaEventSynchronize(stop); float milliseconds = 0; cudaEventElapsedTime(&milliseconds, start, stop); printf("disparity crosscheck %g [ms]\n", milliseconds); if ((e = cudaGetLastError()) != 0) { throw CRuntimeException(std::string("PIP::CCUDADisparityCrosscheck::Estimate : CUDA kernel launch error : \"") + std::string(cudaGetErrorString(e))); } // exit : all CCUDAImage* will be destroyed and data is copied }
a3795d73c033aad83841876573088293b69a5514.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <qudaQKXTM_Kepler.h> #include <errno.h> #include <mpi.h> #include <limits> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <typeinfo> #include <cuPrintf.cu> #define THREADS_PER_BLOCK 64 #define PI 3.141592653589793 //#define TIMING_REPORT using namespace quda; extern Topology *default_topo; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // $$ Section 2: Constant Refeneces $$ /* block for device constants */ __constant__ bool c_dimBreak[4]; __constant__ int c_nColor; __constant__ int c_nDim; __constant__ int c_localL[4]; __constant__ int c_plusGhost[4]; __constant__ int c_minusGhost[4]; __constant__ int c_stride; __constant__ int c_surface[4]; __constant__ int c_nSpin; __constant__ double c_alphaAPE; __constant__ double c_alphaGauss; __constant__ int c_threads; __constant__ int c_eps[6][3]; __constant__ int c_sgn_eps[6]; __constant__ int c_procPosition[4]; __constant__ int c_totalL[4]; __constant__ int c_Nmoms; __constant__ short int c_moms[MAX_NMOMENTA][3]; __constant__ short int c_mesons_indices[10][16][4]; __constant__ short int c_NTN_indices[16][4]; __constant__ short int c_NTR_indices[64][6]; __constant__ short int c_RTN_indices[64][6]; __constant__ short int c_RTR_indices[256][8]; __constant__ short int c_Delta_indices[3][16][4]; __constant__ float c_mesons_values[10][16]; __constant__ float c_NTN_values[16]; __constant__ float c_NTR_values[64]; __constant__ float c_RTN_values[64]; __constant__ float c_RTR_values[256]; __constant__ float c_Delta_values[3][16]; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////// /* Block for global variables */ float GK_deviceMemory = 0.; int GK_nColor; int GK_nSpin; int GK_nDim; int GK_strideFull; double GK_alphaAPE; double GK_alphaGauss; int GK_localVolume; int GK_totalVolume; int GK_nsmearAPE; int GK_nsmearGauss; bool GK_dimBreak[QUDAQKXTM_DIM]; int GK_localL[QUDAQKXTM_DIM]; int GK_totalL[QUDAQKXTM_DIM]; int GK_nProc[QUDAQKXTM_DIM]; int GK_plusGhost[QUDAQKXTM_DIM]; int GK_minusGhost[QUDAQKXTM_DIM]; int GK_surface3D[QUDAQKXTM_DIM]; bool GK_init_qudaQKXTM_Kepler_flag = false; int GK_Nsources; int GK_sourcePosition[MAX_NSOURCES][QUDAQKXTM_DIM]; int GK_Nmoms; short int GK_moms[MAX_NMOMENTA][3]; short int GK_mesons_indices[10][16][4] = {0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,2,0,2,0,2,1,3,0,2,2,0,0,2,3,1,1,3,0,2,1,3,1,3,1,3,2,0,1,3,3,1,2,0,0,2,2,0,1,3,2,0,2,0,2,0,3,1,3,1,0,2,3,1,1,3,3,1,2,0,3,1,3,1,0,3,0,3,0,3,1,2,0,3,2,1,0,3,3,0,1,2,0,3,1,2,1,2,1,2,2,1,1,2,3,0,2,1,0,3,2,1,1,2,2,1,2,1,2,1,3,0,3,0,0,3,3,0,1,2,3,0,2,1,3,0,3,0,0,3,0,3,0,3,1,2,0,3,2,1,0,3,3,0,1,2,0,3,1,2,1,2,1,2,2,1,1,2,3,0,2,1,0,3,2,1,1,2,2,1,2,1,2,1,3,0,3,0,0,3,3,0,1,2,3,0,2,1,3,0,3,0,0,2,0,2,0,2,1,3,0,2,2,0,0,2,3,1,1,3,0,2,1,3,1,3,1,3,2,0,1,3,3,1,2,0,0,2,2,0,1,3,2,0,2,0,2,0,3,1,3,1,0,2,3,1,1,3,3,1,2,0,3,1,3,1,0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2,0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2,0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,2,0,2,0,2,1,3,0,2,2,0,0,2,3,1,1,3,0,2,1,3,1,3,1,3,2,0,1,3,3,1,2,0,0,2,2,0,1,3,2,0,2,0,2,0,3,1,3,1,0,2,3,1,1,3,3,1,2,0,3,1,3,1}; float GK_mesons_values[10][16] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,-1,1,-1,-1,1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,1,1,-1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,-1,1,-1,-1,1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,1,1,-1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1}; short int GK_NTN_indices[16][4] = {0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2}; float GK_NTN_values[16] = {-1,1,-1,1,1,-1,1,-1,-1,1,-1,1,1,-1,1,-1}; short int GK_NTR_indices[64][6] = {0,1,0,3,0,2,0,1,0,3,1,3,0,1,0,3,2,0,0,1,0,3,3,1,0,1,1,2,0,2,0,1,1,2,1,3,0,1,1,2,2,0,0,1,1,2,3,1,0,1,2,1,0,2,0,1,2,1,1,3,0,1,2,1,2,0,0,1,2,1,3,1,0,1,3,0,0,2,0,1,3,0,1,3,0,1,3,0,2,0,0,1,3,0,3,1,1,0,0,3,0,2,1,0,0,3,1,3,1,0,0,3,2,0,1,0,0,3,3,1,1,0,1,2,0,2,1,0,1,2,1,3,1,0,1,2,2,0,1,0,1,2,3,1,1,0,2,1,0,2,1,0,2,1,1,3,1,0,2,1,2,0,1,0,2,1,3,1,1,0,3,0,0,2,1,0,3,0,1,3,1,0,3,0,2,0,1,0,3,0,3,1,2,3,0,3,0,2,2,3,0,3,1,3,2,3,0,3,2,0,2,3,0,3,3,1,2,3,1,2,0,2,2,3,1,2,1,3,2,3,1,2,2,0,2,3,1,2,3,1,2,3,2,1,0,2,2,3,2,1,1,3,2,3,2,1,2,0,2,3,2,1,3,1,2,3,3,0,0,2,2,3,3,0,1,3,2,3,3,0,2,0,2,3,3,0,3,1,3,2,0,3,0,2,3,2,0,3,1,3,3,2,0,3,2,0,3,2,0,3,3,1,3,2,1,2,0,2,3,2,1,2,1,3,3,2,1,2,2,0,3,2,1,2,3,1,3,2,2,1,0,2,3,2,2,1,1,3,3,2,2,1,2,0,3,2,2,1,3,1,3,2,3,0,0,2,3,2,3,0,1,3,3,2,3,0,2,0,3,2,3,0,3,1}; float GK_NTR_values[64] = {1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1}; short int GK_RTN_indices[64][6] = {0,3,0,1,0,2,0,3,0,1,1,3,0,3,0,1,2,0,0,3,0,1,3,1,0,3,1,0,0,2,0,3,1,0,1,3,0,3,1,0,2,0,0,3,1,0,3,1,0,3,2,3,0,2,0,3,2,3,1,3,0,3,2,3,2,0,0,3,2,3,3,1,0,3,3,2,0,2,0,3,3,2,1,3,0,3,3,2,2,0,0,3,3,2,3,1,1,2,0,1,0,2,1,2,0,1,1,3,1,2,0,1,2,0,1,2,0,1,3,1,1,2,1,0,0,2,1,2,1,0,1,3,1,2,1,0,2,0,1,2,1,0,3,1,1,2,2,3,0,2,1,2,2,3,1,3,1,2,2,3,2,0,1,2,2,3,3,1,1,2,3,2,0,2,1,2,3,2,1,3,1,2,3,2,2,0,1,2,3,2,3,1,2,1,0,1,0,2,2,1,0,1,1,3,2,1,0,1,2,0,2,1,0,1,3,1,2,1,1,0,0,2,2,1,1,0,1,3,2,1,1,0,2,0,2,1,1,0,3,1,2,1,2,3,0,2,2,1,2,3,1,3,2,1,2,3,2,0,2,1,2,3,3,1,2,1,3,2,0,2,2,1,3,2,1,3,2,1,3,2,2,0,2,1,3,2,3,1,3,0,0,1,0,2,3,0,0,1,1,3,3,0,0,1,2,0,3,0,0,1,3,1,3,0,1,0,0,2,3,0,1,0,1,3,3,0,1,0,2,0,3,0,1,0,3,1,3,0,2,3,0,2,3,0,2,3,1,3,3,0,2,3,2,0,3,0,2,3,3,1,3,0,3,2,0,2,3,0,3,2,1,3,3,0,3,2,2,0,3,0,3,2,3,1}; float GK_RTN_values[64] = {-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1}; short int GK_RTR_indices[256][8] = {0,3,0,3,0,2,0,2,0,3,0,3,0,2,1,3,0,3,0,3,0,2,2,0,0,3,0,3,0,2,3,1,0,3,0,3,1,3,0,2,0,3,0,3,1,3,1,3,0,3,0,3,1,3,2,0,0,3,0,3,1,3,3,1,0,3,0,3,2,0,0,2,0,3,0,3,2,0,1,3,0,3,0,3,2,0,2,0,0,3,0,3,2,0,3,1,0,3,0,3,3,1,0,2,0,3,0,3,3,1,1,3,0,3,0,3,3,1,2,0,0,3,0,3,3,1,3,1,0,3,1,2,0,2,0,2,0,3,1,2,0,2,1,3,0,3,1,2,0,2,2,0,0,3,1,2,0,2,3,1,0,3,1,2,1,3,0,2,0,3,1,2,1,3,1,3,0,3,1,2,1,3,2,0,0,3,1,2,1,3,3,1,0,3,1,2,2,0,0,2,0,3,1,2,2,0,1,3,0,3,1,2,2,0,2,0,0,3,1,2,2,0,3,1,0,3,1,2,3,1,0,2,0,3,1,2,3,1,1,3,0,3,1,2,3,1,2,0,0,3,1,2,3,1,3,1,0,3,2,1,0,2,0,2,0,3,2,1,0,2,1,3,0,3,2,1,0,2,2,0,0,3,2,1,0,2,3,1,0,3,2,1,1,3,0,2,0,3,2,1,1,3,1,3,0,3,2,1,1,3,2,0,0,3,2,1,1,3,3,1,0,3,2,1,2,0,0,2,0,3,2,1,2,0,1,3,0,3,2,1,2,0,2,0,0,3,2,1,2,0,3,1,0,3,2,1,3,1,0,2,0,3,2,1,3,1,1,3,0,3,2,1,3,1,2,0,0,3,2,1,3,1,3,1,0,3,3,0,0,2,0,2,0,3,3,0,0,2,1,3,0,3,3,0,0,2,2,0,0,3,3,0,0,2,3,1,0,3,3,0,1,3,0,2,0,3,3,0,1,3,1,3,0,3,3,0,1,3,2,0,0,3,3,0,1,3,3,1,0,3,3,0,2,0,0,2,0,3,3,0,2,0,1,3,0,3,3,0,2,0,2,0,0,3,3,0,2,0,3,1,0,3,3,0,3,1,0,2,0,3,3,0,3,1,1,3,0,3,3,0,3,1,2,0,0,3,3,0,3,1,3,1,1,2,0,3,0,2,0,2,1,2,0,3,0,2,1,3,1,2,0,3,0,2,2,0,1,2,0,3,0,2,3,1,1,2,0,3,1,3,0,2,1,2,0,3,1,3,1,3,1,2,0,3,1,3,2,0,1,2,0,3,1,3,3,1,1,2,0,3,2,0,0,2,1,2,0,3,2,0,1,3,1,2,0,3,2,0,2,0,1,2,0,3,2,0,3,1,1,2,0,3,3,1,0,2,1,2,0,3,3,1,1,3,1,2,0,3,3,1,2,0,1,2,0,3,3,1,3,1,1,2,1,2,0,2,0,2,1,2,1,2,0,2,1,3,1,2,1,2,0,2,2,0,1,2,1,2,0,2,3,1,1,2,1,2,1,3,0,2,1,2,1,2,1,3,1,3,1,2,1,2,1,3,2,0,1,2,1,2,1,3,3,1,1,2,1,2,2,0,0,2,1,2,1,2,2,0,1,3,1,2,1,2,2,0,2,0,1,2,1,2,2,0,3,1,1,2,1,2,3,1,0,2,1,2,1,2,3,1,1,3,1,2,1,2,3,1,2,0,1,2,1,2,3,1,3,1,1,2,2,1,0,2,0,2,1,2,2,1,0,2,1,3,1,2,2,1,0,2,2,0,1,2,2,1,0,2,3,1,1,2,2,1,1,3,0,2,1,2,2,1,1,3,1,3,1,2,2,1,1,3,2,0,1,2,2,1,1,3,3,1,1,2,2,1,2,0,0,2,1,2,2,1,2,0,1,3,1,2,2,1,2,0,2,0,1,2,2,1,2,0,3,1,1,2,2,1,3,1,0,2,1,2,2,1,3,1,1,3,1,2,2,1,3,1,2,0,1,2,2,1,3,1,3,1,1,2,3,0,0,2,0,2,1,2,3,0,0,2,1,3,1,2,3,0,0,2,2,0,1,2,3,0,0,2,3,1,1,2,3,0,1,3,0,2,1,2,3,0,1,3,1,3,1,2,3,0,1,3,2,0,1,2,3,0,1,3,3,1,1,2,3,0,2,0,0,2,1,2,3,0,2,0,1,3,1,2,3,0,2,0,2,0,1,2,3,0,2,0,3,1,1,2,3,0,3,1,0,2,1,2,3,0,3,1,1,3,1,2,3,0,3,1,2,0,1,2,3,0,3,1,3,1,2,1,0,3,0,2,0,2,2,1,0,3,0,2,1,3,2,1,0,3,0,2,2,0,2,1,0,3,0,2,3,1,2,1,0,3,1,3,0,2,2,1,0,3,1,3,1,3,2,1,0,3,1,3,2,0,2,1,0,3,1,3,3,1,2,1,0,3,2,0,0,2,2,1,0,3,2,0,1,3,2,1,0,3,2,0,2,0,2,1,0,3,2,0,3,1,2,1,0,3,3,1,0,2,2,1,0,3,3,1,1,3,2,1,0,3,3,1,2,0,2,1,0,3,3,1,3,1,2,1,1,2,0,2,0,2,2,1,1,2,0,2,1,3,2,1,1,2,0,2,2,0,2,1,1,2,0,2,3,1,2,1,1,2,1,3,0,2,2,1,1,2,1,3,1,3,2,1,1,2,1,3,2,0,2,1,1,2,1,3,3,1,2,1,1,2,2,0,0,2,2,1,1,2,2,0,1,3,2,1,1,2,2,0,2,0,2,1,1,2,2,0,3,1,2,1,1,2,3,1,0,2,2,1,1,2,3,1,1,3,2,1,1,2,3,1,2,0,2,1,1,2,3,1,3,1,2,1,2,1,0,2,0,2,2,1,2,1,0,2,1,3,2,1,2,1,0,2,2,0,2,1,2,1,0,2,3,1,2,1,2,1,1,3,0,2,2,1,2,1,1,3,1,3,2,1,2,1,1,3,2,0,2,1,2,1,1,3,3,1,2,1,2,1,2,0,0,2,2,1,2,1,2,0,1,3,2,1,2,1,2,0,2,0,2,1,2,1,2,0,3,1,2,1,2,1,3,1,0,2,2,1,2,1,3,1,1,3,2,1,2,1,3,1,2,0,2,1,2,1,3,1,3,1,2,1,3,0,0,2,0,2,2,1,3,0,0,2,1,3,2,1,3,0,0,2,2,0,2,1,3,0,0,2,3,1,2,1,3,0,1,3,0,2,2,1,3,0,1,3,1,3,2,1,3,0,1,3,2,0,2,1,3,0,1,3,3,1,2,1,3,0,2,0,0,2,2,1,3,0,2,0,1,3,2,1,3,0,2,0,2,0,2,1,3,0,2,0,3,1,2,1,3,0,3,1,0,2,2,1,3,0,3,1,1,3,2,1,3,0,3,1,2,0,2,1,3,0,3,1,3,1,3,0,0,3,0,2,0,2,3,0,0,3,0,2,1,3,3,0,0,3,0,2,2,0,3,0,0,3,0,2,3,1,3,0,0,3,1,3,0,2,3,0,0,3,1,3,1,3,3,0,0,3,1,3,2,0,3,0,0,3,1,3,3,1,3,0,0,3,2,0,0,2,3,0,0,3,2,0,1,3,3,0,0,3,2,0,2,0,3,0,0,3,2,0,3,1,3,0,0,3,3,1,0,2,3,0,0,3,3,1,1,3,3,0,0,3,3,1,2,0,3,0,0,3,3,1,3,1,3,0,1,2,0,2,0,2,3,0,1,2,0,2,1,3,3,0,1,2,0,2,2,0,3,0,1,2,0,2,3,1,3,0,1,2,1,3,0,2,3,0,1,2,1,3,1,3,3,0,1,2,1,3,2,0,3,0,1,2,1,3,3,1,3,0,1,2,2,0,0,2,3,0,1,2,2,0,1,3,3,0,1,2,2,0,2,0,3,0,1,2,2,0,3,1,3,0,1,2,3,1,0,2,3,0,1,2,3,1,1,3,3,0,1,2,3,1,2,0,3,0,1,2,3,1,3,1,3,0,2,1,0,2,0,2,3,0,2,1,0,2,1,3,3,0,2,1,0,2,2,0,3,0,2,1,0,2,3,1,3,0,2,1,1,3,0,2,3,0,2,1,1,3,1,3,3,0,2,1,1,3,2,0,3,0,2,1,1,3,3,1,3,0,2,1,2,0,0,2,3,0,2,1,2,0,1,3,3,0,2,1,2,0,2,0,3,0,2,1,2,0,3,1,3,0,2,1,3,1,0,2,3,0,2,1,3,1,1,3,3,0,2,1,3,1,2,0,3,0,2,1,3,1,3,1,3,0,3,0,0,2,0,2,3,0,3,0,0,2,1,3,3,0,3,0,0,2,2,0,3,0,3,0,0,2,3,1,3,0,3,0,1,3,0,2,3,0,3,0,1,3,1,3,3,0,3,0,1,3,2,0,3,0,3,0,1,3,3,1,3,0,3,0,2,0,0,2,3,0,3,0,2,0,1,3,3,0,3,0,2,0,2,0,3,0,3,0,2,0,3,1,3,0,3,0,3,1,0,2,3,0,3,0,3,1,1,3,3,0,3,0,3,1,2,0,3,0,3,0,3,1,3,1}; float GK_RTR_values[256] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; short int GK_Delta_indices[3][16][4] = {0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2}; float GK_Delta_values[3][16] = {1,-1,-1,1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1}; // for mpi use global variables MPI_Group GK_fullGroup , GK_spaceGroup , GK_timeGroup; MPI_Comm GK_spaceComm , GK_timeComm; int GK_localRank; int GK_localSize; int GK_timeRank; int GK_timeSize; ////////////////////////////////////////////////// static void createMomenta(int Q_sq){ int counter=0; for(int iQ = 0 ; iQ <= Q_sq ; iQ++){ for(int nx = iQ ; nx >= -iQ ; nx--) for(int ny = iQ ; ny >= -iQ ; ny--) for(int nz = iQ ; nz >= -iQ ; nz--){ if( nx*nx + ny*ny + nz*nz == iQ ){ GK_moms[counter][0] = nx; GK_moms[counter][1] = ny; GK_moms[counter][2] = nz; counter++; } } } if(counter > MAX_NMOMENTA)errorQuda("Error exceeded max number of momenta\n"); GK_Nmoms=counter; } void quda::init_qudaQKXTM_Kepler(qudaQKXTMinfo_Kepler *info){ if(GK_init_qudaQKXTM_Kepler_flag == false){ GK_nColor = 3; GK_nSpin = 4; GK_nDim = QUDAQKXTM_DIM; GK_alphaAPE = info->alphaAPE; GK_alphaGauss = info->alphaGauss; GK_nsmearAPE = info->nsmearAPE; GK_nsmearGauss = info->nsmearGauss; createMomenta(info->Q_sq); // from now on depends on lattice and break format we choose for(int i = 0 ; i < GK_nDim ; i++) GK_nProc[i] = comm_dim(i); for(int i = 0 ; i < GK_nDim ; i++){ // take local and total lattice GK_localL[i] = info->lL[i]; GK_totalL[i] = GK_nProc[i] * GK_localL[i]; } GK_localVolume = 1; GK_totalVolume = 1; for(int i = 0 ; i < GK_nDim ; i++){ GK_localVolume *= GK_localL[i]; GK_totalVolume *= GK_totalL[i]; } GK_strideFull = GK_localVolume; for (int i=0; i<GK_nDim; i++) { GK_surface3D[i] = 1; for (int j=0; j<GK_nDim; j++) { if (i==j) continue; GK_surface3D[i] *= GK_localL[j]; } } for(int i = 0 ; i < GK_nDim ; i++) if( GK_localL[i] == GK_totalL[i] ) GK_surface3D[i] = 0; for(int i = 0 ; i < GK_nDim ; i++){ GK_plusGhost[i] =0; GK_minusGhost[i] = 0; } #ifdef MULTI_GPU int lastIndex = GK_localVolume; for(int i = 0 ; i < GK_nDim ; i++) if( GK_localL[i] < GK_totalL[i] ){ GK_plusGhost[i] = lastIndex ; GK_minusGhost[i] = lastIndex + GK_surface3D[i]; lastIndex += 2*GK_surface3D[i]; } #endif for(int i = 0 ; i < GK_nDim ; i++){ if( GK_localL[i] < GK_totalL[i]) GK_dimBreak[i] = true; else GK_dimBreak[i] = false; } const int eps[6][3]= { {0,1,2}, {2,0,1}, {1,2,0}, {2,1,0}, {0,2,1}, {1,0,2} }; const int sgn_eps[6]= { +1,+1,+1,-1,-1,-1 }; int procPosition[4]; for(int i= 0 ; i < 4 ; i++) procPosition[i] = comm_coords(default_topo)[i]; // put it zero but change it later GK_Nsources = info->Nsources; if(GK_Nsources > MAX_NSOURCES) errorQuda("Error you exceeded maximum number of source position\n"); for(int is = 0 ; is < GK_Nsources ; is++) for(int i = 0 ; i < 4 ; i++) GK_sourcePosition[is][i] = info->sourcePosition[is][i]; // initialization consist also from define device constants hipMemcpyToSymbol(c_nColor, &GK_nColor, sizeof(int) ); hipMemcpyToSymbol(c_nSpin, &GK_nSpin, sizeof(int) ); hipMemcpyToSymbol(c_nDim, &GK_nDim, sizeof(int) ); hipMemcpyToSymbol(c_stride, &GK_strideFull, sizeof(int) ); hipMemcpyToSymbol(c_alphaAPE, &GK_alphaAPE , sizeof(double) ); hipMemcpyToSymbol(c_alphaGauss, &GK_alphaGauss , sizeof(double) ); hipMemcpyToSymbol(c_threads , &GK_localVolume , sizeof(double) ); // may change hipMemcpyToSymbol(c_dimBreak , GK_dimBreak , QUDAQKXTM_DIM*sizeof(bool) ); hipMemcpyToSymbol(c_localL , GK_localL , QUDAQKXTM_DIM*sizeof(int) ); hipMemcpyToSymbol(c_totalL , GK_totalL , QUDAQKXTM_DIM*sizeof(int) ); hipMemcpyToSymbol(c_plusGhost , GK_plusGhost , QUDAQKXTM_DIM*sizeof(int) ); hipMemcpyToSymbol(c_minusGhost , GK_minusGhost , QUDAQKXTM_DIM*sizeof(int) ); hipMemcpyToSymbol(c_surface , GK_surface3D , QUDAQKXTM_DIM*sizeof(int) ); hipMemcpyToSymbol(c_eps, &(eps[0][0]) , 6*3*sizeof(int) ); hipMemcpyToSymbol(c_sgn_eps, sgn_eps , 6*sizeof(int) ); hipMemcpyToSymbol(c_procPosition, procPosition, QUDAQKXTM_DIM*sizeof(int)); hipMemcpyToSymbol(c_Nmoms, &GK_Nmoms, sizeof(int)); hipMemcpyToSymbol(c_moms, GK_moms, MAX_NMOMENTA*3*sizeof(short int)); hipMemcpyToSymbol(c_mesons_indices,GK_mesons_indices,10*16*4*sizeof(short int)); hipMemcpyToSymbol(c_NTN_indices,GK_NTN_indices,16*4*sizeof(short int)); hipMemcpyToSymbol(c_NTR_indices,GK_NTR_indices,64*6*sizeof(short int)); hipMemcpyToSymbol(c_RTN_indices,GK_RTN_indices,64*6*sizeof(short int)); hipMemcpyToSymbol(c_RTR_indices,GK_RTR_indices,256*8*sizeof(short int)); hipMemcpyToSymbol(c_Delta_indices,GK_Delta_indices,3*16*4*sizeof(short int)); hipMemcpyToSymbol(c_mesons_values,GK_mesons_values,10*16*sizeof(float)); hipMemcpyToSymbol(c_NTN_values,GK_NTN_values,16*sizeof(float)); hipMemcpyToSymbol(c_NTR_values,GK_NTR_values,64*sizeof(float)); hipMemcpyToSymbol(c_RTN_values,GK_RTN_values,64*sizeof(float)); hipMemcpyToSymbol(c_RTR_values,GK_RTR_values,256*sizeof(float)); hipMemcpyToSymbol(c_Delta_values,GK_Delta_values,3*16*sizeof(float)); checkCudaError(); // create groups of process to use mpi reduce only on spatial points MPI_Comm_group(MPI_COMM_WORLD, &GK_fullGroup); int space3D_proc; space3D_proc = GK_nProc[0] * GK_nProc[1] * GK_nProc[2]; int *ranks = (int*) malloc(space3D_proc*sizeof(int)); for(int i= 0 ; i < space3D_proc ; i++) ranks[i] = comm_coords(default_topo)[3] + GK_nProc[3]*i; // for(int i= 0 ; i < space3D_proc ; i++) // printf("%d (%d,%d,%d,%d)\n",comm_rank(),comm_coords(default_topo)[0],comm_coords(default_topo)[1],comm_coords(default_topo)[2],comm_coords(default_topo)[3]); // for(int i= 0 ; i < space3D_proc ; i++) //printf("%d %d\n",comm_rank(),ranks[i]); MPI_Group_incl(GK_fullGroup,space3D_proc,ranks,&GK_spaceGroup); MPI_Group_rank(GK_spaceGroup,&GK_localRank); MPI_Group_size(GK_spaceGroup,&GK_localSize); MPI_Comm_create(MPI_COMM_WORLD, GK_spaceGroup , &GK_spaceComm); //if(GK_spaceComm == MPI_COMM_NULL) printf("NULL %d\n",comm_rank()); //exit(-1); // create group of process to use mpi gather int *ranksTime = (int*) malloc(GK_nProc[3]*sizeof(int)); for(int i=0 ; i < GK_nProc[3] ; i++) ranksTime[i] = i; MPI_Group_incl(GK_fullGroup,GK_nProc[3], ranksTime, &GK_timeGroup); MPI_Group_rank(GK_timeGroup, &GK_timeRank); MPI_Group_size(GK_timeGroup, &GK_timeSize); MPI_Comm_create(MPI_COMM_WORLD, GK_timeGroup, &GK_timeComm); ////////////////////////////////////////////////////////////////////////////// free(ranks); free(ranksTime); GK_init_qudaQKXTM_Kepler_flag = true; printfQuda("qudaQKXTM_Kepler has been initialized\n"); } else return; } void quda::printf_qudaQKXTM_Kepler(){ if(GK_init_qudaQKXTM_Kepler_flag == false) errorQuda("You must initialize init_qudaQKXTM_Kepler first"); printfQuda("Number of colors is %d\n",GK_nColor); printfQuda("Number of spins is %d\n",GK_nSpin); printfQuda("Number of dimensions is %d\n",GK_nDim); printfQuda("Number of process in each direction is (x,y,z,t) %d x %d x %d x %d\n",GK_nProc[0],GK_nProc[1],GK_nProc[2],GK_nProc[3]); printfQuda("Total lattice is (x,y,z,t) %d x %d x %d x %d\n",GK_totalL[0],GK_totalL[1],GK_totalL[2],GK_totalL[3]); printfQuda("Local lattice is (x,y,z,t) %d x %d x %d x %d\n",GK_localL[0],GK_localL[1],GK_localL[2],GK_localL[3]); printfQuda("Total volume is %d\n",GK_totalVolume); printfQuda("Local volume is %d\n",GK_localVolume); printfQuda("Surface is (x,y,z,t) ( %d , %d , %d , %d)\n",GK_surface3D[0],GK_surface3D[1],GK_surface3D[2],GK_surface3D[3]); printfQuda("The plus Ghost points in directions (x,y,z,t) ( %d , %d , %d , %d )\n",GK_plusGhost[0],GK_plusGhost[1],GK_plusGhost[2],GK_plusGhost[3]); printfQuda("The Minus Ghost points in directixons (x,y,z,t) ( %d , %d , %d , %d )\n",GK_minusGhost[0],GK_minusGhost[1],GK_minusGhost[2],GK_minusGhost[3]); printfQuda("For APE smearing we use nsmear = %d , alpha = %lf\n",GK_nsmearAPE,GK_alphaAPE); printfQuda("For Gauss smearing we use nsmear = %d , alpha = %lf\n",GK_nsmearGauss,GK_alphaGauss); printfQuda("I got %d source positions to work on\n",GK_Nsources); printfQuda("I got %d number of momenta to work on\n",GK_Nmoms); } static __inline__ __device__ double2 fetch_double2(hipTextureObject_t t, int i) { int4 v =tex1Dfetch<int4>(t,i); return make_double2(__hiloint2double(v.y, v.x), __hiloint2double(v.w, v.z)); } static __inline__ __device__ float2 fetch_float2(hipTextureObject_t t, int i) { float2 v = tex1Dfetch<float2>(t,i); return v; } template<typename Float2> __device__ inline Float2 operator*(const Float2 a, const Float2 b){ Float2 res; res.x = a.x*b.x - a.y*b.y; res.y = a.x*b.y + a.y*b.x; return res; } /* template<typename Float2, typename Float> __device__ inline Float2 operator*(const Float a , const Float2 b){ Float2 res; res.x = a*b.x; res.y = a*b.y; return res; } */ __device__ inline float2 operator*(const float a , const float2 b){ float2 res; res.x = a*b.x; res.y = a*b.y; return res; } __device__ inline double2 operator*(const double a , const double2 b){ double2 res; res.x = a*b.x; res.y = a*b.y; return res; } template<typename Float2> __device__ inline Float2 operator*(const int a , const Float2 b){ Float2 res; res.x = a*b.x; res.y = a*b.y; return res; } template<typename Float2> __device__ inline Float2 operator+(const Float2 a, const Float2 b){ Float2 res; res.x = a.x + b.x; res.y = a.y + b.y; return res; } template<typename Float2> __device__ inline Float2 operator-(const Float2 a, const Float2 b){ Float2 res; res.x = a.x - b.x; res.y = a.y - b.y; return res; } template<typename Float2> __device__ inline Float2 conj(const Float2 a){ Float2 res; res.x = a.x; res.y = -a.y; return res; } __device__ inline float norm(const float2 a){ float res; res = sqrt(a.x*a.x + a.y*a.y); return res; } __device__ inline double norm(const double2 a){ double res; res = sqrt(a.x*a.x + a.y*a.y); return res; } template<typename Float2> __device__ inline Float2 get_Projector(Float2 projector[4][4], WHICHPARTICLE PARTICLE, WHICHPROJECTOR PID){ // important Projectors must be in twisted basis #include <projectors_tm_base.h> } template<typename Float2> __device__ inline Float2 get_Operator(Float2 gamma[4][4], int flag, WHICHPARTICLE TESTPARTICLE, int partFlag){ #include <gammas_tm_base.h> } #include <core_def_Kepler.h> __global__ void calculatePlaq_kernel_double(hipTextureObject_t gaugeTexPlaq,double *partial_plaq){ #define FLOAT2 double2 #define FLOAT double #define READGAUGE_FLOAT READGAUGE_double #include <plaquette_core_Kepler.h> #undef FLOAT2 #undef FLOAT #undef READGAUGE_FLOAT } __global__ void calculatePlaq_kernel_float(hipTextureObject_t gaugeTexPlaq,float *partial_plaq){ #define FLOAT2 float2 #define FLOAT float #define READGAUGE_FLOAT READGAUGE_float #include <plaquette_core_Kepler.h> #undef READGAUGE_FLOAT #undef FLOAT2 #undef FLOAT } __global__ void gaussianSmearing_kernel_float(float2* out,hipTextureObject_t vecInTex,hipTextureObject_t gaugeTex ){ #define FLOAT2 float2 #define READGAUGE_FLOAT READGAUGE_float #define READVECTOR_FLOAT READVECTOR_float #include <Gauss_core_Kepler.h> #undef READGAUGE_FLOAT #undef READVECTOR_FLOAT #undef FLOAT2 } __global__ void gaussianSmearing_kernel_double(double2* out,hipTextureObject_t vecInTex,hipTextureObject_t gaugeTex ){ #define FLOAT2 double2 #define READGAUGE_FLOAT READGAUGE_double #define READVECTOR_FLOAT READVECTOR_double #include <Gauss_core_Kepler.h> #undef READGAUGE_FLOAT #undef READVECTOR_FLOAT #undef FLOAT2 } __global__ void contractMesons_kernel_float(float2* block, hipTextureObject_t prop1Tex, hipTextureObject_t prop2Tex,int it, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <contractMesons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void contractMesons_kernel_double(double2* block, hipTextureObject_t prop1Tex, hipTextureObject_t prop2Tex,int it, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <contractMesons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void contractBaryons_kernel_float(float2* block, hipTextureObject_t prop1Tex, hipTextureObject_t prop2Tex,int it, int x0, int y0, int z0, int ip){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <contractBaryons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } /* __global__ void contractBaryons_kernel_double(double2* block, hipTextureObject_t prop1Tex, hipTextureObject_t prop2Tex,int it, int x0, int y0, int z0, int ip){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <contractBaryons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } */ __global__ void seqSourceFixSinkPart1_kernel_float(float2* out, int timeslice, hipTextureObject_t tex1, hipTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <seqSourceFixSinkPart1_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void seqSourceFixSinkPart2_kernel_float(float2* out, int timeslice, hipTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <seqSourceFixSinkPart2_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void seqSourceFixSinkPart1_kernel_double(double2* out, int timeslice, hipTextureObject_t tex1, hipTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <seqSourceFixSinkPart1_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void seqSourceFixSinkPart2_kernel_double(double2* out, int timeslice, hipTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <seqSourceFixSinkPart2_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_local_kernel_float(float2* block, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <fixSinkContractions_local_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_local_kernel_double(double2* block, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <fixSinkContractions_local_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_noether_kernel_float(float2* block, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, hipTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <fixSinkContractions_noether_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_noether_kernel_double(double2* block, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, hipTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <fixSinkContractions_noether_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_oneD_kernel_float(float2* block, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, hipTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int dir, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <fixSinkContractions_oneD_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_oneD_kernel_double(double2* block, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, hipTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int dir, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <fixSinkContractions_oneD_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } template<typename Float, typename Float2> __global__ void scaleVector_kernel(Float a, Float2* inOut){ #include <scaleVector_core_Kepler.h> } template<typename Float2> __global__ void uploadToCuda_kernel(Float2 *in, double2 *outEven, double2 *outOdd){ #include <uploadToCuda_core_Kepler.h> } template<typename Float2> __global__ void downloadFromCuda_kernel(Float2 *out, double2 *inEven, double2 *inOdd){ #include <downloadFromCuda_core_Kepler.h> } template<typename Float2> __global__ void rotateToPhysicalBase_kernel(Float2 *inOut, int sign){ #include <rotateToPhysicalBase_core_Kepler.h> } __global__ void castDoubleToFloat_kernel(float2 *out, double2 *in){ #include <castDoubleToFloat_core_Kepler.h> } __global__ void castFloatToDouble_kernel(double2 *out, float2 *in){ #include <castFloatToDouble_core_Kepler.h> } template<typename Float2> __global__ void conjugate_vector_kernel(Float2 *inOut){ #include <conjugate_vector_core_Kepler.h> } template<typename Float2> __global__ void apply_gamma5_vector_kernel(Float2 *inOut){ #include <apply_gamma5_vector_core_Kepler.h> } template<typename Float2> __global__ void conjugate_propagator_kernel(Float2 *inOut){ #include <conjugate_propagator_core_Kepler.h> } template<typename Float2> __global__ void apply_gamma5_propagator_kernel(Float2 *inOut){ #include <apply_gamma5_propagator_core_Kepler.h> } template<typename Float> static Float calculatePlaq_kernel(hipTextureObject_t gaugeTexPlaq){ Float plaquette = 0.; Float globalPlaquette = 0.; dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); Float *h_partial_plaq = NULL; Float *d_partial_plaq = NULL; h_partial_plaq = (Float*) malloc(gridDim.x * sizeof(Float) ); if(h_partial_plaq == NULL) errorQuda("Error allocate memory for host partial plaq"); hipMalloc((void**)&d_partial_plaq, gridDim.x * sizeof(Float)); #ifdef TIMING_REPORT hipEvent_t start,stop; float elapsedTime; hipEventCreate(&start); hipEventCreate(&stop); hipEventRecord(start,0); #endif if( typeid(Float) == typeid(float) ) hipLaunchKernelGGL(( calculatePlaq_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, gaugeTexPlaq,(float*) d_partial_plaq); else if(typeid(Float) == typeid(double)) hipLaunchKernelGGL(( calculatePlaq_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, gaugeTexPlaq,(double*) d_partial_plaq); #ifdef TIMING_REPORT hipEventRecord(stop,0); hipEventSynchronize(stop); hipEventElapsedTime(&elapsedTime,start,stop); hipEventDestroy(start); hipEventDestroy(stop); printfQuda("Elapsed time for plaquette kernel is %f ms\n",elapsedTime); #endif hipMemcpy(h_partial_plaq, d_partial_plaq , gridDim.x * sizeof(Float) , hipMemcpyDeviceToHost); for(int i = 0 ; i < gridDim.x ; i++) plaquette += h_partial_plaq[i]; free(h_partial_plaq); hipFree(d_partial_plaq); checkCudaError(); int rc; if(typeid(Float) == typeid(double)) rc = MPI_Allreduce(&plaquette , &globalPlaquette , 1 , MPI_DOUBLE , MPI_SUM , MPI_COMM_WORLD); else if( typeid(Float) == typeid(float) ) rc = MPI_Allreduce(&plaquette , &globalPlaquette , 1 , MPI_FLOAT , MPI_SUM , MPI_COMM_WORLD); if( rc != MPI_SUCCESS ) errorQuda("Error in MPI reduction for plaquette"); return globalPlaquette/(GK_totalVolume*GK_nColor*6); } void quda::run_calculatePlaq_kernel(hipTextureObject_t gaugeTexPlaq, int precision){ if(precision == 4){ float plaq = calculatePlaq_kernel<float>(gaugeTexPlaq); printfQuda("Calculated plaquette in single precision is %f\n",plaq); } else if(precision == 8){ double plaq = calculatePlaq_kernel<double>(gaugeTexPlaq); printfQuda("Calculated plaquette in double precision is %lf\n",plaq); } else{ errorQuda("Precision not supported\n"); } } template<typename Float> static void gaussianSmearing_kernel(void* out,hipTextureObject_t vecInTex, hipTextureObject_t gaugeTex){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); #ifdef TIMING_REPORT hipEvent_t start,stop; float elapsedTime; hipEventCreate(&start); hipEventCreate(&stop); hipEventRecord(start,0); #endif if( typeid(Float) == typeid(float) ) hipLaunchKernelGGL(( gaussianSmearing_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) out, vecInTex, gaugeTex); else if(typeid(Float) == typeid(double)) hipLaunchKernelGGL(( gaussianSmearing_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) out, vecInTex, gaugeTex); checkCudaError(); #ifdef TIMING_REPORT hipEventRecord(stop,0); hipEventSynchronize(stop); hipEventElapsedTime(&elapsedTime,start,stop); hipEventDestroy(start); hipEventDestroy(stop); printfQuda("Elapsed time for 1 step in gaussian smearing is %f ms\n",elapsedTime); #endif } void quda::run_GaussianSmearing(void* out, hipTextureObject_t vecInTex, hipTextureObject_t gaugeTex, int precision){ if(precision == 4){ gaussianSmearing_kernel<float>(out,vecInTex,gaugeTex); } else if(precision == 8){ gaussianSmearing_kernel<double>(out,vecInTex,gaugeTex); } else{ errorQuda("Precision not supported\n"); } } void quda::run_UploadToCuda(void* in,cudaColorSpinorField &qudaVec, int precision, bool isEven){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if( qudaVec.SiteSubset() == QUDA_PARITY_SITE_SUBSET ){ if( isEven ){ if(precision == 4){ hipLaunchKernelGGL(( uploadToCuda_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) in,(double2*) qudaVec.V(), NULL ); } else if(precision == 8){ hipLaunchKernelGGL(( uploadToCuda_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) in,(double2*) qudaVec.V(), NULL ); } else{ errorQuda("Precision not supported\n"); } } else{ if(precision == 4){ hipLaunchKernelGGL(( uploadToCuda_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) in, NULL,(double2*) qudaVec.V() ); } else if(precision == 8){ hipLaunchKernelGGL(( uploadToCuda_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) in, NULL,(double2*) qudaVec.V()); } else{ errorQuda("Precision not supported\n"); } } } else{ if(precision == 4){ hipLaunchKernelGGL(( uploadToCuda_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) in,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else if(precision == 8){ hipLaunchKernelGGL(( uploadToCuda_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) in,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else{ errorQuda("Precision not supported\n"); } } checkCudaError(); } void quda::run_DownloadFromCuda(void* out,cudaColorSpinorField &qudaVec, int precision, bool isEven){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if( qudaVec.SiteSubset() == QUDA_PARITY_SITE_SUBSET ){ if( isEven ){ if(precision == 4){ hipLaunchKernelGGL(( downloadFromCuda_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) out,(double2*) qudaVec.V(), NULL ); } else if(precision == 8){ hipLaunchKernelGGL(( downloadFromCuda_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) out,(double2*) qudaVec.V(), NULL ); } else{ errorQuda("Precision not supported\n"); } } else{ if(precision == 4){ hipLaunchKernelGGL(( downloadFromCuda_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) out, NULL,(double2*) qudaVec.V() ); } else if(precision == 8){ hipLaunchKernelGGL(( downloadFromCuda_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) out, NULL,(double2*) qudaVec.V()); } else{ errorQuda("Precision not supported\n"); } } } else{ if(precision == 4){ hipLaunchKernelGGL(( downloadFromCuda_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) out,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else if(precision == 8){ hipLaunchKernelGGL(( downloadFromCuda_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) out,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else{ errorQuda("Precision not supported\n"); } } checkCudaError(); } void quda::run_ScaleVector(double a, void* inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ hipLaunchKernelGGL(( scaleVector_kernel<float,float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float) a, (float2*) inOut); } else if(precision == 8){ hipLaunchKernelGGL(( scaleVector_kernel<double,double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double) a, (double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } template<typename Float2,typename Float> static void contractMesons_kernel(hipTextureObject_t texProp1,hipTextureObject_t texProp2,Float (*corr)[2][10], int it, int isource){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); // spawn threads only for the spatial volume Float *h_partial_block = NULL; Float *d_partial_block = NULL; h_partial_block = (Float*)malloc(GK_Nmoms*2*10*gridDim.x*2*sizeof(Float)); if(h_partial_block == NULL) errorQuda("Error problem with allocation\n"); hipMalloc((void**)&d_partial_block, GK_Nmoms*2*10*gridDim.x*2 * sizeof(Float) ); checkCudaError(); Float *reduction =(Float*) calloc(GK_Nmoms*2*10*2,sizeof(Float)); if( typeid(Float2) == typeid(float2) ) hipLaunchKernelGGL(( contractMesons_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else hipLaunchKernelGGL(( contractMesons_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); checkCudaError(); hipMemcpy(h_partial_block , d_partial_block , GK_Nmoms*2*10*gridDim.x*2 * sizeof(Float) , hipMemcpyDeviceToHost); checkCudaError(); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int ip = 0 ; ip < 10 ; ip++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*2*10*2 + iu*10*2 + ip*2 + 0] += h_partial_block[imom*2*10*gridDim.x*2 + iu*10*gridDim.x*2 + ip*gridDim.x*2 + i*2 + 0]; reduction[imom*2*10*2 + iu*10*2 + ip*2 + 1] += h_partial_block[imom*2*10*gridDim.x*2 + iu*10*gridDim.x*2 + ip*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int ip = 0 ; ip < 10 ; ip++){ corr[it*GK_Nmoms*2 + imom*2 + 0][iu][ip] = reduction[imom*2*10*2 + iu*10*2 + ip*2 + 0]; corr[it*GK_Nmoms*2 + imom*2 + 1][iu][ip] = reduction[imom*2*10*2 + iu*10*2 + ip*2 + 1]; } free(h_partial_block); hipFree(d_partial_block); checkCudaError(); free(reduction); } void quda::run_contractMesons(hipTextureObject_t texProp1,hipTextureObject_t texProp2,void* corr, int it, int isource, int precision){ if(precision == 4){ contractMesons_kernel<float2,float>(texProp1,texProp2,(float(*)[2][10]) corr,it, isource); } else if(precision == 8){ contractMesons_kernel<double2,double>(texProp1,texProp2,(double(*)[2][10]) corr,it, isource); } else{ errorQuda("Precision not supported\n"); } } template<typename Float2,typename Float> static void contractBaryons_kernel(hipTextureObject_t texProp1,hipTextureObject_t texProp2,Float (*corr)[2][10][4][4], int it, int isource){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); // spawn threads only for the spatial volume Float *h_partial_block = NULL; Float *d_partial_block = NULL; h_partial_block = (Float*)malloc(GK_Nmoms*2*4*4*gridDim.x*2*sizeof(Float)); if(h_partial_block == NULL) errorQuda("Error problem with allocation\n"); hipMalloc((void**)&d_partial_block, GK_Nmoms*2*4*4*gridDim.x*2 * sizeof(Float) ); checkCudaError(); Float *reduction =(Float*) calloc(GK_Nmoms*2*4*4*2,sizeof(Float)); for(int ip = 0 ; ip < 10 ; ip++){ if( typeid(Float2) == typeid(float2) ) hipLaunchKernelGGL(( contractBaryons_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2],ip); // else // contractBaryons_kernel_double<<<gridDim,blockDim>>>((double2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2],ip); hipMemcpy(h_partial_block , d_partial_block , GK_Nmoms*2*4*4*gridDim.x*2 * sizeof(Float) , hipMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*2*4*4*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int gamma = 0 ; gamma < 4 ; gamma++) for(int gammap = 0 ; gammap < 4 ; gammap++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 0] += h_partial_block[imom*2*4*4*gridDim.x*2 + iu*4*4*gridDim.x*2 + gamma*4*gridDim.x*2 + gammap*gridDim.x*2 + i*2 + 0]; reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 1] += h_partial_block[imom*2*4*4*gridDim.x*2 + iu*4*4*gridDim.x*2 + gamma*4*gridDim.x*2 + gammap*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int gamma = 0 ; gamma < 4 ; gamma++) for(int gammap = 0 ; gammap < 4 ; gammap++){ corr[it*GK_Nmoms*2 + imom*2 + 0][iu][ip][gamma][gammap] = reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 0]; corr[it*GK_Nmoms*2 + imom*2 + 1][iu][ip][gamma][gammap] = reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 1]; } } // for over the particles free(h_partial_block); hipFree(d_partial_block); checkCudaError(); free(reduction); } void quda::run_contractBaryons(hipTextureObject_t texProp1,hipTextureObject_t texProp2,void* corr, int it, int isource, int precision){ hipFuncSetCacheConfig(contractBaryons_kernel_float,hipFuncCachePreferShared); // hipFuncSetCacheConfig("contractBaryons_kernel_double",hipFuncCachePreferShared); checkCudaError(); if(precision == 4){ contractBaryons_kernel<float2,float>(texProp1,texProp2,(float(*)[2][10][4][4]) corr,it, isource); } else if(precision == 8){ //contractBaryons_kernel<double2,double>(texProp1,texProp2,(double(*)[2][10][4][4]) corr,it, isource); errorQuda("For test reasons I do not need it\n"); } else{ errorQuda("Precision not supported\n"); } } void quda::run_rotateToPhysicalBase(void* inOut, int sign, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ hipLaunchKernelGGL(( rotateToPhysicalBase_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) inOut,sign); } else if(precision == 8){ hipLaunchKernelGGL(( rotateToPhysicalBase_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) inOut,sign); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_castDoubleToFloat(void *out, void *in){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); hipLaunchKernelGGL(( castDoubleToFloat_kernel), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) out, (double2*) in); checkCudaError(); } void quda::run_castFloatToDouble(void *out, void *in){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); hipLaunchKernelGGL(( castFloatToDouble_kernel), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) out, (float2*) in); checkCudaError(); } void quda::run_conjugate_vector(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ hipLaunchKernelGGL(( conjugate_vector_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) inOut); } else if(precision == 8){ hipLaunchKernelGGL(( conjugate_vector_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_apply_gamma5_vector(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ hipLaunchKernelGGL(( apply_gamma5_vector_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) inOut); } else if(precision == 8){ hipLaunchKernelGGL(( apply_gamma5_vector_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_conjugate_propagator(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ hipLaunchKernelGGL(( conjugate_propagator_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) inOut); } else if(precision == 8){ hipLaunchKernelGGL(( conjugate_propagator_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_apply_gamma5_propagator(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ hipLaunchKernelGGL(( apply_gamma5_propagator_kernel<float2>), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) inOut); } else if(precision == 8){ hipLaunchKernelGGL(( apply_gamma5_propagator_kernel<double2>), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } template<typename Float> static void seqSourceFixSinkPart1_kernel(void* out, int timeslice, hipTextureObject_t tex1, hipTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); if( typeid(Float) == typeid(float) ) hipLaunchKernelGGL(( seqSourceFixSinkPart1_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); else if(typeid(Float) == typeid(double)) hipLaunchKernelGGL(( seqSourceFixSinkPart1_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); checkCudaError(); } template<typename Float> static void seqSourceFixSinkPart2_kernel(void* out, int timeslice, hipTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); if( typeid(Float) == typeid(float) ) hipLaunchKernelGGL(( seqSourceFixSinkPart2_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); else if(typeid(Float) == typeid(double)) hipLaunchKernelGGL(( seqSourceFixSinkPart2_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); checkCudaError(); } void quda::run_seqSourceFixSinkPart1(void* out, int timeslice, hipTextureObject_t tex1, hipTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE, int precision){ if(precision == 4){ seqSourceFixSinkPart1_kernel<float>(out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); } else if(precision == 8){ seqSourceFixSinkPart1_kernel<double>(out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); } else{ errorQuda("Precision not supported\n"); } } void quda::run_seqSourceFixSinkPart2(void* out, int timeslice, hipTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE, int precision){ if(precision == 4){ seqSourceFixSinkPart2_kernel<float>(out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); } else if(precision == 8){ seqSourceFixSinkPart2_kernel<double>(out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); } else{ errorQuda("Precision not supported\n"); } } template<typename Float2,typename Float> static void fixSinkContractions_kernel(void* corrThp_local, void* corrThp_noether, void *corrThp_oneD, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, hipTextureObject_t gaugeTex, WHICHPARTICLE PARTICLE, int partflag, int itime, int isource){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); // spawn threads only for the spatial volume Float *h_partial_block = NULL; Float *d_partial_block = NULL; h_partial_block = (Float*)malloc(GK_Nmoms*16*gridDim.x*2*sizeof(Float)); if(h_partial_block == NULL) errorQuda("Error problem with allocation\n"); hipMalloc((void**)&d_partial_block, GK_Nmoms*16*gridDim.x*2 * sizeof(Float) ); checkCudaError(); Float *reduction =(Float*) calloc(GK_Nmoms*16*2,sizeof(Float)); ///////////////////////////////////////////// ultra local operators /////////////////////// if( typeid(Float2) == typeid(float2) ) hipLaunchKernelGGL(( fixSinkContractions_local_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) d_partial_block, fwdTex, seqTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else if( typeid(Float2) == typeid(double2) ) hipLaunchKernelGGL(( fixSinkContractions_local_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) d_partial_block, fwdTex, seqTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); hipMemcpy(h_partial_block , d_partial_block , GK_Nmoms*16*gridDim.x*2 * sizeof(Float) , hipMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*16*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*16*2 + iop*2 + 0] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 0]; reduction[imom*16*2 + iop*2 + 1] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ ((Float*) corrThp_local)[itime*GK_Nmoms*16*2 + imom*16*2 + iop*2 + 0] = reduction[imom*16*2 + iop*2 + 0]; ((Float*) corrThp_local)[itime*GK_Nmoms*16*2 + imom*16*2 + iop*2 + 1] = reduction[imom*16*2 + iop*2 + 1]; } //////////////////////////////////////////////// //////////////////////////// noether conserved current //////// if( typeid(Float2) == typeid(float2) ) hipLaunchKernelGGL(( fixSinkContractions_noether_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else if( typeid(Float2) == typeid(double2) ) hipLaunchKernelGGL(( fixSinkContractions_noether_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); hipMemcpy(h_partial_block , d_partial_block , GK_Nmoms*4*gridDim.x*2 * sizeof(Float) , hipMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*4*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int dir = 0 ; dir < 4 ; dir++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*4*2 + dir*2 + 0] += h_partial_block[imom*4*gridDim.x*2 + dir*gridDim.x*2 + i*2 + 0]; reduction[imom*4*2 + dir*2 + 1] += h_partial_block[imom*4*gridDim.x*2 + dir*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int dir = 0 ; dir < 4 ; dir++) for(int i =0 ; i < gridDim.x ; i++){ ((Float*) corrThp_noether)[itime*GK_Nmoms*4*2 + imom*4*2 + dir*2 + 0] = reduction[imom*4*2 + dir*2 + 0]; ((Float*) corrThp_noether)[itime*GK_Nmoms*4*2 + imom*4*2 + dir*2 + 1] = reduction[imom*4*2 + dir*2 + 1]; } ///////////////////////////////////// //////////////////////////// one derivative current //////// // cudaPrintfInit(); for(int dir = 0 ; dir < 4 ; dir++){ if( typeid(Float2) == typeid(float2) ) hipLaunchKernelGGL(( fixSinkContractions_oneD_kernel_float), dim3(gridDim),dim3(blockDim), 0, 0, (float2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, dir, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else if( typeid(Float2) == typeid(double2) ) hipLaunchKernelGGL(( fixSinkContractions_oneD_kernel_double), dim3(gridDim),dim3(blockDim), 0, 0, (double2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, dir, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); // if(comm_rank() == 0) cudaPrintfDisplay(stdout,true); hipMemcpy(h_partial_block , d_partial_block , GK_Nmoms*16*gridDim.x*2 * sizeof(Float) , hipMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*16*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*16*2 + iop*2 + 0] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 0]; reduction[imom*16*2 + iop*2 + 1] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ ((Float*) corrThp_oneD)[itime*GK_Nmoms*4*16*2 + imom*4*16*2 + dir*16*2 + iop*2 + 0] = reduction[imom*16*2 + iop*2 + 0]; ((Float*) corrThp_oneD)[itime*GK_Nmoms*4*16*2 + imom*4*16*2 + dir*16*2 + iop*2 + 1] = reduction[imom*16*2 + iop*2 + 1]; } } // cudaPrintfEnd(); ///////////////////////////////////// free(h_partial_block); hipFree(d_partial_block); checkCudaError(); free(reduction); } void quda::run_fixSinkContractions(void* corrThp_local, void* corrThp_noether, void* corrThp_oneD, hipTextureObject_t fwdTex, hipTextureObject_t seqTex, hipTextureObject_t gaugeTex, WHICHPARTICLE PARTICLE, int partflag, int it, int isource, int precision){ if(precision == 4){ fixSinkContractions_kernel<float2,float>(corrThp_local,corrThp_noether,corrThp_oneD,fwdTex,seqTex,gaugeTex,PARTICLE,partflag, it, isource); } else if(precision == 8){ fixSinkContractions_kernel<double2,double>(corrThp_local,corrThp_noether,corrThp_oneD,fwdTex,seqTex,gaugeTex,PARTICLE,partflag, it, isource); } else{ errorQuda("Precision not supported\n"); } }
a3795d73c033aad83841876573088293b69a5514.cu
#include <qudaQKXTM_Kepler.h> #include <errno.h> #include <mpi.h> #include <limits> #include <string.h> #include <stdlib.h> #include <stdio.h> #include <typeinfo> #include <cuPrintf.cu> #define THREADS_PER_BLOCK 64 #define PI 3.141592653589793 //#define TIMING_REPORT using namespace quda; extern Topology *default_topo; //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// // $$ Section 2: Constant Refeneces $$ /* block for device constants */ __constant__ bool c_dimBreak[4]; __constant__ int c_nColor; __constant__ int c_nDim; __constant__ int c_localL[4]; __constant__ int c_plusGhost[4]; __constant__ int c_minusGhost[4]; __constant__ int c_stride; __constant__ int c_surface[4]; __constant__ int c_nSpin; __constant__ double c_alphaAPE; __constant__ double c_alphaGauss; __constant__ int c_threads; __constant__ int c_eps[6][3]; __constant__ int c_sgn_eps[6]; __constant__ int c_procPosition[4]; __constant__ int c_totalL[4]; __constant__ int c_Nmoms; __constant__ short int c_moms[MAX_NMOMENTA][3]; __constant__ short int c_mesons_indices[10][16][4]; __constant__ short int c_NTN_indices[16][4]; __constant__ short int c_NTR_indices[64][6]; __constant__ short int c_RTN_indices[64][6]; __constant__ short int c_RTR_indices[256][8]; __constant__ short int c_Delta_indices[3][16][4]; __constant__ float c_mesons_values[10][16]; __constant__ float c_NTN_values[16]; __constant__ float c_NTR_values[64]; __constant__ float c_RTN_values[64]; __constant__ float c_RTR_values[256]; __constant__ float c_Delta_values[3][16]; ///////////////////////////////////////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////// /* Block for global variables */ float GK_deviceMemory = 0.; int GK_nColor; int GK_nSpin; int GK_nDim; int GK_strideFull; double GK_alphaAPE; double GK_alphaGauss; int GK_localVolume; int GK_totalVolume; int GK_nsmearAPE; int GK_nsmearGauss; bool GK_dimBreak[QUDAQKXTM_DIM]; int GK_localL[QUDAQKXTM_DIM]; int GK_totalL[QUDAQKXTM_DIM]; int GK_nProc[QUDAQKXTM_DIM]; int GK_plusGhost[QUDAQKXTM_DIM]; int GK_minusGhost[QUDAQKXTM_DIM]; int GK_surface3D[QUDAQKXTM_DIM]; bool GK_init_qudaQKXTM_Kepler_flag = false; int GK_Nsources; int GK_sourcePosition[MAX_NSOURCES][QUDAQKXTM_DIM]; int GK_Nmoms; short int GK_moms[MAX_NMOMENTA][3]; short int GK_mesons_indices[10][16][4] = {0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,2,0,2,0,2,1,3,0,2,2,0,0,2,3,1,1,3,0,2,1,3,1,3,1,3,2,0,1,3,3,1,2,0,0,2,2,0,1,3,2,0,2,0,2,0,3,1,3,1,0,2,3,1,1,3,3,1,2,0,3,1,3,1,0,3,0,3,0,3,1,2,0,3,2,1,0,3,3,0,1,2,0,3,1,2,1,2,1,2,2,1,1,2,3,0,2,1,0,3,2,1,1,2,2,1,2,1,2,1,3,0,3,0,0,3,3,0,1,2,3,0,2,1,3,0,3,0,0,3,0,3,0,3,1,2,0,3,2,1,0,3,3,0,1,2,0,3,1,2,1,2,1,2,2,1,1,2,3,0,2,1,0,3,2,1,1,2,2,1,2,1,2,1,3,0,3,0,0,3,3,0,1,2,3,0,2,1,3,0,3,0,0,2,0,2,0,2,1,3,0,2,2,0,0,2,3,1,1,3,0,2,1,3,1,3,1,3,2,0,1,3,3,1,2,0,0,2,2,0,1,3,2,0,2,0,2,0,3,1,3,1,0,2,3,1,1,3,3,1,2,0,3,1,3,1,0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2,0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2,0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,2,0,2,0,2,1,3,0,2,2,0,0,2,3,1,1,3,0,2,1,3,1,3,1,3,2,0,1,3,3,1,2,0,0,2,2,0,1,3,2,0,2,0,2,0,3,1,3,1,0,2,3,1,1,3,3,1,2,0,3,1,3,1}; float GK_mesons_values[10][16] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,-1,1,-1,-1,1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,1,1,-1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,-1,1,-1,-1,1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,1,-1,1,1,-1,1,-1,-1,1,1,-1,-1,1,-1,1,1,-1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1}; short int GK_NTN_indices[16][4] = {0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2}; float GK_NTN_values[16] = {-1,1,-1,1,1,-1,1,-1,-1,1,-1,1,1,-1,1,-1}; short int GK_NTR_indices[64][6] = {0,1,0,3,0,2,0,1,0,3,1,3,0,1,0,3,2,0,0,1,0,3,3,1,0,1,1,2,0,2,0,1,1,2,1,3,0,1,1,2,2,0,0,1,1,2,3,1,0,1,2,1,0,2,0,1,2,1,1,3,0,1,2,1,2,0,0,1,2,1,3,1,0,1,3,0,0,2,0,1,3,0,1,3,0,1,3,0,2,0,0,1,3,0,3,1,1,0,0,3,0,2,1,0,0,3,1,3,1,0,0,3,2,0,1,0,0,3,3,1,1,0,1,2,0,2,1,0,1,2,1,3,1,0,1,2,2,0,1,0,1,2,3,1,1,0,2,1,0,2,1,0,2,1,1,3,1,0,2,1,2,0,1,0,2,1,3,1,1,0,3,0,0,2,1,0,3,0,1,3,1,0,3,0,2,0,1,0,3,0,3,1,2,3,0,3,0,2,2,3,0,3,1,3,2,3,0,3,2,0,2,3,0,3,3,1,2,3,1,2,0,2,2,3,1,2,1,3,2,3,1,2,2,0,2,3,1,2,3,1,2,3,2,1,0,2,2,3,2,1,1,3,2,3,2,1,2,0,2,3,2,1,3,1,2,3,3,0,0,2,2,3,3,0,1,3,2,3,3,0,2,0,2,3,3,0,3,1,3,2,0,3,0,2,3,2,0,3,1,3,3,2,0,3,2,0,3,2,0,3,3,1,3,2,1,2,0,2,3,2,1,2,1,3,3,2,1,2,2,0,3,2,1,2,3,1,3,2,2,1,0,2,3,2,2,1,1,3,3,2,2,1,2,0,3,2,2,1,3,1,3,2,3,0,0,2,3,2,3,0,1,3,3,2,3,0,2,0,3,2,3,0,3,1}; float GK_NTR_values[64] = {1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1}; short int GK_RTN_indices[64][6] = {0,3,0,1,0,2,0,3,0,1,1,3,0,3,0,1,2,0,0,3,0,1,3,1,0,3,1,0,0,2,0,3,1,0,1,3,0,3,1,0,2,0,0,3,1,0,3,1,0,3,2,3,0,2,0,3,2,3,1,3,0,3,2,3,2,0,0,3,2,3,3,1,0,3,3,2,0,2,0,3,3,2,1,3,0,3,3,2,2,0,0,3,3,2,3,1,1,2,0,1,0,2,1,2,0,1,1,3,1,2,0,1,2,0,1,2,0,1,3,1,1,2,1,0,0,2,1,2,1,0,1,3,1,2,1,0,2,0,1,2,1,0,3,1,1,2,2,3,0,2,1,2,2,3,1,3,1,2,2,3,2,0,1,2,2,3,3,1,1,2,3,2,0,2,1,2,3,2,1,3,1,2,3,2,2,0,1,2,3,2,3,1,2,1,0,1,0,2,2,1,0,1,1,3,2,1,0,1,2,0,2,1,0,1,3,1,2,1,1,0,0,2,2,1,1,0,1,3,2,1,1,0,2,0,2,1,1,0,3,1,2,1,2,3,0,2,2,1,2,3,1,3,2,1,2,3,2,0,2,1,2,3,3,1,2,1,3,2,0,2,2,1,3,2,1,3,2,1,3,2,2,0,2,1,3,2,3,1,3,0,0,1,0,2,3,0,0,1,1,3,3,0,0,1,2,0,3,0,0,1,3,1,3,0,1,0,0,2,3,0,1,0,1,3,3,0,1,0,2,0,3,0,1,0,3,1,3,0,2,3,0,2,3,0,2,3,1,3,3,0,2,3,2,0,3,0,2,3,3,1,3,0,3,2,0,2,3,0,3,2,1,3,3,0,3,2,2,0,3,0,3,2,3,1}; float GK_RTN_values[64] = {-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1}; short int GK_RTR_indices[256][8] = {0,3,0,3,0,2,0,2,0,3,0,3,0,2,1,3,0,3,0,3,0,2,2,0,0,3,0,3,0,2,3,1,0,3,0,3,1,3,0,2,0,3,0,3,1,3,1,3,0,3,0,3,1,3,2,0,0,3,0,3,1,3,3,1,0,3,0,3,2,0,0,2,0,3,0,3,2,0,1,3,0,3,0,3,2,0,2,0,0,3,0,3,2,0,3,1,0,3,0,3,3,1,0,2,0,3,0,3,3,1,1,3,0,3,0,3,3,1,2,0,0,3,0,3,3,1,3,1,0,3,1,2,0,2,0,2,0,3,1,2,0,2,1,3,0,3,1,2,0,2,2,0,0,3,1,2,0,2,3,1,0,3,1,2,1,3,0,2,0,3,1,2,1,3,1,3,0,3,1,2,1,3,2,0,0,3,1,2,1,3,3,1,0,3,1,2,2,0,0,2,0,3,1,2,2,0,1,3,0,3,1,2,2,0,2,0,0,3,1,2,2,0,3,1,0,3,1,2,3,1,0,2,0,3,1,2,3,1,1,3,0,3,1,2,3,1,2,0,0,3,1,2,3,1,3,1,0,3,2,1,0,2,0,2,0,3,2,1,0,2,1,3,0,3,2,1,0,2,2,0,0,3,2,1,0,2,3,1,0,3,2,1,1,3,0,2,0,3,2,1,1,3,1,3,0,3,2,1,1,3,2,0,0,3,2,1,1,3,3,1,0,3,2,1,2,0,0,2,0,3,2,1,2,0,1,3,0,3,2,1,2,0,2,0,0,3,2,1,2,0,3,1,0,3,2,1,3,1,0,2,0,3,2,1,3,1,1,3,0,3,2,1,3,1,2,0,0,3,2,1,3,1,3,1,0,3,3,0,0,2,0,2,0,3,3,0,0,2,1,3,0,3,3,0,0,2,2,0,0,3,3,0,0,2,3,1,0,3,3,0,1,3,0,2,0,3,3,0,1,3,1,3,0,3,3,0,1,3,2,0,0,3,3,0,1,3,3,1,0,3,3,0,2,0,0,2,0,3,3,0,2,0,1,3,0,3,3,0,2,0,2,0,0,3,3,0,2,0,3,1,0,3,3,0,3,1,0,2,0,3,3,0,3,1,1,3,0,3,3,0,3,1,2,0,0,3,3,0,3,1,3,1,1,2,0,3,0,2,0,2,1,2,0,3,0,2,1,3,1,2,0,3,0,2,2,0,1,2,0,3,0,2,3,1,1,2,0,3,1,3,0,2,1,2,0,3,1,3,1,3,1,2,0,3,1,3,2,0,1,2,0,3,1,3,3,1,1,2,0,3,2,0,0,2,1,2,0,3,2,0,1,3,1,2,0,3,2,0,2,0,1,2,0,3,2,0,3,1,1,2,0,3,3,1,0,2,1,2,0,3,3,1,1,3,1,2,0,3,3,1,2,0,1,2,0,3,3,1,3,1,1,2,1,2,0,2,0,2,1,2,1,2,0,2,1,3,1,2,1,2,0,2,2,0,1,2,1,2,0,2,3,1,1,2,1,2,1,3,0,2,1,2,1,2,1,3,1,3,1,2,1,2,1,3,2,0,1,2,1,2,1,3,3,1,1,2,1,2,2,0,0,2,1,2,1,2,2,0,1,3,1,2,1,2,2,0,2,0,1,2,1,2,2,0,3,1,1,2,1,2,3,1,0,2,1,2,1,2,3,1,1,3,1,2,1,2,3,1,2,0,1,2,1,2,3,1,3,1,1,2,2,1,0,2,0,2,1,2,2,1,0,2,1,3,1,2,2,1,0,2,2,0,1,2,2,1,0,2,3,1,1,2,2,1,1,3,0,2,1,2,2,1,1,3,1,3,1,2,2,1,1,3,2,0,1,2,2,1,1,3,3,1,1,2,2,1,2,0,0,2,1,2,2,1,2,0,1,3,1,2,2,1,2,0,2,0,1,2,2,1,2,0,3,1,1,2,2,1,3,1,0,2,1,2,2,1,3,1,1,3,1,2,2,1,3,1,2,0,1,2,2,1,3,1,3,1,1,2,3,0,0,2,0,2,1,2,3,0,0,2,1,3,1,2,3,0,0,2,2,0,1,2,3,0,0,2,3,1,1,2,3,0,1,3,0,2,1,2,3,0,1,3,1,3,1,2,3,0,1,3,2,0,1,2,3,0,1,3,3,1,1,2,3,0,2,0,0,2,1,2,3,0,2,0,1,3,1,2,3,0,2,0,2,0,1,2,3,0,2,0,3,1,1,2,3,0,3,1,0,2,1,2,3,0,3,1,1,3,1,2,3,0,3,1,2,0,1,2,3,0,3,1,3,1,2,1,0,3,0,2,0,2,2,1,0,3,0,2,1,3,2,1,0,3,0,2,2,0,2,1,0,3,0,2,3,1,2,1,0,3,1,3,0,2,2,1,0,3,1,3,1,3,2,1,0,3,1,3,2,0,2,1,0,3,1,3,3,1,2,1,0,3,2,0,0,2,2,1,0,3,2,0,1,3,2,1,0,3,2,0,2,0,2,1,0,3,2,0,3,1,2,1,0,3,3,1,0,2,2,1,0,3,3,1,1,3,2,1,0,3,3,1,2,0,2,1,0,3,3,1,3,1,2,1,1,2,0,2,0,2,2,1,1,2,0,2,1,3,2,1,1,2,0,2,2,0,2,1,1,2,0,2,3,1,2,1,1,2,1,3,0,2,2,1,1,2,1,3,1,3,2,1,1,2,1,3,2,0,2,1,1,2,1,3,3,1,2,1,1,2,2,0,0,2,2,1,1,2,2,0,1,3,2,1,1,2,2,0,2,0,2,1,1,2,2,0,3,1,2,1,1,2,3,1,0,2,2,1,1,2,3,1,1,3,2,1,1,2,3,1,2,0,2,1,1,2,3,1,3,1,2,1,2,1,0,2,0,2,2,1,2,1,0,2,1,3,2,1,2,1,0,2,2,0,2,1,2,1,0,2,3,1,2,1,2,1,1,3,0,2,2,1,2,1,1,3,1,3,2,1,2,1,1,3,2,0,2,1,2,1,1,3,3,1,2,1,2,1,2,0,0,2,2,1,2,1,2,0,1,3,2,1,2,1,2,0,2,0,2,1,2,1,2,0,3,1,2,1,2,1,3,1,0,2,2,1,2,1,3,1,1,3,2,1,2,1,3,1,2,0,2,1,2,1,3,1,3,1,2,1,3,0,0,2,0,2,2,1,3,0,0,2,1,3,2,1,3,0,0,2,2,0,2,1,3,0,0,2,3,1,2,1,3,0,1,3,0,2,2,1,3,0,1,3,1,3,2,1,3,0,1,3,2,0,2,1,3,0,1,3,3,1,2,1,3,0,2,0,0,2,2,1,3,0,2,0,1,3,2,1,3,0,2,0,2,0,2,1,3,0,2,0,3,1,2,1,3,0,3,1,0,2,2,1,3,0,3,1,1,3,2,1,3,0,3,1,2,0,2,1,3,0,3,1,3,1,3,0,0,3,0,2,0,2,3,0,0,3,0,2,1,3,3,0,0,3,0,2,2,0,3,0,0,3,0,2,3,1,3,0,0,3,1,3,0,2,3,0,0,3,1,3,1,3,3,0,0,3,1,3,2,0,3,0,0,3,1,3,3,1,3,0,0,3,2,0,0,2,3,0,0,3,2,0,1,3,3,0,0,3,2,0,2,0,3,0,0,3,2,0,3,1,3,0,0,3,3,1,0,2,3,0,0,3,3,1,1,3,3,0,0,3,3,1,2,0,3,0,0,3,3,1,3,1,3,0,1,2,0,2,0,2,3,0,1,2,0,2,1,3,3,0,1,2,0,2,2,0,3,0,1,2,0,2,3,1,3,0,1,2,1,3,0,2,3,0,1,2,1,3,1,3,3,0,1,2,1,3,2,0,3,0,1,2,1,3,3,1,3,0,1,2,2,0,0,2,3,0,1,2,2,0,1,3,3,0,1,2,2,0,2,0,3,0,1,2,2,0,3,1,3,0,1,2,3,1,0,2,3,0,1,2,3,1,1,3,3,0,1,2,3,1,2,0,3,0,1,2,3,1,3,1,3,0,2,1,0,2,0,2,3,0,2,1,0,2,1,3,3,0,2,1,0,2,2,0,3,0,2,1,0,2,3,1,3,0,2,1,1,3,0,2,3,0,2,1,1,3,1,3,3,0,2,1,1,3,2,0,3,0,2,1,1,3,3,1,3,0,2,1,2,0,0,2,3,0,2,1,2,0,1,3,3,0,2,1,2,0,2,0,3,0,2,1,2,0,3,1,3,0,2,1,3,1,0,2,3,0,2,1,3,1,1,3,3,0,2,1,3,1,2,0,3,0,2,1,3,1,3,1,3,0,3,0,0,2,0,2,3,0,3,0,0,2,1,3,3,0,3,0,0,2,2,0,3,0,3,0,0,2,3,1,3,0,3,0,1,3,0,2,3,0,3,0,1,3,1,3,3,0,3,0,1,3,2,0,3,0,3,0,1,3,3,1,3,0,3,0,2,0,0,2,3,0,3,0,2,0,1,3,3,0,3,0,2,0,2,0,3,0,3,0,2,0,3,1,3,0,3,0,3,1,0,2,3,0,3,0,3,1,1,3,3,0,3,0,3,1,2,0,3,0,3,0,3,1,3,1}; float GK_RTR_values[256] = {1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1}; short int GK_Delta_indices[3][16][4] = {0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,0,0,0,0,0,1,1,0,0,2,2,0,0,3,3,1,1,0,0,1,1,1,1,1,1,2,2,1,1,3,3,2,2,0,0,2,2,1,1,2,2,2,2,2,2,3,3,3,3,0,0,3,3,1,1,3,3,2,2,3,3,3,3,0,1,0,1,0,1,1,0,0,1,2,3,0,1,3,2,1,0,0,1,1,0,1,0,1,0,2,3,1,0,3,2,2,3,0,1,2,3,1,0,2,3,2,3,2,3,3,2,3,2,0,1,3,2,1,0,3,2,2,3,3,2,3,2}; float GK_Delta_values[3][16] = {1,-1,-1,1,-1,1,1,-1,-1,1,1,-1,1,-1,-1,1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1,1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1}; // for mpi use global variables MPI_Group GK_fullGroup , GK_spaceGroup , GK_timeGroup; MPI_Comm GK_spaceComm , GK_timeComm; int GK_localRank; int GK_localSize; int GK_timeRank; int GK_timeSize; ////////////////////////////////////////////////// static void createMomenta(int Q_sq){ int counter=0; for(int iQ = 0 ; iQ <= Q_sq ; iQ++){ for(int nx = iQ ; nx >= -iQ ; nx--) for(int ny = iQ ; ny >= -iQ ; ny--) for(int nz = iQ ; nz >= -iQ ; nz--){ if( nx*nx + ny*ny + nz*nz == iQ ){ GK_moms[counter][0] = nx; GK_moms[counter][1] = ny; GK_moms[counter][2] = nz; counter++; } } } if(counter > MAX_NMOMENTA)errorQuda("Error exceeded max number of momenta\n"); GK_Nmoms=counter; } void quda::init_qudaQKXTM_Kepler(qudaQKXTMinfo_Kepler *info){ if(GK_init_qudaQKXTM_Kepler_flag == false){ GK_nColor = 3; GK_nSpin = 4; GK_nDim = QUDAQKXTM_DIM; GK_alphaAPE = info->alphaAPE; GK_alphaGauss = info->alphaGauss; GK_nsmearAPE = info->nsmearAPE; GK_nsmearGauss = info->nsmearGauss; createMomenta(info->Q_sq); // from now on depends on lattice and break format we choose for(int i = 0 ; i < GK_nDim ; i++) GK_nProc[i] = comm_dim(i); for(int i = 0 ; i < GK_nDim ; i++){ // take local and total lattice GK_localL[i] = info->lL[i]; GK_totalL[i] = GK_nProc[i] * GK_localL[i]; } GK_localVolume = 1; GK_totalVolume = 1; for(int i = 0 ; i < GK_nDim ; i++){ GK_localVolume *= GK_localL[i]; GK_totalVolume *= GK_totalL[i]; } GK_strideFull = GK_localVolume; for (int i=0; i<GK_nDim; i++) { GK_surface3D[i] = 1; for (int j=0; j<GK_nDim; j++) { if (i==j) continue; GK_surface3D[i] *= GK_localL[j]; } } for(int i = 0 ; i < GK_nDim ; i++) if( GK_localL[i] == GK_totalL[i] ) GK_surface3D[i] = 0; for(int i = 0 ; i < GK_nDim ; i++){ GK_plusGhost[i] =0; GK_minusGhost[i] = 0; } #ifdef MULTI_GPU int lastIndex = GK_localVolume; for(int i = 0 ; i < GK_nDim ; i++) if( GK_localL[i] < GK_totalL[i] ){ GK_plusGhost[i] = lastIndex ; GK_minusGhost[i] = lastIndex + GK_surface3D[i]; lastIndex += 2*GK_surface3D[i]; } #endif for(int i = 0 ; i < GK_nDim ; i++){ if( GK_localL[i] < GK_totalL[i]) GK_dimBreak[i] = true; else GK_dimBreak[i] = false; } const int eps[6][3]= { {0,1,2}, {2,0,1}, {1,2,0}, {2,1,0}, {0,2,1}, {1,0,2} }; const int sgn_eps[6]= { +1,+1,+1,-1,-1,-1 }; int procPosition[4]; for(int i= 0 ; i < 4 ; i++) procPosition[i] = comm_coords(default_topo)[i]; // put it zero but change it later GK_Nsources = info->Nsources; if(GK_Nsources > MAX_NSOURCES) errorQuda("Error you exceeded maximum number of source position\n"); for(int is = 0 ; is < GK_Nsources ; is++) for(int i = 0 ; i < 4 ; i++) GK_sourcePosition[is][i] = info->sourcePosition[is][i]; // initialization consist also from define device constants cudaMemcpyToSymbol(c_nColor, &GK_nColor, sizeof(int) ); cudaMemcpyToSymbol(c_nSpin, &GK_nSpin, sizeof(int) ); cudaMemcpyToSymbol(c_nDim, &GK_nDim, sizeof(int) ); cudaMemcpyToSymbol(c_stride, &GK_strideFull, sizeof(int) ); cudaMemcpyToSymbol(c_alphaAPE, &GK_alphaAPE , sizeof(double) ); cudaMemcpyToSymbol(c_alphaGauss, &GK_alphaGauss , sizeof(double) ); cudaMemcpyToSymbol(c_threads , &GK_localVolume , sizeof(double) ); // may change cudaMemcpyToSymbol(c_dimBreak , GK_dimBreak , QUDAQKXTM_DIM*sizeof(bool) ); cudaMemcpyToSymbol(c_localL , GK_localL , QUDAQKXTM_DIM*sizeof(int) ); cudaMemcpyToSymbol(c_totalL , GK_totalL , QUDAQKXTM_DIM*sizeof(int) ); cudaMemcpyToSymbol(c_plusGhost , GK_plusGhost , QUDAQKXTM_DIM*sizeof(int) ); cudaMemcpyToSymbol(c_minusGhost , GK_minusGhost , QUDAQKXTM_DIM*sizeof(int) ); cudaMemcpyToSymbol(c_surface , GK_surface3D , QUDAQKXTM_DIM*sizeof(int) ); cudaMemcpyToSymbol(c_eps, &(eps[0][0]) , 6*3*sizeof(int) ); cudaMemcpyToSymbol(c_sgn_eps, sgn_eps , 6*sizeof(int) ); cudaMemcpyToSymbol(c_procPosition, procPosition, QUDAQKXTM_DIM*sizeof(int)); cudaMemcpyToSymbol(c_Nmoms, &GK_Nmoms, sizeof(int)); cudaMemcpyToSymbol(c_moms, GK_moms, MAX_NMOMENTA*3*sizeof(short int)); cudaMemcpyToSymbol(c_mesons_indices,GK_mesons_indices,10*16*4*sizeof(short int)); cudaMemcpyToSymbol(c_NTN_indices,GK_NTN_indices,16*4*sizeof(short int)); cudaMemcpyToSymbol(c_NTR_indices,GK_NTR_indices,64*6*sizeof(short int)); cudaMemcpyToSymbol(c_RTN_indices,GK_RTN_indices,64*6*sizeof(short int)); cudaMemcpyToSymbol(c_RTR_indices,GK_RTR_indices,256*8*sizeof(short int)); cudaMemcpyToSymbol(c_Delta_indices,GK_Delta_indices,3*16*4*sizeof(short int)); cudaMemcpyToSymbol(c_mesons_values,GK_mesons_values,10*16*sizeof(float)); cudaMemcpyToSymbol(c_NTN_values,GK_NTN_values,16*sizeof(float)); cudaMemcpyToSymbol(c_NTR_values,GK_NTR_values,64*sizeof(float)); cudaMemcpyToSymbol(c_RTN_values,GK_RTN_values,64*sizeof(float)); cudaMemcpyToSymbol(c_RTR_values,GK_RTR_values,256*sizeof(float)); cudaMemcpyToSymbol(c_Delta_values,GK_Delta_values,3*16*sizeof(float)); checkCudaError(); // create groups of process to use mpi reduce only on spatial points MPI_Comm_group(MPI_COMM_WORLD, &GK_fullGroup); int space3D_proc; space3D_proc = GK_nProc[0] * GK_nProc[1] * GK_nProc[2]; int *ranks = (int*) malloc(space3D_proc*sizeof(int)); for(int i= 0 ; i < space3D_proc ; i++) ranks[i] = comm_coords(default_topo)[3] + GK_nProc[3]*i; // for(int i= 0 ; i < space3D_proc ; i++) // printf("%d (%d,%d,%d,%d)\n",comm_rank(),comm_coords(default_topo)[0],comm_coords(default_topo)[1],comm_coords(default_topo)[2],comm_coords(default_topo)[3]); // for(int i= 0 ; i < space3D_proc ; i++) //printf("%d %d\n",comm_rank(),ranks[i]); MPI_Group_incl(GK_fullGroup,space3D_proc,ranks,&GK_spaceGroup); MPI_Group_rank(GK_spaceGroup,&GK_localRank); MPI_Group_size(GK_spaceGroup,&GK_localSize); MPI_Comm_create(MPI_COMM_WORLD, GK_spaceGroup , &GK_spaceComm); //if(GK_spaceComm == MPI_COMM_NULL) printf("NULL %d\n",comm_rank()); //exit(-1); // create group of process to use mpi gather int *ranksTime = (int*) malloc(GK_nProc[3]*sizeof(int)); for(int i=0 ; i < GK_nProc[3] ; i++) ranksTime[i] = i; MPI_Group_incl(GK_fullGroup,GK_nProc[3], ranksTime, &GK_timeGroup); MPI_Group_rank(GK_timeGroup, &GK_timeRank); MPI_Group_size(GK_timeGroup, &GK_timeSize); MPI_Comm_create(MPI_COMM_WORLD, GK_timeGroup, &GK_timeComm); ////////////////////////////////////////////////////////////////////////////// free(ranks); free(ranksTime); GK_init_qudaQKXTM_Kepler_flag = true; printfQuda("qudaQKXTM_Kepler has been initialized\n"); } else return; } void quda::printf_qudaQKXTM_Kepler(){ if(GK_init_qudaQKXTM_Kepler_flag == false) errorQuda("You must initialize init_qudaQKXTM_Kepler first"); printfQuda("Number of colors is %d\n",GK_nColor); printfQuda("Number of spins is %d\n",GK_nSpin); printfQuda("Number of dimensions is %d\n",GK_nDim); printfQuda("Number of process in each direction is (x,y,z,t) %d x %d x %d x %d\n",GK_nProc[0],GK_nProc[1],GK_nProc[2],GK_nProc[3]); printfQuda("Total lattice is (x,y,z,t) %d x %d x %d x %d\n",GK_totalL[0],GK_totalL[1],GK_totalL[2],GK_totalL[3]); printfQuda("Local lattice is (x,y,z,t) %d x %d x %d x %d\n",GK_localL[0],GK_localL[1],GK_localL[2],GK_localL[3]); printfQuda("Total volume is %d\n",GK_totalVolume); printfQuda("Local volume is %d\n",GK_localVolume); printfQuda("Surface is (x,y,z,t) ( %d , %d , %d , %d)\n",GK_surface3D[0],GK_surface3D[1],GK_surface3D[2],GK_surface3D[3]); printfQuda("The plus Ghost points in directions (x,y,z,t) ( %d , %d , %d , %d )\n",GK_plusGhost[0],GK_plusGhost[1],GK_plusGhost[2],GK_plusGhost[3]); printfQuda("The Minus Ghost points in directixons (x,y,z,t) ( %d , %d , %d , %d )\n",GK_minusGhost[0],GK_minusGhost[1],GK_minusGhost[2],GK_minusGhost[3]); printfQuda("For APE smearing we use nsmear = %d , alpha = %lf\n",GK_nsmearAPE,GK_alphaAPE); printfQuda("For Gauss smearing we use nsmear = %d , alpha = %lf\n",GK_nsmearGauss,GK_alphaGauss); printfQuda("I got %d source positions to work on\n",GK_Nsources); printfQuda("I got %d number of momenta to work on\n",GK_Nmoms); } static __inline__ __device__ double2 fetch_double2(cudaTextureObject_t t, int i) { int4 v =tex1Dfetch<int4>(t,i); return make_double2(__hiloint2double(v.y, v.x), __hiloint2double(v.w, v.z)); } static __inline__ __device__ float2 fetch_float2(cudaTextureObject_t t, int i) { float2 v = tex1Dfetch<float2>(t,i); return v; } template<typename Float2> __device__ inline Float2 operator*(const Float2 a, const Float2 b){ Float2 res; res.x = a.x*b.x - a.y*b.y; res.y = a.x*b.y + a.y*b.x; return res; } /* template<typename Float2, typename Float> __device__ inline Float2 operator*(const Float a , const Float2 b){ Float2 res; res.x = a*b.x; res.y = a*b.y; return res; } */ __device__ inline float2 operator*(const float a , const float2 b){ float2 res; res.x = a*b.x; res.y = a*b.y; return res; } __device__ inline double2 operator*(const double a , const double2 b){ double2 res; res.x = a*b.x; res.y = a*b.y; return res; } template<typename Float2> __device__ inline Float2 operator*(const int a , const Float2 b){ Float2 res; res.x = a*b.x; res.y = a*b.y; return res; } template<typename Float2> __device__ inline Float2 operator+(const Float2 a, const Float2 b){ Float2 res; res.x = a.x + b.x; res.y = a.y + b.y; return res; } template<typename Float2> __device__ inline Float2 operator-(const Float2 a, const Float2 b){ Float2 res; res.x = a.x - b.x; res.y = a.y - b.y; return res; } template<typename Float2> __device__ inline Float2 conj(const Float2 a){ Float2 res; res.x = a.x; res.y = -a.y; return res; } __device__ inline float norm(const float2 a){ float res; res = sqrt(a.x*a.x + a.y*a.y); return res; } __device__ inline double norm(const double2 a){ double res; res = sqrt(a.x*a.x + a.y*a.y); return res; } template<typename Float2> __device__ inline Float2 get_Projector(Float2 projector[4][4], WHICHPARTICLE PARTICLE, WHICHPROJECTOR PID){ // important Projectors must be in twisted basis #include <projectors_tm_base.h> } template<typename Float2> __device__ inline Float2 get_Operator(Float2 gamma[4][4], int flag, WHICHPARTICLE TESTPARTICLE, int partFlag){ #include <gammas_tm_base.h> } #include <core_def_Kepler.h> __global__ void calculatePlaq_kernel_double(cudaTextureObject_t gaugeTexPlaq,double *partial_plaq){ #define FLOAT2 double2 #define FLOAT double #define READGAUGE_FLOAT READGAUGE_double #include <plaquette_core_Kepler.h> #undef FLOAT2 #undef FLOAT #undef READGAUGE_FLOAT } __global__ void calculatePlaq_kernel_float(cudaTextureObject_t gaugeTexPlaq,float *partial_plaq){ #define FLOAT2 float2 #define FLOAT float #define READGAUGE_FLOAT READGAUGE_float #include <plaquette_core_Kepler.h> #undef READGAUGE_FLOAT #undef FLOAT2 #undef FLOAT } __global__ void gaussianSmearing_kernel_float(float2* out,cudaTextureObject_t vecInTex,cudaTextureObject_t gaugeTex ){ #define FLOAT2 float2 #define READGAUGE_FLOAT READGAUGE_float #define READVECTOR_FLOAT READVECTOR_float #include <Gauss_core_Kepler.h> #undef READGAUGE_FLOAT #undef READVECTOR_FLOAT #undef FLOAT2 } __global__ void gaussianSmearing_kernel_double(double2* out,cudaTextureObject_t vecInTex,cudaTextureObject_t gaugeTex ){ #define FLOAT2 double2 #define READGAUGE_FLOAT READGAUGE_double #define READVECTOR_FLOAT READVECTOR_double #include <Gauss_core_Kepler.h> #undef READGAUGE_FLOAT #undef READVECTOR_FLOAT #undef FLOAT2 } __global__ void contractMesons_kernel_float(float2* block, cudaTextureObject_t prop1Tex, cudaTextureObject_t prop2Tex,int it, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <contractMesons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void contractMesons_kernel_double(double2* block, cudaTextureObject_t prop1Tex, cudaTextureObject_t prop2Tex,int it, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <contractMesons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void contractBaryons_kernel_float(float2* block, cudaTextureObject_t prop1Tex, cudaTextureObject_t prop2Tex,int it, int x0, int y0, int z0, int ip){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <contractBaryons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } /* __global__ void contractBaryons_kernel_double(double2* block, cudaTextureObject_t prop1Tex, cudaTextureObject_t prop2Tex,int it, int x0, int y0, int z0, int ip){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <contractBaryons_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } */ __global__ void seqSourceFixSinkPart1_kernel_float(float2* out, int timeslice, cudaTextureObject_t tex1, cudaTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <seqSourceFixSinkPart1_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void seqSourceFixSinkPart2_kernel_float(float2* out, int timeslice, cudaTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <seqSourceFixSinkPart2_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void seqSourceFixSinkPart1_kernel_double(double2* out, int timeslice, cudaTextureObject_t tex1, cudaTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <seqSourceFixSinkPart1_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void seqSourceFixSinkPart2_kernel_double(double2* out, int timeslice, cudaTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <seqSourceFixSinkPart2_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_local_kernel_float(float2* block, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <fixSinkContractions_local_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_local_kernel_double(double2* block, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <fixSinkContractions_local_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_noether_kernel_float(float2* block, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, cudaTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <fixSinkContractions_noether_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_noether_kernel_double(double2* block, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, cudaTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <fixSinkContractions_noether_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_oneD_kernel_float(float2* block, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, cudaTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int dir, int x0, int y0, int z0){ #define FLOAT2 float2 #define FLOAT float #define FETCH_FLOAT2 fetch_float2 #include <fixSinkContractions_oneD_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } __global__ void fixSinkContractions_oneD_kernel_double(double2* block, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, cudaTextureObject_t gaugeTex, WHICHPARTICLE TESTPARTICLE, int partflag, int it, int dir, int x0, int y0, int z0){ #define FLOAT2 double2 #define FLOAT double #define FETCH_FLOAT2 fetch_double2 #include <fixSinkContractions_oneD_core_Kepler.h> #undef FETCH_FLOAT2 #undef FLOAT2 #undef FLOAT } template<typename Float, typename Float2> __global__ void scaleVector_kernel(Float a, Float2* inOut){ #include <scaleVector_core_Kepler.h> } template<typename Float2> __global__ void uploadToCuda_kernel(Float2 *in, double2 *outEven, double2 *outOdd){ #include <uploadToCuda_core_Kepler.h> } template<typename Float2> __global__ void downloadFromCuda_kernel(Float2 *out, double2 *inEven, double2 *inOdd){ #include <downloadFromCuda_core_Kepler.h> } template<typename Float2> __global__ void rotateToPhysicalBase_kernel(Float2 *inOut, int sign){ #include <rotateToPhysicalBase_core_Kepler.h> } __global__ void castDoubleToFloat_kernel(float2 *out, double2 *in){ #include <castDoubleToFloat_core_Kepler.h> } __global__ void castFloatToDouble_kernel(double2 *out, float2 *in){ #include <castFloatToDouble_core_Kepler.h> } template<typename Float2> __global__ void conjugate_vector_kernel(Float2 *inOut){ #include <conjugate_vector_core_Kepler.h> } template<typename Float2> __global__ void apply_gamma5_vector_kernel(Float2 *inOut){ #include <apply_gamma5_vector_core_Kepler.h> } template<typename Float2> __global__ void conjugate_propagator_kernel(Float2 *inOut){ #include <conjugate_propagator_core_Kepler.h> } template<typename Float2> __global__ void apply_gamma5_propagator_kernel(Float2 *inOut){ #include <apply_gamma5_propagator_core_Kepler.h> } template<typename Float> static Float calculatePlaq_kernel(cudaTextureObject_t gaugeTexPlaq){ Float plaquette = 0.; Float globalPlaquette = 0.; dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); Float *h_partial_plaq = NULL; Float *d_partial_plaq = NULL; h_partial_plaq = (Float*) malloc(gridDim.x * sizeof(Float) ); if(h_partial_plaq == NULL) errorQuda("Error allocate memory for host partial plaq"); cudaMalloc((void**)&d_partial_plaq, gridDim.x * sizeof(Float)); #ifdef TIMING_REPORT cudaEvent_t start,stop; float elapsedTime; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start,0); #endif if( typeid(Float) == typeid(float) ) calculatePlaq_kernel_float<<<gridDim,blockDim>>>(gaugeTexPlaq,(float*) d_partial_plaq); else if(typeid(Float) == typeid(double)) calculatePlaq_kernel_double<<<gridDim,blockDim>>>(gaugeTexPlaq,(double*) d_partial_plaq); #ifdef TIMING_REPORT cudaEventRecord(stop,0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsedTime,start,stop); cudaEventDestroy(start); cudaEventDestroy(stop); printfQuda("Elapsed time for plaquette kernel is %f ms\n",elapsedTime); #endif cudaMemcpy(h_partial_plaq, d_partial_plaq , gridDim.x * sizeof(Float) , cudaMemcpyDeviceToHost); for(int i = 0 ; i < gridDim.x ; i++) plaquette += h_partial_plaq[i]; free(h_partial_plaq); cudaFree(d_partial_plaq); checkCudaError(); int rc; if(typeid(Float) == typeid(double)) rc = MPI_Allreduce(&plaquette , &globalPlaquette , 1 , MPI_DOUBLE , MPI_SUM , MPI_COMM_WORLD); else if( typeid(Float) == typeid(float) ) rc = MPI_Allreduce(&plaquette , &globalPlaquette , 1 , MPI_FLOAT , MPI_SUM , MPI_COMM_WORLD); if( rc != MPI_SUCCESS ) errorQuda("Error in MPI reduction for plaquette"); return globalPlaquette/(GK_totalVolume*GK_nColor*6); } void quda::run_calculatePlaq_kernel(cudaTextureObject_t gaugeTexPlaq, int precision){ if(precision == 4){ float plaq = calculatePlaq_kernel<float>(gaugeTexPlaq); printfQuda("Calculated plaquette in single precision is %f\n",plaq); } else if(precision == 8){ double plaq = calculatePlaq_kernel<double>(gaugeTexPlaq); printfQuda("Calculated plaquette in double precision is %lf\n",plaq); } else{ errorQuda("Precision not supported\n"); } } template<typename Float> static void gaussianSmearing_kernel(void* out,cudaTextureObject_t vecInTex, cudaTextureObject_t gaugeTex){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); #ifdef TIMING_REPORT cudaEvent_t start,stop; float elapsedTime; cudaEventCreate(&start); cudaEventCreate(&stop); cudaEventRecord(start,0); #endif if( typeid(Float) == typeid(float) ) gaussianSmearing_kernel_float<<<gridDim,blockDim>>>((float2*) out, vecInTex, gaugeTex); else if(typeid(Float) == typeid(double)) gaussianSmearing_kernel_double<<<gridDim,blockDim>>>((double2*) out, vecInTex, gaugeTex); checkCudaError(); #ifdef TIMING_REPORT cudaEventRecord(stop,0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsedTime,start,stop); cudaEventDestroy(start); cudaEventDestroy(stop); printfQuda("Elapsed time for 1 step in gaussian smearing is %f ms\n",elapsedTime); #endif } void quda::run_GaussianSmearing(void* out, cudaTextureObject_t vecInTex, cudaTextureObject_t gaugeTex, int precision){ if(precision == 4){ gaussianSmearing_kernel<float>(out,vecInTex,gaugeTex); } else if(precision == 8){ gaussianSmearing_kernel<double>(out,vecInTex,gaugeTex); } else{ errorQuda("Precision not supported\n"); } } void quda::run_UploadToCuda(void* in,cudaColorSpinorField &qudaVec, int precision, bool isEven){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if( qudaVec.SiteSubset() == QUDA_PARITY_SITE_SUBSET ){ if( isEven ){ if(precision == 4){ uploadToCuda_kernel<float2><<<gridDim,blockDim>>>((float2*) in,(double2*) qudaVec.V(), NULL ); } else if(precision == 8){ uploadToCuda_kernel<double2><<<gridDim,blockDim>>>((double2*) in,(double2*) qudaVec.V(), NULL ); } else{ errorQuda("Precision not supported\n"); } } else{ if(precision == 4){ uploadToCuda_kernel<float2><<<gridDim,blockDim>>>((float2*) in, NULL,(double2*) qudaVec.V() ); } else if(precision == 8){ uploadToCuda_kernel<double2><<<gridDim,blockDim>>>((double2*) in, NULL,(double2*) qudaVec.V()); } else{ errorQuda("Precision not supported\n"); } } } else{ if(precision == 4){ uploadToCuda_kernel<float2><<<gridDim,blockDim>>>((float2*) in,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else if(precision == 8){ uploadToCuda_kernel<double2><<<gridDim,blockDim>>>((double2*) in,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else{ errorQuda("Precision not supported\n"); } } checkCudaError(); } void quda::run_DownloadFromCuda(void* out,cudaColorSpinorField &qudaVec, int precision, bool isEven){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if( qudaVec.SiteSubset() == QUDA_PARITY_SITE_SUBSET ){ if( isEven ){ if(precision == 4){ downloadFromCuda_kernel<float2><<<gridDim,blockDim>>>((float2*) out,(double2*) qudaVec.V(), NULL ); } else if(precision == 8){ downloadFromCuda_kernel<double2><<<gridDim,blockDim>>>((double2*) out,(double2*) qudaVec.V(), NULL ); } else{ errorQuda("Precision not supported\n"); } } else{ if(precision == 4){ downloadFromCuda_kernel<float2><<<gridDim,blockDim>>>((float2*) out, NULL,(double2*) qudaVec.V() ); } else if(precision == 8){ downloadFromCuda_kernel<double2><<<gridDim,blockDim>>>((double2*) out, NULL,(double2*) qudaVec.V()); } else{ errorQuda("Precision not supported\n"); } } } else{ if(precision == 4){ downloadFromCuda_kernel<float2><<<gridDim,blockDim>>>((float2*) out,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else if(precision == 8){ downloadFromCuda_kernel<double2><<<gridDim,blockDim>>>((double2*) out,(double2*) qudaVec.Even().V(), (double2*) qudaVec.Odd().V() ); } else{ errorQuda("Precision not supported\n"); } } checkCudaError(); } void quda::run_ScaleVector(double a, void* inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ scaleVector_kernel<float,float2><<<gridDim,blockDim>>>((float) a, (float2*) inOut); } else if(precision == 8){ scaleVector_kernel<double,double2><<<gridDim,blockDim>>>((double) a, (double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } template<typename Float2,typename Float> static void contractMesons_kernel(cudaTextureObject_t texProp1,cudaTextureObject_t texProp2,Float (*corr)[2][10], int it, int isource){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); // spawn threads only for the spatial volume Float *h_partial_block = NULL; Float *d_partial_block = NULL; h_partial_block = (Float*)malloc(GK_Nmoms*2*10*gridDim.x*2*sizeof(Float)); if(h_partial_block == NULL) errorQuda("Error problem with allocation\n"); cudaMalloc((void**)&d_partial_block, GK_Nmoms*2*10*gridDim.x*2 * sizeof(Float) ); checkCudaError(); Float *reduction =(Float*) calloc(GK_Nmoms*2*10*2,sizeof(Float)); if( typeid(Float2) == typeid(float2) ) contractMesons_kernel_float<<<gridDim,blockDim>>>((float2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else contractMesons_kernel_double<<<gridDim,blockDim>>>((double2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); checkCudaError(); cudaMemcpy(h_partial_block , d_partial_block , GK_Nmoms*2*10*gridDim.x*2 * sizeof(Float) , cudaMemcpyDeviceToHost); checkCudaError(); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int ip = 0 ; ip < 10 ; ip++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*2*10*2 + iu*10*2 + ip*2 + 0] += h_partial_block[imom*2*10*gridDim.x*2 + iu*10*gridDim.x*2 + ip*gridDim.x*2 + i*2 + 0]; reduction[imom*2*10*2 + iu*10*2 + ip*2 + 1] += h_partial_block[imom*2*10*gridDim.x*2 + iu*10*gridDim.x*2 + ip*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int ip = 0 ; ip < 10 ; ip++){ corr[it*GK_Nmoms*2 + imom*2 + 0][iu][ip] = reduction[imom*2*10*2 + iu*10*2 + ip*2 + 0]; corr[it*GK_Nmoms*2 + imom*2 + 1][iu][ip] = reduction[imom*2*10*2 + iu*10*2 + ip*2 + 1]; } free(h_partial_block); cudaFree(d_partial_block); checkCudaError(); free(reduction); } void quda::run_contractMesons(cudaTextureObject_t texProp1,cudaTextureObject_t texProp2,void* corr, int it, int isource, int precision){ if(precision == 4){ contractMesons_kernel<float2,float>(texProp1,texProp2,(float(*)[2][10]) corr,it, isource); } else if(precision == 8){ contractMesons_kernel<double2,double>(texProp1,texProp2,(double(*)[2][10]) corr,it, isource); } else{ errorQuda("Precision not supported\n"); } } template<typename Float2,typename Float> static void contractBaryons_kernel(cudaTextureObject_t texProp1,cudaTextureObject_t texProp2,Float (*corr)[2][10][4][4], int it, int isource){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); // spawn threads only for the spatial volume Float *h_partial_block = NULL; Float *d_partial_block = NULL; h_partial_block = (Float*)malloc(GK_Nmoms*2*4*4*gridDim.x*2*sizeof(Float)); if(h_partial_block == NULL) errorQuda("Error problem with allocation\n"); cudaMalloc((void**)&d_partial_block, GK_Nmoms*2*4*4*gridDim.x*2 * sizeof(Float) ); checkCudaError(); Float *reduction =(Float*) calloc(GK_Nmoms*2*4*4*2,sizeof(Float)); for(int ip = 0 ; ip < 10 ; ip++){ if( typeid(Float2) == typeid(float2) ) contractBaryons_kernel_float<<<gridDim,blockDim>>>((float2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2],ip); // else // contractBaryons_kernel_double<<<gridDim,blockDim>>>((double2*) d_partial_block, texProp1, texProp2, it, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2],ip); cudaMemcpy(h_partial_block , d_partial_block , GK_Nmoms*2*4*4*gridDim.x*2 * sizeof(Float) , cudaMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*2*4*4*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int gamma = 0 ; gamma < 4 ; gamma++) for(int gammap = 0 ; gammap < 4 ; gammap++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 0] += h_partial_block[imom*2*4*4*gridDim.x*2 + iu*4*4*gridDim.x*2 + gamma*4*gridDim.x*2 + gammap*gridDim.x*2 + i*2 + 0]; reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 1] += h_partial_block[imom*2*4*4*gridDim.x*2 + iu*4*4*gridDim.x*2 + gamma*4*gridDim.x*2 + gammap*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iu = 0 ; iu < 2 ; iu++) for(int gamma = 0 ; gamma < 4 ; gamma++) for(int gammap = 0 ; gammap < 4 ; gammap++){ corr[it*GK_Nmoms*2 + imom*2 + 0][iu][ip][gamma][gammap] = reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 0]; corr[it*GK_Nmoms*2 + imom*2 + 1][iu][ip][gamma][gammap] = reduction[imom*2*4*4*2 + iu*4*4*2 + gamma*4*2 + gammap*2 + 1]; } } // for over the particles free(h_partial_block); cudaFree(d_partial_block); checkCudaError(); free(reduction); } void quda::run_contractBaryons(cudaTextureObject_t texProp1,cudaTextureObject_t texProp2,void* corr, int it, int isource, int precision){ cudaFuncSetCacheConfig(contractBaryons_kernel_float,cudaFuncCachePreferShared); // cudaFuncSetCacheConfig("contractBaryons_kernel_double",cudaFuncCachePreferShared); checkCudaError(); if(precision == 4){ contractBaryons_kernel<float2,float>(texProp1,texProp2,(float(*)[2][10][4][4]) corr,it, isource); } else if(precision == 8){ //contractBaryons_kernel<double2,double>(texProp1,texProp2,(double(*)[2][10][4][4]) corr,it, isource); errorQuda("For test reasons I do not need it\n"); } else{ errorQuda("Precision not supported\n"); } } void quda::run_rotateToPhysicalBase(void* inOut, int sign, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ rotateToPhysicalBase_kernel<float2><<<gridDim,blockDim>>>((float2*) inOut,sign); } else if(precision == 8){ rotateToPhysicalBase_kernel<double2><<<gridDim,blockDim>>>((double2*) inOut,sign); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_castDoubleToFloat(void *out, void *in){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); castDoubleToFloat_kernel<<<gridDim,blockDim>>>((float2*) out, (double2*) in); checkCudaError(); } void quda::run_castFloatToDouble(void *out, void *in){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); castFloatToDouble_kernel<<<gridDim,blockDim>>>((double2*) out, (float2*) in); checkCudaError(); } void quda::run_conjugate_vector(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ conjugate_vector_kernel<float2><<<gridDim,blockDim>>>((float2*) inOut); } else if(precision == 8){ conjugate_vector_kernel<double2><<<gridDim,blockDim>>>((double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_apply_gamma5_vector(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ apply_gamma5_vector_kernel<float2><<<gridDim,blockDim>>>((float2*) inOut); } else if(precision == 8){ apply_gamma5_vector_kernel<double2><<<gridDim,blockDim>>>((double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_conjugate_propagator(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ conjugate_propagator_kernel<float2><<<gridDim,blockDim>>>((float2*) inOut); } else if(precision == 8){ conjugate_propagator_kernel<double2><<<gridDim,blockDim>>>((double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } void quda::run_apply_gamma5_propagator(void *inOut, int precision){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume + blockDim.x -1)/blockDim.x , 1 , 1); if(precision == 4){ apply_gamma5_propagator_kernel<float2><<<gridDim,blockDim>>>((float2*) inOut); } else if(precision == 8){ apply_gamma5_propagator_kernel<double2><<<gridDim,blockDim>>>((double2*) inOut); } else{ errorQuda("Precision not supported\n"); } checkCudaError(); } template<typename Float> static void seqSourceFixSinkPart1_kernel(void* out, int timeslice, cudaTextureObject_t tex1, cudaTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); if( typeid(Float) == typeid(float) ) seqSourceFixSinkPart1_kernel_float<<<gridDim,blockDim>>>((float2*) out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); else if(typeid(Float) == typeid(double)) seqSourceFixSinkPart1_kernel_double<<<gridDim,blockDim>>>((double2*) out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); checkCudaError(); } template<typename Float> static void seqSourceFixSinkPart2_kernel(void* out, int timeslice, cudaTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE ){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); if( typeid(Float) == typeid(float) ) seqSourceFixSinkPart2_kernel_float<<<gridDim,blockDim>>>((float2*) out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); else if(typeid(Float) == typeid(double)) seqSourceFixSinkPart2_kernel_double<<<gridDim,blockDim>>>((double2*) out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); checkCudaError(); } void quda::run_seqSourceFixSinkPart1(void* out, int timeslice, cudaTextureObject_t tex1, cudaTextureObject_t tex2, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE, int precision){ if(precision == 4){ seqSourceFixSinkPart1_kernel<float>(out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); } else if(precision == 8){ seqSourceFixSinkPart1_kernel<double>(out, timeslice, tex1, tex2, c_nu, c_c2, PID, PARTICLE); } else{ errorQuda("Precision not supported\n"); } } void quda::run_seqSourceFixSinkPart2(void* out, int timeslice, cudaTextureObject_t tex, int c_nu, int c_c2, WHICHPROJECTOR PID, WHICHPARTICLE PARTICLE, int precision){ if(precision == 4){ seqSourceFixSinkPart2_kernel<float>(out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); } else if(precision == 8){ seqSourceFixSinkPart2_kernel<double>(out, timeslice, tex, c_nu, c_c2, PID, PARTICLE); } else{ errorQuda("Precision not supported\n"); } } template<typename Float2,typename Float> static void fixSinkContractions_kernel(void* corrThp_local, void* corrThp_noether, void *corrThp_oneD, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, cudaTextureObject_t gaugeTex, WHICHPARTICLE PARTICLE, int partflag, int itime, int isource){ dim3 blockDim( THREADS_PER_BLOCK , 1, 1); dim3 gridDim( (GK_localVolume/GK_localL[3] + blockDim.x -1)/blockDim.x , 1 , 1); // spawn threads only for the spatial volume Float *h_partial_block = NULL; Float *d_partial_block = NULL; h_partial_block = (Float*)malloc(GK_Nmoms*16*gridDim.x*2*sizeof(Float)); if(h_partial_block == NULL) errorQuda("Error problem with allocation\n"); cudaMalloc((void**)&d_partial_block, GK_Nmoms*16*gridDim.x*2 * sizeof(Float) ); checkCudaError(); Float *reduction =(Float*) calloc(GK_Nmoms*16*2,sizeof(Float)); ///////////////////////////////////////////// ultra local operators /////////////////////// if( typeid(Float2) == typeid(float2) ) fixSinkContractions_local_kernel_float<<<gridDim,blockDim>>>((float2*) d_partial_block, fwdTex, seqTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else if( typeid(Float2) == typeid(double2) ) fixSinkContractions_local_kernel_double<<<gridDim,blockDim>>>((double2*) d_partial_block, fwdTex, seqTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); cudaMemcpy(h_partial_block , d_partial_block , GK_Nmoms*16*gridDim.x*2 * sizeof(Float) , cudaMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*16*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*16*2 + iop*2 + 0] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 0]; reduction[imom*16*2 + iop*2 + 1] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ ((Float*) corrThp_local)[itime*GK_Nmoms*16*2 + imom*16*2 + iop*2 + 0] = reduction[imom*16*2 + iop*2 + 0]; ((Float*) corrThp_local)[itime*GK_Nmoms*16*2 + imom*16*2 + iop*2 + 1] = reduction[imom*16*2 + iop*2 + 1]; } //////////////////////////////////////////////// //////////////////////////// noether conserved current //////// if( typeid(Float2) == typeid(float2) ) fixSinkContractions_noether_kernel_float<<<gridDim,blockDim>>>((float2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else if( typeid(Float2) == typeid(double2) ) fixSinkContractions_noether_kernel_double<<<gridDim,blockDim>>>((double2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); cudaMemcpy(h_partial_block , d_partial_block , GK_Nmoms*4*gridDim.x*2 * sizeof(Float) , cudaMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*4*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int dir = 0 ; dir < 4 ; dir++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*4*2 + dir*2 + 0] += h_partial_block[imom*4*gridDim.x*2 + dir*gridDim.x*2 + i*2 + 0]; reduction[imom*4*2 + dir*2 + 1] += h_partial_block[imom*4*gridDim.x*2 + dir*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int dir = 0 ; dir < 4 ; dir++) for(int i =0 ; i < gridDim.x ; i++){ ((Float*) corrThp_noether)[itime*GK_Nmoms*4*2 + imom*4*2 + dir*2 + 0] = reduction[imom*4*2 + dir*2 + 0]; ((Float*) corrThp_noether)[itime*GK_Nmoms*4*2 + imom*4*2 + dir*2 + 1] = reduction[imom*4*2 + dir*2 + 1]; } ///////////////////////////////////// //////////////////////////// one derivative current //////// // cudaPrintfInit(); for(int dir = 0 ; dir < 4 ; dir++){ if( typeid(Float2) == typeid(float2) ) fixSinkContractions_oneD_kernel_float<<<gridDim,blockDim>>>((float2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, dir, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); else if( typeid(Float2) == typeid(double2) ) fixSinkContractions_oneD_kernel_double<<<gridDim,blockDim>>>((double2*) d_partial_block, fwdTex, seqTex, gaugeTex, PARTICLE, partflag, itime, dir, GK_sourcePosition[isource][0] , GK_sourcePosition[isource][1], GK_sourcePosition[isource][2]); // if(comm_rank() == 0) cudaPrintfDisplay(stdout,true); cudaMemcpy(h_partial_block , d_partial_block , GK_Nmoms*16*gridDim.x*2 * sizeof(Float) , cudaMemcpyDeviceToHost); checkCudaError(); memset(reduction,0,GK_Nmoms*16*2*sizeof(Float)); for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ reduction[imom*16*2 + iop*2 + 0] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 0]; reduction[imom*16*2 + iop*2 + 1] += h_partial_block[imom*16*gridDim.x*2 + iop*gridDim.x*2 + i*2 + 1]; } for(int imom = 0 ; imom < GK_Nmoms ; imom++) for(int iop = 0 ; iop < 16 ; iop++) for(int i =0 ; i < gridDim.x ; i++){ ((Float*) corrThp_oneD)[itime*GK_Nmoms*4*16*2 + imom*4*16*2 + dir*16*2 + iop*2 + 0] = reduction[imom*16*2 + iop*2 + 0]; ((Float*) corrThp_oneD)[itime*GK_Nmoms*4*16*2 + imom*4*16*2 + dir*16*2 + iop*2 + 1] = reduction[imom*16*2 + iop*2 + 1]; } } // cudaPrintfEnd(); ///////////////////////////////////// free(h_partial_block); cudaFree(d_partial_block); checkCudaError(); free(reduction); } void quda::run_fixSinkContractions(void* corrThp_local, void* corrThp_noether, void* corrThp_oneD, cudaTextureObject_t fwdTex, cudaTextureObject_t seqTex, cudaTextureObject_t gaugeTex, WHICHPARTICLE PARTICLE, int partflag, int it, int isource, int precision){ if(precision == 4){ fixSinkContractions_kernel<float2,float>(corrThp_local,corrThp_noether,corrThp_oneD,fwdTex,seqTex,gaugeTex,PARTICLE,partflag, it, isource); } else if(precision == 8){ fixSinkContractions_kernel<double2,double>(corrThp_local,corrThp_noether,corrThp_oneD,fwdTex,seqTex,gaugeTex,PARTICLE,partflag, it, isource); } else{ errorQuda("Precision not supported\n"); } }
487fea38087cc43eb72d192a8245b6d289033cb2.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, const Dtype *weight, Dtype* loss, const int num, const int dim, const int spatial_dim, const bool has_ignore_label_, const int ignore_label_, Dtype* counts) { // num == outer_num_, spatial_dim == inner_num_ CUDA_KERNEL_LOOP(index, nthreads) { const int n = index / spatial_dim; // always 0 here const int s = index % spatial_dim; const int label_value = static_cast<int>(label[n * spatial_dim + s]); if (has_ignore_label_ && label_value == ignore_label_) { loss[index] = 0; counts[index] = 0; } else { const Dtype weight_value = (weight != NULL) ? static_cast<Dtype>(weight[n * spatial_dim + s]) : 1; // loss is always positive, the lower the prob is, the larger the loss is. loss[index] = - weight_value * log(max(prob_data[n * dim + label_value * spatial_dim + s], Dtype(FLT_MIN))); counts[index] = weight_value; } } } 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(); //1102 added bool has_weight = bottom.size() >= 3; const Dtype* weight = NULL; if (has_weight) weight = bottom[2]->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, weight, loss_data, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); Dtype loss; caffe_gpu_asum(nthreads, loss_data, &loss); Dtype valid_count = -1; // Only launch another CUDA kernel if we actually need the count of valid // outputs. // 1102 changed //if (normalization_ == LossParameter_NormalizationMode_VALID && // has_ignore_label_) { if (normalization_ == LossParameter_NormalizationMode_VALID) { caffe_gpu_asum(nthreads, counts, &valid_count); } //LOG(INFO) << "Softmax Forward: valid_count = " << valid_count << ", normalizer = "<< get_normalizer(normalization_, valid_count); top[0]->mutable_cpu_data()[0] = loss / get_normalizer(normalization_, valid_count); if (top.size() >= 2) { top[1]->ShareData(prob_); } if (top.size() >= 3) { // Output per-instance loss caffe_gpu_memcpy(top[2]->count() * sizeof(Dtype), loss_data, top[2]->mutable_gpu_data()); } // Fix a bug, which happens when propagate_down[0] = false in backward caffe_gpu_set(bottom[0]->count(), Dtype(0), bottom[0]->mutable_gpu_diff()); } template <typename Dtype> __global__ void SoftmaxLossBackwardGPU(const int nthreads, const Dtype* top, const Dtype* label, const Dtype *weight, 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]); 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; if (weight != NULL){ const Dtype weight_value = static_cast<Dtype>(weight[n * spatial_dim + s]); for (int k = 0; k < channels; ++k) bottom_diff[n * dim + k * spatial_dim + s] *= weight_value; counts[index] = weight_value; } else 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(); // loss_data: entropy loss of each position 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(); //1102 added bool has_weight = bottom.size() >= 3; const Dtype* weight = NULL; if (has_weight) weight = bottom[2]->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, weight, bottom_diff, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); Dtype valid_count = -1; // Only launch another CUDA kernel if we actually need the count of valid // outputs. // 1102 changed //if (normalization_ == LossParameter_NormalizationMode_VALID && // has_ignore_label_) { if (normalization_ == LossParameter_NormalizationMode_VALID) { caffe_gpu_asum(nthreads, counts, &valid_count); } //LOG(INFO) << "Softmax Backward: valid_count = " << valid_count << ", normalizer = "<< get_normalizer(normalization_, valid_count); const Dtype loss_weight = top[0]->cpu_diff()[0] / get_normalizer(normalization_, valid_count); caffe_gpu_scal(prob_.count(), loss_weight , bottom_diff); } } INSTANTIATE_LAYER_GPU_FUNCS(SoftmaxWithLossLayer); } // namespace caffe
487fea38087cc43eb72d192a8245b6d289033cb2.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, const Dtype *weight, Dtype* loss, const int num, const int dim, const int spatial_dim, const bool has_ignore_label_, const int ignore_label_, Dtype* counts) { // num == outer_num_, spatial_dim == inner_num_ CUDA_KERNEL_LOOP(index, nthreads) { const int n = index / spatial_dim; // always 0 here const int s = index % spatial_dim; const int label_value = static_cast<int>(label[n * spatial_dim + s]); if (has_ignore_label_ && label_value == ignore_label_) { loss[index] = 0; counts[index] = 0; } else { const Dtype weight_value = (weight != NULL) ? static_cast<Dtype>(weight[n * spatial_dim + s]) : 1; // loss is always positive, the lower the prob is, the larger the loss is. loss[index] = - weight_value * log(max(prob_data[n * dim + label_value * spatial_dim + s], Dtype(FLT_MIN))); counts[index] = weight_value; } } } 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(); //1102 added bool has_weight = bottom.size() >= 3; const Dtype* weight = NULL; if (has_weight) weight = bottom[2]->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, weight, loss_data, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); Dtype loss; caffe_gpu_asum(nthreads, loss_data, &loss); Dtype valid_count = -1; // Only launch another CUDA kernel if we actually need the count of valid // outputs. // 1102 changed //if (normalization_ == LossParameter_NormalizationMode_VALID && // has_ignore_label_) { if (normalization_ == LossParameter_NormalizationMode_VALID) { caffe_gpu_asum(nthreads, counts, &valid_count); } //LOG(INFO) << "Softmax Forward: valid_count = " << valid_count << ", normalizer = "<< get_normalizer(normalization_, valid_count); top[0]->mutable_cpu_data()[0] = loss / get_normalizer(normalization_, valid_count); if (top.size() >= 2) { top[1]->ShareData(prob_); } if (top.size() >= 3) { // Output per-instance loss caffe_gpu_memcpy(top[2]->count() * sizeof(Dtype), loss_data, top[2]->mutable_gpu_data()); } // Fix a bug, which happens when propagate_down[0] = false in backward caffe_gpu_set(bottom[0]->count(), Dtype(0), bottom[0]->mutable_gpu_diff()); } template <typename Dtype> __global__ void SoftmaxLossBackwardGPU(const int nthreads, const Dtype* top, const Dtype* label, const Dtype *weight, 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]); 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; if (weight != NULL){ const Dtype weight_value = static_cast<Dtype>(weight[n * spatial_dim + s]); for (int k = 0; k < channels; ++k) bottom_diff[n * dim + k * spatial_dim + s] *= weight_value; counts[index] = weight_value; } else 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(); // loss_data: entropy loss of each position 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(); //1102 added bool has_weight = bottom.size() >= 3; const Dtype* weight = NULL; if (has_weight) weight = bottom[2]->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, weight, bottom_diff, outer_num_, dim, inner_num_, has_ignore_label_, ignore_label_, counts); Dtype valid_count = -1; // Only launch another CUDA kernel if we actually need the count of valid // outputs. // 1102 changed //if (normalization_ == LossParameter_NormalizationMode_VALID && // has_ignore_label_) { if (normalization_ == LossParameter_NormalizationMode_VALID) { caffe_gpu_asum(nthreads, counts, &valid_count); } //LOG(INFO) << "Softmax Backward: valid_count = " << valid_count << ", normalizer = "<< get_normalizer(normalization_, valid_count); const Dtype loss_weight = top[0]->cpu_diff()[0] / get_normalizer(normalization_, valid_count); caffe_gpu_scal(prob_.count(), loss_weight , bottom_diff); } } INSTANTIATE_LAYER_GPU_FUNCS(SoftmaxWithLossLayer); } // namespace caffe
78ab523330442297905fc35d9de831e945106310.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #!/usr/bin/env c-script #include <bmp.h> struct img{ int w; int h; int* d; __device__ __host__ img(){ w=0; h=0; d=NULL; } __device__ __host__ int& operator () (int x,int y,int z){ if(x>=w) x=w-1; else if(x<0) x=0; if(y>=h) y=h-1; else if(y<0) y=0; return d[(y*w+x)*3+z]; } __device__ __host__ const int& operator () (int x,int y,int z)const{ if(x>=w) x=w-1; else if(x<0) x=0; if(y>=h) y=h-1; else if(y<0) y=0; return d[(y*w+x)*3+z]; } }; void copy(const BMP& bm,img& im){ im.w=bm.w; im.h=bm.h; malloc_d(im.d,im.w*im.h*3*sizeof(int)); cpy_h2d(bm.rgb,im.d,im.w*im.h*3*sizeof(int)); } void copy(const img& im,BMP& bm){ bm.init(im.w,im.h); cpy_d2h(im.d,bm.rgb,im.w*im.h*3*sizeof(int)); } void copy(const img& im,img& im2){ im2=im; malloc_d(im2.d,im.w*im.h*3*sizeof(int)); cpy_d2d(im.d,im2.d,im.w*im.h*3*sizeof(int)); } void init(const img& im,img& im2){ im2=im; malloc_d(im2.d,im.w*im.h*3*sizeof(int)); } #define xl(in,x) ((x)<0 ? 0 :( ((x)>=(in).w) ? (in).w-1:(x))) #define yl(in,y) ((y)<0 ? 0 :( ((y)>=(in).h) ? (in).h-1:(y))) #define val(in,x,y,z) (in.d[((yl((in),(y)))*in.w+(xl((in),(x))))*3+(z)]) __global__ void filter(img in,img out){ int idx=blockIdx.x * blockDim.x + threadIdx.x; int x=idx%in.w; int y=idx/in.w; if(idx>in.w*in.h) return; for(int k=0;k<3;k++){ int v= -in(x,y-1,k) -in(x-1,y,k)+in(x,y,k)*5-in(x+1,y,k)+ -in(x,y+1,k); if(v>255) v=255; else if(v<0) v=0; out(x,y,k)=v; } } int main(int argc,char** argv){ BMP bin(argv[1]); BMP bout; img in; img out; copy(bin,in); init(in,out); int th=256; hipLaunchKernelGGL(( filter), dim3((in.w*in.h+th-1)/th),dim3(th), 0, 0, in,out); // filter(in,out); copy(out,bout); bout.write(argv[2]); free_d(in.d); free_d(out.d); return 0; }
78ab523330442297905fc35d9de831e945106310.cu
#!/usr/bin/env c-script #include <bmp.h> struct img{ int w; int h; int* d; __device__ __host__ img(){ w=0; h=0; d=NULL; } __device__ __host__ int& operator () (int x,int y,int z){ if(x>=w) x=w-1; else if(x<0) x=0; if(y>=h) y=h-1; else if(y<0) y=0; return d[(y*w+x)*3+z]; } __device__ __host__ const int& operator () (int x,int y,int z)const{ if(x>=w) x=w-1; else if(x<0) x=0; if(y>=h) y=h-1; else if(y<0) y=0; return d[(y*w+x)*3+z]; } }; void copy(const BMP& bm,img& im){ im.w=bm.w; im.h=bm.h; malloc_d(im.d,im.w*im.h*3*sizeof(int)); cpy_h2d(bm.rgb,im.d,im.w*im.h*3*sizeof(int)); } void copy(const img& im,BMP& bm){ bm.init(im.w,im.h); cpy_d2h(im.d,bm.rgb,im.w*im.h*3*sizeof(int)); } void copy(const img& im,img& im2){ im2=im; malloc_d(im2.d,im.w*im.h*3*sizeof(int)); cpy_d2d(im.d,im2.d,im.w*im.h*3*sizeof(int)); } void init(const img& im,img& im2){ im2=im; malloc_d(im2.d,im.w*im.h*3*sizeof(int)); } #define xl(in,x) ((x)<0 ? 0 :( ((x)>=(in).w) ? (in).w-1:(x))) #define yl(in,y) ((y)<0 ? 0 :( ((y)>=(in).h) ? (in).h-1:(y))) #define val(in,x,y,z) (in.d[((yl((in),(y)))*in.w+(xl((in),(x))))*3+(z)]) __global__ void filter(img in,img out){ int idx=blockIdx.x * blockDim.x + threadIdx.x; int x=idx%in.w; int y=idx/in.w; if(idx>in.w*in.h) return; for(int k=0;k<3;k++){ int v= -in(x,y-1,k) -in(x-1,y,k)+in(x,y,k)*5-in(x+1,y,k)+ -in(x,y+1,k); if(v>255) v=255; else if(v<0) v=0; out(x,y,k)=v; } } int main(int argc,char** argv){ BMP bin(argv[1]); BMP bout; img in; img out; copy(bin,in); init(in,out); int th=256; filter<<<(in.w*in.h+th-1)/th,th>>>(in,out); // filter(in,out); copy(out,bout); bout.write(argv[2]); free_d(in.d); free_d(out.d); return 0; }
71f51e6be8ff5211c270c7cfa5312766bc8ad9e9.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 "square_i32.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]; int *vector = NULL; hipMalloc(&vector, XSIZE*YSIZE); int *output = NULL; hipMalloc(&output, XSIZE*YSIZE); int len = 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(( square_i32), dim3(gridBlock),dim3(threadBlock), 0, 0, vector,output,len); hipDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) {hipLaunchKernelGGL(( square_i32), dim3(gridBlock),dim3(threadBlock), 0, 0, vector,output,len); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) {hipLaunchKernelGGL(( square_i32), dim3(gridBlock),dim3(threadBlock), 0, 0, vector,output,len); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
71f51e6be8ff5211c270c7cfa5312766bc8ad9e9.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 "square_i32.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]; int *vector = NULL; cudaMalloc(&vector, XSIZE*YSIZE); int *output = NULL; cudaMalloc(&output, XSIZE*YSIZE); int len = 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); square_i32<<<gridBlock,threadBlock>>>(vector,output,len); cudaDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) { square_i32<<<gridBlock,threadBlock>>>(vector,output,len); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) { square_i32<<<gridBlock,threadBlock>>>(vector,output,len); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
d76f2d7c3948ce8ab29e08516937d68d13633baa.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "common.h" __global__ void SamplingKernel(float* C, const float* im, const unsigned int* fwdMap1, const unsigned int* fwdMap2, const unsigned short* bwdMap1, const unsigned short* bwdMap2, paraType par, unsigned int N1, unsigned int N2, unsigned short TL, // time series length. float* gpuRandMat, dim3 size, uint job, uint checkerboard); __device__ float GetCorr(const float* im, unsigned int N, unsigned int M, // time series length int idx1, int idx2); void GPUSampling(float* C, // initial connectivity matrix. const float* im, const unsigned int* fwdMap1, const unsigned int* fwdMap2, const unsigned short* bwdMap1, const unsigned short* bwdMap2, paraType par, unsigned int N1, unsigned int N2, unsigned short TL, // time series length. const unsigned short* size) { if (_DBG >= 3){ printf("GPUSampling row and col of C: N1 = %d, N2 = %d\n", N1, N2); printf("GPUSampling, size = [%d][%d][%d]\n", size[0], size[1], size[2]); } uint iter; // Gibbs Sampling iteration time. uint i, j; // connectivty matrix size. unsigned int BN = N1 * (N1+1)/2; unsigned int mapSize = size[0]*size[1]*size[2]; // define simSize as argument of kernel fun. dim3 dimSize(size[0], size[1], size[2]); // random number matrix. float* randMat = (float*) calloc(BN, sizeof(float)); // pointer to device memory. float* gpuC; float* gpuIm; unsigned int* gpuFwdMap1; unsigned int* gpuFwdMap2; unsigned short* gpuBwdMap1; unsigned short* gpuBwdMap2; float* gpuRandMat; /* create input and output array on GPU. */ hipMalloc((void**) &gpuC, sizeof(float)*BN); checkCUDAError("CudaSampling, allocate gpuC."); hipMalloc((void**) &gpuIm, sizeof(float)*N1*TL); checkCUDAError("CudaSampling, allocate gpuR"); hipMalloc((void**) &gpuFwdMap1, sizeof(unsigned int)*mapSize); checkCUDAError("CudaSampling, allocate fwdMap1"); hipMalloc((void**) &gpuFwdMap2, sizeof(unsigned int)*mapSize); checkCUDAError("CudaSampling, allocate fwdMap2"); hipMalloc((void**) &gpuBwdMap1, sizeof(unsigned short)*N1*3); checkCUDAError("CudaSampling, allocate bwdMap1"); hipMalloc((void**) &gpuBwdMap2, sizeof(unsigned short)*N2*3); checkCUDAError("CudaSampling, allocate bwdMap2"); /* host to device memory. */ hipMemcpy(gpuC, C, sizeof(float)*BN, hipMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuC"); hipMemcpy(gpuFwdMap1, fwdMap1, sizeof(unsigned int)*mapSize, hipMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuFwdMap1"); hipMemcpy(gpuFwdMap2, fwdMap2, sizeof(unsigned int)*mapSize, hipMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuFwdMap2"); hipMemcpy(gpuBwdMap1, bwdMap1, sizeof(unsigned short)*N1*3, hipMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuBwdMap1"); hipMemcpy(gpuBwdMap2, bwdMap2, sizeof(unsigned short)*N2*3, hipMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuBwdMap2"); hipMemcpy(gpuIm, im, sizeof(float)*N1*TL, hipMemcpyHostToDevice); checkCUDAError("CudaSampling, copy im to gpuIm"); /* run the kernel function. */ int gridDimx = N1/BLOCK_SIZE_X + (N1%BLOCK_SIZE_X == 0?0:1); int gridDimy = N2/BLOCK_SIZE_Y + (N2%BLOCK_SIZE_Y == 0?0:1); dim3 dimBlock(BLOCK_SIZE_X, BLOCK_SIZE_Y); dim3 dimGrid(gridDimx, gridDimy); if(_DBG >= 3){ printf("GPUSampling, block size: %dx%d\n", BLOCK_SIZE_X, BLOCK_SIZE_Y); printf("GPUsampling, gridsize: %dx%d\n", gridDimx, gridDimy); } if (DO_SAMPLING) { // allocate gpu memory for random number. hipMalloc((void**) &gpuRandMat, sizeof(float)*BN); checkCUDAError("CudaSampling, allocate gpuRandMat"); for (iter = 1; iter < GIBBSMAXITER; iter++){ if (_DBG >= 1 & iter%1 == 0){ printf("GPUSampling, begin iteration %d...\n", iter); } // Generate random number. //srand48(time(0)); srand48(iter); for (i = 0; i < BN; i++){ randMat[i] = drand48(); } // send random number to gpu. hipMemcpy(gpuRandMat, randMat, sizeof(float)*BN, hipMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuRandMat"); // call kernel for even voxels. hipLaunchKernelGGL(( SamplingKernel), dim3(dimGrid), dim3(dimBlock), 0, 0, gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 0, 0); hipDeviceSynchronize(); // call kernel for odd voxels. hipLaunchKernelGGL(( SamplingKernel), dim3(dimGrid), dim3(dimBlock), 0, 0, gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 0, 1); if (_DBG >= 4){ // Send results back to cpu memeory. Do we really need this step??? hipMemcpy(C, gpuC, sizeof(float)*BN, hipMemcpyDeviceToHost); printf("GPUSampling, after samplingKernel iteration %d. C: \n", iter); show_mat(C, N1, "matrix C"); } } if (_DBG >= 4){ printf("GPUSampling, all sampling iteration done.C: \n"); show_mat(C, N1, "matrix C"); // FieldViewer(C, N1, N2, fwdMap1, fwdMap2, "GPUSampling: Sampled C"); } } // end of DO_SAMPLING // Now compute mean field. for (iter = 1; iter <= MEANFIELDITER; iter++){ if (_DBG >= 1 & iter%1 == 0){ printf("GPUSampling, mean filed iteration: %d...\n", iter); } hipLaunchKernelGGL(( SamplingKernel), dim3(dimGrid), dim3(dimBlock), 0, 0, gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 1, 0); hipDeviceSynchronize(); hipLaunchKernelGGL(( SamplingKernel), dim3(dimGrid), dim3(dimBlock), 0, 0, gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 1, 1); if (_DBG >= 4){ /* Send results back to cpu memeory */ hipMemcpy(C, gpuC, sizeof(float)*BN, hipMemcpyDeviceToHost); show_mat(C, N1, "expcted value C"); FieldViewer(C, N1, N2, fwdMap1, fwdMap2, "GPUSampling: Mean Field"); } } hipMemcpy(C, gpuC, sizeof(float)*BN, hipMemcpyDeviceToHost); /* clean up. */ hipFree(gpuC); hipFree(gpuFwdMap1); hipFree(gpuFwdMap2); hipFree(gpuBwdMap1); hipFree(gpuBwdMap2); hipFree(gpuIm); free(randMat); if (DO_SAMPLING) { hipFree(gpuRandMat); } } /* Kernel function */ __global__ void SamplingKernel(float* C, const float* im, const unsigned int* gpuFwdMap1, const unsigned int* gpuFwdMap2, const unsigned short* gpuBwdMap1, const unsigned short* gpuBwdMap2, paraType par, unsigned int N1, unsigned int N2, unsigned short TL, // time series length. float* gpuRandMat, dim3 size, uint job, uint checkerboard) { unsigned short i; unsigned short j; unsigned short k; int di, dj, dk; int ti, tj, tk; uint n; uint n1 = blockIdx.x*blockDim.x + threadIdx.x; uint n2 = blockIdx.y*blockDim.y + threadIdx.y; float gc1 = 1/(sqrt(2*PI*par.sigma21)); float gc2 = 1/(sqrt(2*PI*par.sigma22)); float sum = 0, denom = 0, pr1 = 0, pr2 = 0, postsum = 0; float lh1 = 0, lh2 = 0, post1 = 0, post2 = 0; float upp = 0, upn = 0; // posterior energy for x = 1 (upp) and x = -1 (upn). // thread fall outside of matrix C, or mask is zero. if (n1 >= N1 | n2 >= N2 | n1 > n2) {return;} // define checkerboard and update image in two steps. unsigned short checksum = gpuBwdMap1[n1*3 + 0] + gpuBwdMap1[n1*3 + 1] + gpuBwdMap1[n1*3 + 2] + gpuBwdMap2[n2*3 + 0] + gpuBwdMap2[n2*3 + 1] + gpuBwdMap2[n2*3 + 2]; if (checksum%2 != checkerboard) {return;} // image one's neighbors. i = gpuBwdMap1[n1*3 + 0]; j = gpuBwdMap1[n1*3 + 1]; k = gpuBwdMap1[n1*3 + 2]; for (di = -1; di <= 1; di ++){ for (dj = -1; dj <= 1; dj ++){ for (dk = -1; dk <= 1; dk ++){ ti = i + di; tj = j + dj; tk = k + dk; if ((ti >= 0 && ti < size.x && tj >= 0 && tj < size.y && tk >= 0 && tk < size.z) && (gpuFwdMap1[ti * size.y*size.z + tj * size.z + tk] > 0)){ n = gpuFwdMap1[ti * size.y*size.z + tj * size.z + tk]; if (n <= n2) { sum = sum + GTI(C, n, n2, N2); } else { // lower traingle of matrix C. use upper triangle value. sum = sum + GTI(C, n2, n, N2); } } } } } sum = sum - GTI(C, n1, n2, N2); // image 2's neighbors. i = gpuBwdMap2[n2*3 + 0]; j = gpuBwdMap2[n2*3 + 1]; k = gpuBwdMap2[n2*3 + 2]; for (di = -1; di <= 1; di ++){ for (dj = -1; dj <= 1; dj ++){ for (dk = -1; dk <= 1; dk ++){ ti = i + di; tj = j + dj; tk = k + dk; if ((ti >= 0 && ti < size.x && tj >= 0 && tj < size.y && tk >= 0 && tk < size.z) && (gpuFwdMap2[ti * size.y * size.z + tj * size.z + tk] > 0)){ n = gpuFwdMap2[ti * size.y * size.z + tj * size.z + tk]; if (n1 <= n) { sum = sum + GTI(C, n1, n, N2); } else { sum = sum + GTI(C, n, n1, N2); } } } } } sum = sum - GTI(C, n1, n2, N2); float yi = GetCorr(im, N1, TL, n1, n2); upn = par.beta*sum + (yi-par.mu1)*(yi-par.mu1)/(2*par.sigma21) + log(sqrt(par.sigma21)); upp = - par.beta*sum + (yi-par.mu2)*(yi-par.mu2)/(2*par.sigma22) + log(sqrt(par.sigma22)); if ((upn-upp) > MAXEXP) { post1 = 0; post2 = 1; } else if ((upn-upp) < -MAXEXP) { post1 = 1; post2 = 0; } else { post1 = 1/(1 + exp(upn-upp)); post2 = 1 - post1; } if (job == 1){ // expectation. mean field. GTI(C, n1, n2, N2) = post2 - post1; } else if (job == 0){ // sampling if (GTI(gpuRandMat, n1, n2, N2) < post1) { GTI(C, n1, n2, N2) = -1; } else{ GTI(C, n1, n2, N2) = 1; } } else if (job == 2){ // compute posterior. p(c == -1) GTI(gpuRandMat, n1, n2, N2) = post2; // if (n1 == n2) GTI(gpuRandMat, n1, n2, N2) = 1; } else{ // something must be wrong. Just exit. } } // compute correlation. __device__ float GetCorr(const float* im, unsigned int N, unsigned int M, // time series length int idx1, int idx2) { int m = 0; float mean1 = 0; float mean2 = 0; float std1 = 0; float std2 = 0; int lidx1, lidx2; float r = 0; // temp variable for sample correlation. if (idx1 == idx2){ return DIAGCORR; } // mean of vectors. for (m = 0; m < M; m++){ lidx1 = idx1*M + m; lidx2 = idx2*M + m; mean1 = mean1 + *(im + lidx1)/M; mean2 = mean2 + *(im + lidx2)/M; } /* Standard deviation. */ for (m = 0; m < M; m++){ lidx1 = idx1 * M + m; lidx2 = idx2 * M + m; std1 = std1 + pow((*(im+lidx1) - mean1), 2)/(M-1); std2 = std2 + pow((*(im+lidx2) - mean2), 2)/(M-1); } std1 = sqrt(std1); std2 = sqrt(std2); /* Sample Correlation. */ if (std1 == 0 | std2 == 0){ return 0; } else{ for (m = 0; m < M; m++){ lidx1 = idx1 * M + m; lidx2 = idx2 * M + m; r = r + (*(im + lidx1) - mean1) * (*(im + lidx2)-mean2)/((M-1)*std1*std2); } return r; } }
d76f2d7c3948ce8ab29e08516937d68d13633baa.cu
#include "common.h" __global__ void SamplingKernel(float* C, const float* im, const unsigned int* fwdMap1, const unsigned int* fwdMap2, const unsigned short* bwdMap1, const unsigned short* bwdMap2, paraType par, unsigned int N1, unsigned int N2, unsigned short TL, // time series length. float* gpuRandMat, dim3 size, uint job, uint checkerboard); __device__ float GetCorr(const float* im, unsigned int N, unsigned int M, // time series length int idx1, int idx2); void GPUSampling(float* C, // initial connectivity matrix. const float* im, const unsigned int* fwdMap1, const unsigned int* fwdMap2, const unsigned short* bwdMap1, const unsigned short* bwdMap2, paraType par, unsigned int N1, unsigned int N2, unsigned short TL, // time series length. const unsigned short* size) { if (_DBG >= 3){ printf("GPUSampling row and col of C: N1 = %d, N2 = %d\n", N1, N2); printf("GPUSampling, size = [%d][%d][%d]\n", size[0], size[1], size[2]); } uint iter; // Gibbs Sampling iteration time. uint i, j; // connectivty matrix size. unsigned int BN = N1 * (N1+1)/2; unsigned int mapSize = size[0]*size[1]*size[2]; // define simSize as argument of kernel fun. dim3 dimSize(size[0], size[1], size[2]); // random number matrix. float* randMat = (float*) calloc(BN, sizeof(float)); // pointer to device memory. float* gpuC; float* gpuIm; unsigned int* gpuFwdMap1; unsigned int* gpuFwdMap2; unsigned short* gpuBwdMap1; unsigned short* gpuBwdMap2; float* gpuRandMat; /* create input and output array on GPU. */ cudaMalloc((void**) &gpuC, sizeof(float)*BN); checkCUDAError("CudaSampling, allocate gpuC."); cudaMalloc((void**) &gpuIm, sizeof(float)*N1*TL); checkCUDAError("CudaSampling, allocate gpuR"); cudaMalloc((void**) &gpuFwdMap1, sizeof(unsigned int)*mapSize); checkCUDAError("CudaSampling, allocate fwdMap1"); cudaMalloc((void**) &gpuFwdMap2, sizeof(unsigned int)*mapSize); checkCUDAError("CudaSampling, allocate fwdMap2"); cudaMalloc((void**) &gpuBwdMap1, sizeof(unsigned short)*N1*3); checkCUDAError("CudaSampling, allocate bwdMap1"); cudaMalloc((void**) &gpuBwdMap2, sizeof(unsigned short)*N2*3); checkCUDAError("CudaSampling, allocate bwdMap2"); /* host to device memory. */ cudaMemcpy(gpuC, C, sizeof(float)*BN, cudaMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuC"); cudaMemcpy(gpuFwdMap1, fwdMap1, sizeof(unsigned int)*mapSize, cudaMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuFwdMap1"); cudaMemcpy(gpuFwdMap2, fwdMap2, sizeof(unsigned int)*mapSize, cudaMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuFwdMap2"); cudaMemcpy(gpuBwdMap1, bwdMap1, sizeof(unsigned short)*N1*3, cudaMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuBwdMap1"); cudaMemcpy(gpuBwdMap2, bwdMap2, sizeof(unsigned short)*N2*3, cudaMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuBwdMap2"); cudaMemcpy(gpuIm, im, sizeof(float)*N1*TL, cudaMemcpyHostToDevice); checkCUDAError("CudaSampling, copy im to gpuIm"); /* run the kernel function. */ int gridDimx = N1/BLOCK_SIZE_X + (N1%BLOCK_SIZE_X == 0?0:1); int gridDimy = N2/BLOCK_SIZE_Y + (N2%BLOCK_SIZE_Y == 0?0:1); dim3 dimBlock(BLOCK_SIZE_X, BLOCK_SIZE_Y); dim3 dimGrid(gridDimx, gridDimy); if(_DBG >= 3){ printf("GPUSampling, block size: %dx%d\n", BLOCK_SIZE_X, BLOCK_SIZE_Y); printf("GPUsampling, gridsize: %dx%d\n", gridDimx, gridDimy); } if (DO_SAMPLING) { // allocate gpu memory for random number. cudaMalloc((void**) &gpuRandMat, sizeof(float)*BN); checkCUDAError("CudaSampling, allocate gpuRandMat"); for (iter = 1; iter < GIBBSMAXITER; iter++){ if (_DBG >= 1 & iter%1 == 0){ printf("GPUSampling, begin iteration %d...\n", iter); } // Generate random number. //srand48(time(0)); srand48(iter); for (i = 0; i < BN; i++){ randMat[i] = drand48(); } // send random number to gpu. cudaMemcpy(gpuRandMat, randMat, sizeof(float)*BN, cudaMemcpyHostToDevice); checkCUDAError("CudaSampling, memcpy gpuRandMat"); // call kernel for even voxels. SamplingKernel<<<dimGrid, dimBlock>>>(gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 0, 0); cudaThreadSynchronize(); // call kernel for odd voxels. SamplingKernel<<<dimGrid, dimBlock>>>(gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 0, 1); if (_DBG >= 4){ // Send results back to cpu memeory. Do we really need this step??? cudaMemcpy(C, gpuC, sizeof(float)*BN, cudaMemcpyDeviceToHost); printf("GPUSampling, after samplingKernel iteration %d. C: \n", iter); show_mat(C, N1, "matrix C"); } } if (_DBG >= 4){ printf("GPUSampling, all sampling iteration done.C: \n"); show_mat(C, N1, "matrix C"); // FieldViewer(C, N1, N2, fwdMap1, fwdMap2, "GPUSampling: Sampled C"); } } // end of DO_SAMPLING // Now compute mean field. for (iter = 1; iter <= MEANFIELDITER; iter++){ if (_DBG >= 1 & iter%1 == 0){ printf("GPUSampling, mean filed iteration: %d...\n", iter); } SamplingKernel<<<dimGrid, dimBlock>>>(gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 1, 0); cudaThreadSynchronize(); SamplingKernel<<<dimGrid, dimBlock>>>(gpuC, gpuIm, gpuFwdMap1, gpuFwdMap2, gpuBwdMap1, gpuBwdMap2, par, N1, N2, TL, gpuRandMat, dimSize, 1, 1); if (_DBG >= 4){ /* Send results back to cpu memeory */ cudaMemcpy(C, gpuC, sizeof(float)*BN, cudaMemcpyDeviceToHost); show_mat(C, N1, "expcted value C"); FieldViewer(C, N1, N2, fwdMap1, fwdMap2, "GPUSampling: Mean Field"); } } cudaMemcpy(C, gpuC, sizeof(float)*BN, cudaMemcpyDeviceToHost); /* clean up. */ cudaFree(gpuC); cudaFree(gpuFwdMap1); cudaFree(gpuFwdMap2); cudaFree(gpuBwdMap1); cudaFree(gpuBwdMap2); cudaFree(gpuIm); free(randMat); if (DO_SAMPLING) { cudaFree(gpuRandMat); } } /* Kernel function */ __global__ void SamplingKernel(float* C, const float* im, const unsigned int* gpuFwdMap1, const unsigned int* gpuFwdMap2, const unsigned short* gpuBwdMap1, const unsigned short* gpuBwdMap2, paraType par, unsigned int N1, unsigned int N2, unsigned short TL, // time series length. float* gpuRandMat, dim3 size, uint job, uint checkerboard) { unsigned short i; unsigned short j; unsigned short k; int di, dj, dk; int ti, tj, tk; uint n; uint n1 = blockIdx.x*blockDim.x + threadIdx.x; uint n2 = blockIdx.y*blockDim.y + threadIdx.y; float gc1 = 1/(sqrt(2*PI*par.sigma21)); float gc2 = 1/(sqrt(2*PI*par.sigma22)); float sum = 0, denom = 0, pr1 = 0, pr2 = 0, postsum = 0; float lh1 = 0, lh2 = 0, post1 = 0, post2 = 0; float upp = 0, upn = 0; // posterior energy for x = 1 (upp) and x = -1 (upn). // thread fall outside of matrix C, or mask is zero. if (n1 >= N1 | n2 >= N2 | n1 > n2) {return;} // define checkerboard and update image in two steps. unsigned short checksum = gpuBwdMap1[n1*3 + 0] + gpuBwdMap1[n1*3 + 1] + gpuBwdMap1[n1*3 + 2] + gpuBwdMap2[n2*3 + 0] + gpuBwdMap2[n2*3 + 1] + gpuBwdMap2[n2*3 + 2]; if (checksum%2 != checkerboard) {return;} // image one's neighbors. i = gpuBwdMap1[n1*3 + 0]; j = gpuBwdMap1[n1*3 + 1]; k = gpuBwdMap1[n1*3 + 2]; for (di = -1; di <= 1; di ++){ for (dj = -1; dj <= 1; dj ++){ for (dk = -1; dk <= 1; dk ++){ ti = i + di; tj = j + dj; tk = k + dk; if ((ti >= 0 && ti < size.x && tj >= 0 && tj < size.y && tk >= 0 && tk < size.z) && (gpuFwdMap1[ti * size.y*size.z + tj * size.z + tk] > 0)){ n = gpuFwdMap1[ti * size.y*size.z + tj * size.z + tk]; if (n <= n2) { sum = sum + GTI(C, n, n2, N2); } else { // lower traingle of matrix C. use upper triangle value. sum = sum + GTI(C, n2, n, N2); } } } } } sum = sum - GTI(C, n1, n2, N2); // image 2's neighbors. i = gpuBwdMap2[n2*3 + 0]; j = gpuBwdMap2[n2*3 + 1]; k = gpuBwdMap2[n2*3 + 2]; for (di = -1; di <= 1; di ++){ for (dj = -1; dj <= 1; dj ++){ for (dk = -1; dk <= 1; dk ++){ ti = i + di; tj = j + dj; tk = k + dk; if ((ti >= 0 && ti < size.x && tj >= 0 && tj < size.y && tk >= 0 && tk < size.z) && (gpuFwdMap2[ti * size.y * size.z + tj * size.z + tk] > 0)){ n = gpuFwdMap2[ti * size.y * size.z + tj * size.z + tk]; if (n1 <= n) { sum = sum + GTI(C, n1, n, N2); } else { sum = sum + GTI(C, n, n1, N2); } } } } } sum = sum - GTI(C, n1, n2, N2); float yi = GetCorr(im, N1, TL, n1, n2); upn = par.beta*sum + (yi-par.mu1)*(yi-par.mu1)/(2*par.sigma21) + log(sqrt(par.sigma21)); upp = - par.beta*sum + (yi-par.mu2)*(yi-par.mu2)/(2*par.sigma22) + log(sqrt(par.sigma22)); if ((upn-upp) > MAXEXP) { post1 = 0; post2 = 1; } else if ((upn-upp) < -MAXEXP) { post1 = 1; post2 = 0; } else { post1 = 1/(1 + exp(upn-upp)); post2 = 1 - post1; } if (job == 1){ // expectation. mean field. GTI(C, n1, n2, N2) = post2 - post1; } else if (job == 0){ // sampling if (GTI(gpuRandMat, n1, n2, N2) < post1) { GTI(C, n1, n2, N2) = -1; } else{ GTI(C, n1, n2, N2) = 1; } } else if (job == 2){ // compute posterior. p(c == -1) GTI(gpuRandMat, n1, n2, N2) = post2; // if (n1 == n2) GTI(gpuRandMat, n1, n2, N2) = 1; } else{ // something must be wrong. Just exit. } } // compute correlation. __device__ float GetCorr(const float* im, unsigned int N, unsigned int M, // time series length int idx1, int idx2) { int m = 0; float mean1 = 0; float mean2 = 0; float std1 = 0; float std2 = 0; int lidx1, lidx2; float r = 0; // temp variable for sample correlation. if (idx1 == idx2){ return DIAGCORR; } // mean of vectors. for (m = 0; m < M; m++){ lidx1 = idx1*M + m; lidx2 = idx2*M + m; mean1 = mean1 + *(im + lidx1)/M; mean2 = mean2 + *(im + lidx2)/M; } /* Standard deviation. */ for (m = 0; m < M; m++){ lidx1 = idx1 * M + m; lidx2 = idx2 * M + m; std1 = std1 + pow((*(im+lidx1) - mean1), 2)/(M-1); std2 = std2 + pow((*(im+lidx2) - mean2), 2)/(M-1); } std1 = sqrt(std1); std2 = sqrt(std2); /* Sample Correlation. */ if (std1 == 0 | std2 == 0){ return 0; } else{ for (m = 0; m < M; m++){ lidx1 = idx1 * M + m; lidx2 = idx2 * M + m; r = r + (*(im + lidx1) - mean1) * (*(im + lidx2)-mean2)/((M-1)*std1*std2); } return r; } }
aff335fbaed896bd39c347cb2e97b02449c34356.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <algorithm> #include "caffe2/core/operator.h" #include "caffe2/operators/segment_reduction_op.h" #include "caffe2/operators/segment_reduction_op_gpu.cuh" #include "caffe2/utils/GpuAtomics.cuh" #include "caffe2/utils/math.h" namespace caffe2 { namespace { void inclusive_scan_wrapper( const int* length_data, int len_length, Tensor* temp_buffer, Tensor* prefix_sum_out, CUDAContext* context_) { // Retrieve buffer size size_t temp_storage_bytes = 0; hipcub::DeviceScan::InclusiveSum( NULL, temp_storage_bytes, length_data, prefix_sum_out->template mutable_data<int>(), len_length, context_->cuda_stream()); // Allocate temporary storage auto buffer_size = (temp_storage_bytes + sizeof(int)) / sizeof(int); temp_buffer->Resize(buffer_size); void* d_temp_storage = static_cast<void*>(temp_buffer->template mutable_data<int>()); // Run inclusive prefix sum hipcub::DeviceScan::InclusiveSum( d_temp_storage, temp_storage_bytes, length_data, prefix_sum_out->template mutable_data<int>(), len_length, context_->cuda_stream()); } template <typename T, bool ExactBlock = false, bool Average = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_sum_kernel( const T* __restrict__ in, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { in += threadIdx.x; T sum = (T)0; for (int line = start; line < end; ++line) { sum += in[line * post]; } if (Average && (end - start) > 1) { sum /= (end - start); } out[group * post + threadIdx.x] = sum; } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T sum = (T)0; for (int line = start; line < end; ++line) { sum += in[line * post + i]; } if (Average && (end - start) > 1) { sum /= (end - start); } out[group * post + i] = sum; } } } template <typename T, bool ExactBlock = false, bool Average = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_sum_gradient_kernel( const T* __restrict__ grad_in, T* __restrict__ grad_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { grad_out += threadIdx.x; grad_in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { grad_out[line * post] = grad_in[group * post]; if (Average && (end - start) > 1) { grad_out[line * post] /= (end - start); } } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { for (int line = start; line < end; ++line) { grad_out[line * post + i] = grad_in[group * post + i]; if (Average && (end - start) > 1) { grad_out[line * post + i] /= (end - start); } } } } } template <typename T, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_max_kernel( const T* __restrict__ in, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length, const T numeric_min) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { in += threadIdx.x; T max = numeric_min; for (int line = start; line < end; ++line) { T in_data = in[line * post]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + threadIdx.x] = max; } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T max = numeric_min; for (int line = start; line < end; ++line) { T in_data = in[line * post + i]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + i] = max; } } } template <typename T, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_weighted_sum_gradient_kernel( const T* __restrict__ grad_in, const T* __restrict__ weights_in, T* __restrict__ grad_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { grad_out += threadIdx.x; grad_in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { grad_out[line * post] = weights_in[line] * grad_in[group * post]; } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { for (int line = start; line < end; ++line) { grad_out[line * post + i] = weights_in[line] * grad_in[group * post + i]; } } } } template <typename T, typename IndexType, int NumThreads> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_weighted_sum_with_main_input_gradient_kernel( const T* __restrict__ grad_in, const T* __restrict__ weights_in, const T* __restrict__ data_in, const IndexType* __restrict__ indices, T* __restrict__ data_grad_out, T* __restrict__ weights_grad_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); // todo figure this num threads thing typedef hipcub::BlockReduce<float, NumThreads> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; // TODO(wyiming): parallelize this outter loop for (int line = start; line < end; ++line) { T w_grad = 0; for (int i = threadIdx.x; i < post; i += blockDim.x) { auto g_in = grad_in[group * post + i]; data_grad_out[line * post + i] = weights_in[line] * g_in; w_grad += g_in * data_in[indices[line] * post + i]; } w_grad = BlockReduce(temp_storage).Reduce(w_grad, hipcub::Sum()); if (threadIdx.x == 0) { weights_grad_out[line] = w_grad; } __syncthreads(); } } template <typename T, typename IndexType, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void sparse_length_max_kernel( const T* __restrict__ in, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, const IndexType* __restrict__ indices, int N, int post, int len_length, int len_indices, const T numeric_min) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= len_indices); CUDA_KERNEL_ASSERT(end <= len_indices); extern __shared__ T reduceVals[]; if (ExactBlock) { T max = numeric_min; in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { T in_data = in[indices[line] * post]; max = max > in_data ? max : in_data; } reduceVals[threadIdx.y * blockDim.x + threadIdx.x] = max; __syncthreads(); if (threadIdx.y == 0) { max = numeric_min; for (int i = 0; i < blockDim.y; ++i) { T in_data = reduceVals[i * blockDim.x + threadIdx.x]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + threadIdx.x] = max; } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T max = numeric_min; for (int line = start; line < end; ++line) { T in_data = in[indices[line] * post + i]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + i] = max; } } } template <typename T, typename IndexType, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void sparse_length_weighted_sum_kernel( const T* __restrict__ in, const T* __restrict__ in_weights, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, const IndexType* __restrict__ indices, int N, int post, int len_length, int len_indices) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= len_indices); CUDA_KERNEL_ASSERT(end <= len_indices); extern __shared__ T reduceVals[]; if (ExactBlock) { T sum = (T)0; in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { sum += in_weights[line] * in[indices[line] * post]; } reduceVals[threadIdx.y * blockDim.x + threadIdx.x] = sum; __syncthreads(); if (threadIdx.y == 0) { sum = (T)0; for (int i = 0; i < blockDim.y; ++i) { sum += reduceVals[i * blockDim.x + threadIdx.x]; } out[group * post + threadIdx.x] = sum; } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T sum = (T)0; for (int line = start; line < end; ++line) { sum += in_weights[line] * in[indices[line] * post + i]; } out[group * post + i] = sum; } } } } // namespace template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsSumOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit CUDASparseLengthsSumOp(Args&&... args) : Operator<CUDAContext>(std::forward<Args>(args)...) {} ~CUDASparseLengthsSumOp() {} bool RunOnDevice() override { if (SparseFused) { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } else { // type doesn't matter return DoRunWithType<int32_t>(); } } template <typename IndexType> bool DoRunWithType() { if (SparseFused) { return DispatchHelper<TensorTypes2<float, at::Half>, IndexType>::call( this, Input(DATA)); } else { return DoRunWithType2<IndexType, T>(); } } template <typename IndexType, typename InType> bool DoRunWithType2() { auto& dataInput = Input(DATA); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it int64_t dataToReduceSize; const int64_t outputSize = lengthsInput.dim(0); const int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); T* out_data = output->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } const IndexType* indices; if (SparseFused) { // static if auto& indicesInput = Input(INDICES); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); indices = indicesInput.template data<IndexType>(); dataToReduceSize = indicesInput.dim(0); } else { dataToReduceSize = dataSize; } // only compute this the first time inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (SparseFused) { const InType* in_data = dataInput.template data<InType>(); if (post <= maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; // calling cuda kernel with ExactBlock = true, Average = false hipLaunchKernelGGL(( sparse_length_sum_kernel<InType, T, IndexType, true, false>) , dim3(len_length), dim3(block), smem, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = false hipLaunchKernelGGL(( sparse_length_sum_kernel<InType, T, IndexType, false, false>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_HIP_KERNEL_LAUNCH_CHECK(); } } else { const T* in_data = dataInput.template data<T>(); if (post <= maxThreads) { hipLaunchKernelGGL(( length_sum_kernel<T, true, false>) , dim3(len_length), dim3(post), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { hipLaunchKernelGGL(( length_sum_kernel<T, true, false>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } } return true; } enum { DATA = 0, INDICES = 1, LENGTHS = 1 + (SparseFused ? 1 : 0) }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsMeanOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit CUDASparseLengthsMeanOp(Args&&... args) : Operator<CUDAContext>(std::forward<Args>(args)...) {} ~CUDASparseLengthsMeanOp() {} bool RunOnDevice() override { if (SparseFused) { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } else { // type doesn't matter return DoRunWithType<int32_t>(); } } template <typename IndexType> bool DoRunWithType() { if (SparseFused) { return DispatchHelper<TensorTypes2<float, at::Half>, IndexType>::call( this, Input(DATA)); } else { return DoRunWithType2<IndexType, T>(); } } template <typename IndexType, typename InType> bool DoRunWithType2() { auto& dataInput = Input(DATA); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it int64_t dataToReduceSize; const int64_t outputSize = lengthsInput.dim(0); const int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); T* out_data = output->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } const IndexType* indices; if (SparseFused) { // static if auto& indicesInput = Input(INDICES); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); indices = indicesInput.template data<IndexType>(); dataToReduceSize = indicesInput.dim(0); } else { dataToReduceSize = dataSize; } // only compute this the first time inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (SparseFused) { const InType* in_data = dataInput.template data<InType>(); if (post <= maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; // calling cuda kernel with ExactBlock = true, Average = true hipLaunchKernelGGL(( sparse_length_sum_kernel<InType, T, IndexType, true, true>) , dim3(len_length), dim3(block), smem, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = true hipLaunchKernelGGL(( sparse_length_sum_kernel<InType, T, IndexType, false, true>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_HIP_KERNEL_LAUNCH_CHECK(); } } else { const T* in_data = dataInput.template data<T>(); if (post <= maxThreads) { // calling cuda kernel with ExactBlock = true, Average = true hipLaunchKernelGGL(( length_sum_kernel<T, true, true>) , dim3(len_length), dim3(post), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = true, Average = true hipLaunchKernelGGL(( length_sum_kernel<T, true, true>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } } return true; } enum { DATA = 0, INDICES = 1, LENGTHS = 1 + (SparseFused ? 1 : 0) }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsMaxOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit CUDASparseLengthsMaxOp(Args&&... args) : Operator<CUDAContext>(std::forward<Args>(args)...) {} ~CUDASparseLengthsMaxOp() {} bool RunOnDevice() override { if (SparseFused) { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } else { // type doesn't matter return DoRunWithType<int32_t>(); } } template <typename IndexType> bool DoRunWithType() { auto& dataInput = Input(0); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it int64_t dataToReduceSize; const int64_t outputSize = lengthsInput.dim(0); int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } const IndexType* indices; if (SparseFused) { // static if auto& indicesInput = Input(INDICES); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); indices = indicesInput.template data<IndexType>(); dataToReduceSize = indicesInput.dim(0); } else { dataToReduceSize = dataSize; } // only compute this the first time inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); const T* in_data = dataInput.template data<T>(); T* out_data = output->template mutable_data<T>(); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; T numeric_min = std::numeric_limits<T>::min(); if (SparseFused) { if (post <= maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; hipLaunchKernelGGL(( sparse_length_max_kernel<T, IndexType, true>) , dim3(len_length), dim3(block), smem, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize, numeric_min); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { hipLaunchKernelGGL(( sparse_length_max_kernel<T, IndexType, false>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize, numeric_min); C10_HIP_KERNEL_LAUNCH_CHECK(); } } else { if (post <= maxThreads) { hipLaunchKernelGGL(( length_max_kernel<T, true>) , dim3(len_length), dim3(post), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length, numeric_min); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { hipLaunchKernelGGL(( length_max_kernel<T, true>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length, numeric_min); C10_HIP_KERNEL_LAUNCH_CHECK(); } } return true; } enum { INDICES = 1, LENGTHS = 1 + (SparseFused ? 1 : 0) }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsWeightedSumOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsWeightedSumOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsWeightedSumOp() {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } template <typename IndexType> bool DoRunWithType() { auto& dataInput = Input(DATA); auto& weightsInput = Input(WEIGHTS); auto& indicesInput = Input(INDICES); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, weightsInput.dim(), "WEIGHTS must be a vector"); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it const int64_t dataToReduceSize = indicesInput.dim(0); const int64_t outputSize = lengthsInput.dim(0); const int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); T* out_data = output->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); const IndexType* indices = indicesInput.template data<IndexType>(); const T* in_data = dataInput.template data<T>(); const T* in_weights = weightsInput.template data<T>(); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; hipLaunchKernelGGL(( sparse_length_weighted_sum_kernel<T, IndexType, true>) , dim3(len_length), dim3(block), smem, context_.cuda_stream(), in_data, in_weights, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { hipLaunchKernelGGL(( sparse_length_weighted_sum_kernel<T, IndexType, false>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, in_weights, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_HIP_KERNEL_LAUNCH_CHECK(); } return true; } enum { DATA = 0, WEIGHTS = 1, INDICES = 2, LENGTHS = 3 }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename SIndex> __global__ void MaxSegmentKernel(int n, const SIndex* segment_ids, SIndex* max_segment) { typedef hipcub::BlockReduce<SIndex, CAFFE_CUDA_NUM_THREADS> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; int mx = 0; for (int j = threadIdx.x; j < n; j += blockDim.x) { mx = segment_ids[j] > mx ? segment_ids[j] : mx; } SIndex max_seg = BlockReduce(temp_storage).Reduce(mx, hipcub::Max()); if (threadIdx.x == 0) { *max_segment = max_seg; } } template <typename SIndex, typename T> __global__ void UnsortedSegmentSumKernel( int n, int slize_sz, const SIndex* segments, const T* data, T* out, int* scales) { CUDA_1D_KERNEL_LOOP(i, n) { int slice_idx = i / slize_sz; int j = i % slize_sz; SIndex segment = segments[slice_idx]; gpu_atomic_add(&out[segment * slize_sz + j], data[i]); if (scales && j == 0) { gpu_atomic_add(&scales[segment], 1); } } } template <typename SIndex, typename T> __global__ void SegmentScalingKernel(int m, int slize_sz, const int* scales, T* out) { CUDA_1D_KERNEL_LOOP(i, m) { int scale = scales[i / slize_sz]; out[i] = scale > 0 ? out[i] / scale : 0.0; // avoid 0/0 division } } template <typename T, typename SIndex, bool mean> class CUDAUnsortedSegmentSumOp : public Operator<CUDAContext> { public: USE_OPERATOR_FUNCTIONS(CUDAContext); CUDAUnsortedSegmentSumOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDAUnsortedSegmentSumOp() {} bool RunOnDevice() override { auto& data = Input(0); auto& segment_ids = Input(1); if (segment_ids.numel() == 0 || data.numel() == 0) { // Special handling for empty input auto dims = data.sizes().vec(); if (dims.size() > 0) { dims[0] = 0; } Output(0, dims, at::dtype<T>()); return true; } CAFFE_ENFORCE_EQ(1, segment_ids.dim(), "SEGMENT_IDS must be a vector"); int64_t slize_sz = data.size_from_dim(1); ReinitializeTensor(&K_tensor_, {1}, at::dtype<SIndex>().device(CUDA)); // Get maximum segment id so we can size the output. // This must be done synchronously with host. if (segment_ids.numel() > 4096) { // when the input size is large, device reduce is better. size_t tmp_storage_bytes = 0; // the first call to `Max` do nothing, but set correct tmp_storage_bytes. hipcub::DeviceReduce::Max( nullptr, tmp_storage_bytes, segment_ids.template data<SIndex>(), // input device data K_tensor_.template mutable_data<SIndex>(), // output device data segment_ids.numel(), // number of items context_.cuda_stream()); // the second call do the real computation. ReinitializeTensor( &buffer_tensor_, {static_cast<int64_t>(tmp_storage_bytes)}, at::dtype<char>().device(CUDA)); hipcub::DeviceReduce::Max( static_cast<void*>(buffer_tensor_.mutable_data<char>()), tmp_storage_bytes, segment_ids.template data<SIndex>(), // input device data K_tensor_.template mutable_data<SIndex>(), // output device data segment_ids.numel(), // number of items context_.cuda_stream()); } else { hipLaunchKernelGGL(( MaxSegmentKernel<SIndex>) , dim3(1), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), segment_ids.numel(), segment_ids.template data<SIndex>(), K_tensor_.mutable_data<SIndex>()); C10_HIP_KERNEL_LAUNCH_CHECK(); } SIndex K = 0; context_.CopyBytesToCPU( sizeof(SIndex), K_tensor_.template data<SIndex>(), &K); context_.FinishDeviceComputation(); auto dims = data.sizes().vec(); dims[0] = K + 1; auto* output = Output(0, dims, at::dtype<T>()); // Clear the output as we will be accumulating the values math::Set<T, CUDAContext>( output->numel(), T(0), output->template mutable_data<T>(), &context_); if (!mean) { hipLaunchKernelGGL(( UnsortedSegmentSumKernel<SIndex, T>) , dim3(CAFFE_GET_BLOCKS(data.numel())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), data.numel(), slize_sz, segment_ids.template data<SIndex>(), data.template data<T>(), output->template mutable_data<T>(), nullptr); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { // For mean, we need to compute scaling factors ReinitializeTensor( &scaling_factors_, {K + 1}, at::dtype<int>().device(CUDA)); math::Set<int, CUDAContext>( scaling_factors_.numel(), int(0), scaling_factors_.template mutable_data<int>(), &context_); hipLaunchKernelGGL(( UnsortedSegmentSumKernel<SIndex, T>) , dim3(CAFFE_GET_BLOCKS(data.numel())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), data.numel(), slize_sz, segment_ids.template data<SIndex>(), data.template data<T>(), output->template mutable_data<T>(), scaling_factors_.template mutable_data<int>()); C10_HIP_KERNEL_LAUNCH_CHECK(); // Divide by the scaling factors to get means hipLaunchKernelGGL(( SegmentScalingKernel<SIndex, T>) , dim3(CAFFE_GET_BLOCKS(output->numel())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), output->numel(), slize_sz, scaling_factors_.template data<int>(), output->template mutable_data<T>()); C10_HIP_KERNEL_LAUNCH_CHECK(); } return true; } private: Tensor buffer_tensor_; Tensor K_tensor_; Tensor scaling_factors_; // for mean }; template <typename SIndex> __global__ void segment_lengths_kernel(int N, const SIndex* X, SIndex* Y) { CUDA_1D_KERNEL_LOOP(i, N) { gpu_atomic_add(&Y[X[i]], 1); } } template <typename T, typename SIndex, bool LOGEXP = false> __global__ void sorted_segment_mean_kernel( const SIndex K, const int N, const SIndex* S, const SIndex* I, const T* X, T* Y) { for (int sId = blockIdx.x; sId < K; sId += gridDim.x) { const int start_index = sId > 0 ? S[sId] * N : 0; const int y_start_index = sId * N; for (int i = threadIdx.x; i < N; i += blockDim.x) { T sum = 0.0; for (int j = 0; j < I[sId]; ++j) { const T x_i_j = X[start_index + j * N + i]; sum += LOGEXP ? exp(x_i_j) : x_i_j; } const T norm_sum = sum / I[sId]; Y[y_start_index + i] = LOGEXP ? log(norm_sum) : norm_sum; } } } template <typename T, typename SIndex, bool LOGEXP, class Context = CUDAContext> class SortedSegmentRangeMeanOp : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; SortedSegmentRangeMeanOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~SortedSegmentRangeMeanOp() {} bool RunOnDevice() override { const auto& input = Input(0); const auto& indices = Input(1); int M = input.dim32(0); int N = input.size_from_dim(1); auto* output = Output(0); auto dims = input.sizes().vec(); SIndex K = 0; context_.CopyBytesToCPU( sizeof(SIndex), indices.template data<SIndex>() + indices.size() - 1, &K); context_.FinishDeviceComputation(); K += 1; dims[0] = K; if (segment_len_.size() != K) { segment_len_.Resize(K); segment_len_prefix_sum_.Resize(K); } output->Resize(dims); math::Set<SIndex, CUDAContext>( segment_len_.size(), 0, segment_len_.template mutable_data<SIndex>(), &context_); hipLaunchKernelGGL(( segment_lengths_kernel), dim3(CAFFE_GET_BLOCKS(indices.size())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), indices.size(), indices.template data<SIndex>(), segment_len_.template mutable_data<SIndex>()); C10_HIP_KERNEL_LAUNCH_CHECK(); size_t temp_storage_bytes = 0; hipcub::DeviceScan::ExclusiveSum( nullptr, temp_storage_bytes, segment_len_.template data<SIndex>(), segment_len_prefix_sum_.template mutable_data<SIndex>(), K, context_.cuda_stream()); auto buffer_size = (temp_storage_bytes + sizeof(T)) / sizeof(T); prefix_buffer_.Resize(buffer_size); void* dev_temp_storage = static_cast<void*>(prefix_buffer_.mutable_data<T>()); hipcub::DeviceScan::ExclusiveSum( dev_temp_storage, temp_storage_bytes, segment_len_.template data<SIndex>(), segment_len_prefix_sum_.template mutable_data<SIndex>(), K, context_.cuda_stream()); hipLaunchKernelGGL(( sorted_segment_mean_kernel<T, SIndex, LOGEXP>) , dim3(::min(K, CAFFE_MAXIMUM_NUM_BLOCKS)), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), K, N, segment_len_prefix_sum_.template data<SIndex>(), segment_len_.template data<SIndex>(), input.template data<T>(), output->template mutable_data<T>()); C10_HIP_KERNEL_LAUNCH_CHECK(); return true; } private: Tensor segment_len_{CUDA}; // for mean Tensor segment_len_prefix_sum_{CUDA}; Tensor prefix_buffer_{CUDA}; }; template <typename T, typename SIndex, bool LOGEXP = false> __global__ void sorted_segment_mean_gradient_kernel( const int M, const int N, const T* X, const T* Y, const T* dY, const SIndex* I, const SIndex* S, T* dX) { CUDA_1D_KERNEL_LOOP(i, M * N) { const int sId = I[i / N]; const int sSize = S[sId]; const int yId = N * sId + i % N; dX[i] = LOGEXP ? dY[yId] * exp(X[i] - Y[yId]) / sSize : dY[yId] / sSize; } } template <typename T, typename SIndex, bool LOGEXP, class Context = CUDAContext> class SortedSegmentRangeMeanGradientOp : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; SortedSegmentRangeMeanGradientOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~SortedSegmentRangeMeanGradientOp() {} bool RunOnDevice() override { const auto& X = Input(0); const auto& Y = Input(1); const auto& dY = Input(2); const auto& I = Input(3); auto* dX = Output(0, X.sizes(), at::dtype<T>()); const int M = X.dim32(0); const int N = X.size_from_dim(1); SIndex K = 0; context_.CopyBytesToCPU( sizeof(SIndex), I.template data<SIndex>() + I.numel() - 1, &K); K += 1; if (segment_len_.numel() != K) { ReinitializeTensor(&segment_len_, {K}, at::dtype<SIndex>().device(CUDA)); } math::Set<SIndex, CUDAContext>( segment_len_.numel(), 0, segment_len_.template mutable_data<SIndex>(), &context_); hipLaunchKernelGGL(( segment_lengths_kernel), dim3(CAFFE_GET_BLOCKS(I.numel())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), I.numel(), I.template data<SIndex>(), segment_len_.template mutable_data<SIndex>()); C10_HIP_KERNEL_LAUNCH_CHECK(); hipLaunchKernelGGL(( sorted_segment_mean_gradient_kernel<T, SIndex, LOGEXP>) , dim3(CAFFE_GET_BLOCKS(dX->numel())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), M, N, X.template data<T>(), Y.template data<T>(), dY.template data<T>(), I.template data<SIndex>(), segment_len_.template data<SIndex>(), dX->template mutable_data<T>()); C10_HIP_KERNEL_LAUNCH_CHECK(); return true; } private: Tensor segment_len_; // for mean }; REGISTER_CUDA_OPERATOR_STR( "LengthsSum", CUDASparseLengthsSumOp<float, CUDAContext, false>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsSum", CUDASparseLengthsSumOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "LengthsMean", CUDASparseLengthsMeanOp<float, CUDAContext, false>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsMean", CUDASparseLengthsMeanOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "LengthsMax", CUDASparseLengthsMaxOp<float, CUDAContext, false>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsMax", CUDASparseLengthsMaxOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsWeightedSum", CUDASparseLengthsWeightedSumOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "UnsortedSegmentSum", CUDAUnsortedSegmentSumOp<float, int, false>); REGISTER_CUDA_OPERATOR_STR( "UnsortedSegmentMean", CUDAUnsortedSegmentSumOp<float, int, true>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeMean", SortedSegmentRangeMeanOp<float, int, false>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeLogMeanExp", SortedSegmentRangeMeanOp<float, int, true>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeMeanGradient", SortedSegmentRangeMeanGradientOp<float, int, false>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeLogMeanExpGradient", SortedSegmentRangeMeanGradientOp<float, int, true>); template <typename T, class Context = CUDAContext> class CUDASparseLengthsSumGradientWithIndicesOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsSumGradientWithIndicesOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsSumGradientWithIndicesOp() {} bool RunOnDevice() override { auto& segmentGradsInput = Input(0); auto& lengthsInput = Input(1); auto& indicesInput = Input(2); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); T* out_data = dataGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = segmentGradsInput.template data<T>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); // calling cuda kernel with ExactBlock = true, Average = false hipLaunchKernelGGL(( length_sum_gradient_kernel<T, true, false>) , dim3(len_length), dim3(block), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = false hipLaunchKernelGGL(( length_sum_gradient_kernel<T, false, false>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext> class CUDASparseLengthsMeanGradientWithIndicesOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsMeanGradientWithIndicesOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsMeanGradientWithIndicesOp() {} bool RunOnDevice() override { auto& segmentGradsInput = Input(0); auto& lengthsInput = Input(1); auto& indicesInput = Input(2); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); T* out_data = dataGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = segmentGradsInput.template data<T>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); // calling cuda kernel with ExactBlock = true, Average = true hipLaunchKernelGGL(( length_sum_gradient_kernel<T, true, true>) , dim3(len_length), dim3(block), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = true hipLaunchKernelGGL(( length_sum_gradient_kernel<T, false, true>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext> class CUDASparseLengthsWeightedSumGradientWithIndicesOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsWeightedSumGradientWithIndicesOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsWeightedSumGradientWithIndicesOp() {} bool RunOnDevice() override { auto& weightsInput = Input(0); auto& segmentGradsInput = Input(1); auto& lengthsInput = Input(2); auto& indicesInput = Input(3); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); CAFFE_ENFORCE_EQ(1, weightsInput.dim(), "WEIGHTS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); T* out_data = dataGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = segmentGradsInput.template data<T>(); const T* in_weights = weightsInput.template data<T>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post < maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); hipLaunchKernelGGL(( length_weighted_sum_gradient_kernel<T, true>) , dim3(len_length), dim3(block), 0, context_.cuda_stream(), in_data, in_weights, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { hipLaunchKernelGGL(( length_weighted_sum_gradient_kernel<T, false>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, in_weights, out_data, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, bool ExactBlock = false> __global__ void length_max_gradient_kernel( const T* __restrict__ grad_in, T* __restrict__ grad_out, const T* data_in, const T* data_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { grad_out += threadIdx.x; grad_in += threadIdx.x; data_in += threadIdx.x; data_out += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { if (data_in[line * post] == data_out[group * post]) { grad_out[line * post] = grad_in[group * post]; } else { grad_out[line * post] = 0; } } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { for (int line = start; line < end; ++line) { if (data_in[line * post + i] == data_out[group * post + i]) { grad_out[line * post + i] = grad_in[group * post + i]; } else { grad_out[line * post + i] = 0; } } } } } template <typename T, class Context = CUDAContext> class CUDALengthsMaxWithMainInputAndForwardOutputGradientOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDALengthsMaxWithMainInputAndForwardOutputGradientOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDALengthsMaxWithMainInputAndForwardOutputGradientOp() {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<int32_t, float>>::call(this, Input(3)); } template <typename IndexType> bool DoRunWithType() { auto& segmentGradsInput = Input(1); auto& lengthsInput = Input(2); auto& dataInput = Input(3); auto& dataOutput = Input(0); // based on CPU version CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); auto shape = dataInput.sizes().vec(); auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); const T* in_data = segmentGradsInput.template data<T>(); T* out_data = dataGradsOutput->template mutable_data<T>(); int N = dataInput.dim(0); int post = segmentGradsInput.size_from_dim(1); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = ::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); hipLaunchKernelGGL(( length_max_gradient_kernel<T, true>) , dim3(len_length), dim3(block), 0, context_.cuda_stream(), in_data, out_data, dataInput.template data<T>(), dataOutput.template data<T>(), prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { hipLaunchKernelGGL(( length_max_gradient_kernel<T, false>) , dim3(len_length), dim3(maxThreads), 0, context_.cuda_stream(), in_data, out_data, dataInput.template data<T>(), dataOutput.template data<T>(), prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext> class CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp() {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call(this, Input(4)); } template <typename IndexType> bool DoRunWithType() { auto& weightsInput = Input(0); auto& segmentGradsInput = Input(1); auto& lengthsInput = Input(2); auto& dataInput = Input(3); auto& indicesInput = Input(4); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); CAFFE_ENFORCE_EQ(1, weightsInput.dim(), "WEIGHTS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); auto* weightGradsOutput = Output(1, indicesInput.sizes(), at::dtype<T>()); T* out_data_grads = dataGradsOutput->template mutable_data<T>(); T* out_weight_grads = weightGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = dataInput.template data<T>(); const T* in_grads = segmentGradsInput.template data<T>(); const T* in_weights = weightsInput.template data<T>(); const IndexType* indices = indicesInput.template data<IndexType>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); if (post > 128) { hipLaunchKernelGGL(( length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 512>) , dim3(len_length), dim3(512), 0, context_.cuda_stream(), in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else if (post > 64) { hipLaunchKernelGGL(( length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 128>) , dim3(len_length), dim3(128), 0, context_.cuda_stream(), in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else if (post > 32) { hipLaunchKernelGGL(( length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 64>) , dim3(len_length), dim3(64), 0, context_.cuda_stream(), in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } else { hipLaunchKernelGGL(( length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 32>) , dim3(len_length), dim3(32), 0, context_.cuda_stream(), in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_HIP_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; // Needed because name is auto-generated in segment_reduction_op.cc:224 REGISTER_CUDA_OPERATOR_STR( "LengthsMaxWithMainInputAndForwardOutputGradient", CUDALengthsMaxWithMainInputAndForwardOutputGradientOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientWeightedSumGradient, CUDASparseLengthsWeightedSumGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient, CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp< float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientSumGradient, CUDASparseLengthsSumGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( LengthsIndicesInGradientSumGradient, CUDASparseLengthsSumGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientMeanGradient, CUDASparseLengthsMeanGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( LengthsIndicesInGradientMeanGradient, CUDASparseLengthsMeanGradientWithIndicesOp<float, CUDAContext>); } // namespace caffe2 // Macro doesn't like comma using LengthsSumCUDAOp = caffe2::CUDASparseLengthsSumOp<float, caffe2::CUDAContext, false>; using LengthsMeanCUDAOp = caffe2::CUDASparseLengthsMeanOp<float, caffe2::CUDAContext, false>; using LengthsMaxCUDAOp = caffe2::CUDASparseLengthsMaxOp<float, caffe2::CUDAContext, false>; C10_EXPORT_CAFFE2_OP_TO_C10_CUDA(LengthsSum, LengthsSumCUDAOp); C10_EXPORT_CAFFE2_OP_TO_C10_CUDA(LengthsMean, LengthsMeanCUDAOp); C10_EXPORT_CAFFE2_OP_TO_C10_CUDA(LengthsMax, LengthsMaxCUDAOp); #undef SEGREDUCE_MINBLOCKS
aff335fbaed896bd39c347cb2e97b02449c34356.cu
#include <algorithm> #include "caffe2/core/operator.h" #include "caffe2/operators/segment_reduction_op.h" #include "caffe2/operators/segment_reduction_op_gpu.cuh" #include "caffe2/utils/GpuAtomics.cuh" #include "caffe2/utils/math.h" namespace caffe2 { namespace { void inclusive_scan_wrapper( const int* length_data, int len_length, Tensor* temp_buffer, Tensor* prefix_sum_out, CUDAContext* context_) { // Retrieve buffer size size_t temp_storage_bytes = 0; cub::DeviceScan::InclusiveSum( NULL, temp_storage_bytes, length_data, prefix_sum_out->template mutable_data<int>(), len_length, context_->cuda_stream()); // Allocate temporary storage auto buffer_size = (temp_storage_bytes + sizeof(int)) / sizeof(int); temp_buffer->Resize(buffer_size); void* d_temp_storage = static_cast<void*>(temp_buffer->template mutable_data<int>()); // Run inclusive prefix sum cub::DeviceScan::InclusiveSum( d_temp_storage, temp_storage_bytes, length_data, prefix_sum_out->template mutable_data<int>(), len_length, context_->cuda_stream()); } template <typename T, bool ExactBlock = false, bool Average = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_sum_kernel( const T* __restrict__ in, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { in += threadIdx.x; T sum = (T)0; for (int line = start; line < end; ++line) { sum += in[line * post]; } if (Average && (end - start) > 1) { sum /= (end - start); } out[group * post + threadIdx.x] = sum; } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T sum = (T)0; for (int line = start; line < end; ++line) { sum += in[line * post + i]; } if (Average && (end - start) > 1) { sum /= (end - start); } out[group * post + i] = sum; } } } template <typename T, bool ExactBlock = false, bool Average = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_sum_gradient_kernel( const T* __restrict__ grad_in, T* __restrict__ grad_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { grad_out += threadIdx.x; grad_in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { grad_out[line * post] = grad_in[group * post]; if (Average && (end - start) > 1) { grad_out[line * post] /= (end - start); } } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { for (int line = start; line < end; ++line) { grad_out[line * post + i] = grad_in[group * post + i]; if (Average && (end - start) > 1) { grad_out[line * post + i] /= (end - start); } } } } } template <typename T, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_max_kernel( const T* __restrict__ in, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length, const T numeric_min) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { in += threadIdx.x; T max = numeric_min; for (int line = start; line < end; ++line) { T in_data = in[line * post]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + threadIdx.x] = max; } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T max = numeric_min; for (int line = start; line < end; ++line) { T in_data = in[line * post + i]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + i] = max; } } } template <typename T, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_weighted_sum_gradient_kernel( const T* __restrict__ grad_in, const T* __restrict__ weights_in, T* __restrict__ grad_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { grad_out += threadIdx.x; grad_in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { grad_out[line * post] = weights_in[line] * grad_in[group * post]; } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { for (int line = start; line < end; ++line) { grad_out[line * post + i] = weights_in[line] * grad_in[group * post + i]; } } } } template <typename T, typename IndexType, int NumThreads> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void length_weighted_sum_with_main_input_gradient_kernel( const T* __restrict__ grad_in, const T* __restrict__ weights_in, const T* __restrict__ data_in, const IndexType* __restrict__ indices, T* __restrict__ data_grad_out, T* __restrict__ weights_grad_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); // todo figure this num threads thing typedef cub::BlockReduce<float, NumThreads> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; // TODO(wyiming): parallelize this outter loop for (int line = start; line < end; ++line) { T w_grad = 0; for (int i = threadIdx.x; i < post; i += blockDim.x) { auto g_in = grad_in[group * post + i]; data_grad_out[line * post + i] = weights_in[line] * g_in; w_grad += g_in * data_in[indices[line] * post + i]; } w_grad = BlockReduce(temp_storage).Reduce(w_grad, cub::Sum()); if (threadIdx.x == 0) { weights_grad_out[line] = w_grad; } __syncthreads(); } } template <typename T, typename IndexType, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void sparse_length_max_kernel( const T* __restrict__ in, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, const IndexType* __restrict__ indices, int N, int post, int len_length, int len_indices, const T numeric_min) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= len_indices); CUDA_KERNEL_ASSERT(end <= len_indices); extern __shared__ T reduceVals[]; if (ExactBlock) { T max = numeric_min; in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { T in_data = in[indices[line] * post]; max = max > in_data ? max : in_data; } reduceVals[threadIdx.y * blockDim.x + threadIdx.x] = max; __syncthreads(); if (threadIdx.y == 0) { max = numeric_min; for (int i = 0; i < blockDim.y; ++i) { T in_data = reduceVals[i * blockDim.x + threadIdx.x]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + threadIdx.x] = max; } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T max = numeric_min; for (int line = start; line < end; ++line) { T in_data = in[indices[line] * post + i]; max = max > in_data ? max : in_data; } // setting output to 0 to not break gradient max = max == numeric_min ? 0 : max; out[group * post + i] = max; } } } template <typename T, typename IndexType, bool ExactBlock = false> #ifdef __HIP_PLATFORM_HCC__ C10_LAUNCH_BOUNDS_2(1024, SEGREDUCE_MINBLOCKS) #endif __global__ void sparse_length_weighted_sum_kernel( const T* __restrict__ in, const T* __restrict__ in_weights, T* __restrict__ out, const int* __restrict__ prefix_sum_length_data, const IndexType* __restrict__ indices, int N, int post, int len_length, int len_indices) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= len_indices); CUDA_KERNEL_ASSERT(end <= len_indices); extern __shared__ T reduceVals[]; if (ExactBlock) { T sum = (T)0; in += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { sum += in_weights[line] * in[indices[line] * post]; } reduceVals[threadIdx.y * blockDim.x + threadIdx.x] = sum; __syncthreads(); if (threadIdx.y == 0) { sum = (T)0; for (int i = 0; i < blockDim.y; ++i) { sum += reduceVals[i * blockDim.x + threadIdx.x]; } out[group * post + threadIdx.x] = sum; } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { T sum = (T)0; for (int line = start; line < end; ++line) { sum += in_weights[line] * in[indices[line] * post + i]; } out[group * post + i] = sum; } } } } // namespace template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsSumOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit CUDASparseLengthsSumOp(Args&&... args) : Operator<CUDAContext>(std::forward<Args>(args)...) {} ~CUDASparseLengthsSumOp() {} bool RunOnDevice() override { if (SparseFused) { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } else { // type doesn't matter return DoRunWithType<int32_t>(); } } template <typename IndexType> bool DoRunWithType() { if (SparseFused) { return DispatchHelper<TensorTypes2<float, at::Half>, IndexType>::call( this, Input(DATA)); } else { return DoRunWithType2<IndexType, T>(); } } template <typename IndexType, typename InType> bool DoRunWithType2() { auto& dataInput = Input(DATA); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it int64_t dataToReduceSize; const int64_t outputSize = lengthsInput.dim(0); const int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); T* out_data = output->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } const IndexType* indices; if (SparseFused) { // static if auto& indicesInput = Input(INDICES); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); indices = indicesInput.template data<IndexType>(); dataToReduceSize = indicesInput.dim(0); } else { dataToReduceSize = dataSize; } // only compute this the first time inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (SparseFused) { const InType* in_data = dataInput.template data<InType>(); if (post <= maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; // calling cuda kernel with ExactBlock = true, Average = false sparse_length_sum_kernel<InType, T, IndexType, true, false> <<<len_length, block, smem, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = false sparse_length_sum_kernel<InType, T, IndexType, false, false> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_CUDA_KERNEL_LAUNCH_CHECK(); } } else { const T* in_data = dataInput.template data<T>(); if (post <= maxThreads) { length_sum_kernel<T, true, false> <<<len_length, post, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { length_sum_kernel<T, true, false> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } } return true; } enum { DATA = 0, INDICES = 1, LENGTHS = 1 + (SparseFused ? 1 : 0) }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsMeanOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit CUDASparseLengthsMeanOp(Args&&... args) : Operator<CUDAContext>(std::forward<Args>(args)...) {} ~CUDASparseLengthsMeanOp() {} bool RunOnDevice() override { if (SparseFused) { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } else { // type doesn't matter return DoRunWithType<int32_t>(); } } template <typename IndexType> bool DoRunWithType() { if (SparseFused) { return DispatchHelper<TensorTypes2<float, at::Half>, IndexType>::call( this, Input(DATA)); } else { return DoRunWithType2<IndexType, T>(); } } template <typename IndexType, typename InType> bool DoRunWithType2() { auto& dataInput = Input(DATA); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it int64_t dataToReduceSize; const int64_t outputSize = lengthsInput.dim(0); const int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); T* out_data = output->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } const IndexType* indices; if (SparseFused) { // static if auto& indicesInput = Input(INDICES); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); indices = indicesInput.template data<IndexType>(); dataToReduceSize = indicesInput.dim(0); } else { dataToReduceSize = dataSize; } // only compute this the first time inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (SparseFused) { const InType* in_data = dataInput.template data<InType>(); if (post <= maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; // calling cuda kernel with ExactBlock = true, Average = true sparse_length_sum_kernel<InType, T, IndexType, true, true> <<<len_length, block, smem, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = true sparse_length_sum_kernel<InType, T, IndexType, false, true> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_CUDA_KERNEL_LAUNCH_CHECK(); } } else { const T* in_data = dataInput.template data<T>(); if (post <= maxThreads) { // calling cuda kernel with ExactBlock = true, Average = true length_sum_kernel<T, true, true> <<<len_length, post, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = true, Average = true length_sum_kernel<T, true, true> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } } return true; } enum { DATA = 0, INDICES = 1, LENGTHS = 1 + (SparseFused ? 1 : 0) }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsMaxOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; template <class... Args> explicit CUDASparseLengthsMaxOp(Args&&... args) : Operator<CUDAContext>(std::forward<Args>(args)...) {} ~CUDASparseLengthsMaxOp() {} bool RunOnDevice() override { if (SparseFused) { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } else { // type doesn't matter return DoRunWithType<int32_t>(); } } template <typename IndexType> bool DoRunWithType() { auto& dataInput = Input(0); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it int64_t dataToReduceSize; const int64_t outputSize = lengthsInput.dim(0); int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } const IndexType* indices; if (SparseFused) { // static if auto& indicesInput = Input(INDICES); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); indices = indicesInput.template data<IndexType>(); dataToReduceSize = indicesInput.dim(0); } else { dataToReduceSize = dataSize; } // only compute this the first time inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); const T* in_data = dataInput.template data<T>(); T* out_data = output->template mutable_data<T>(); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; T numeric_min = std::numeric_limits<T>::min(); if (SparseFused) { if (post <= maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; sparse_length_max_kernel<T, IndexType, true> <<<len_length, block, smem, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize, numeric_min); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { sparse_length_max_kernel<T, IndexType, false> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize, numeric_min); C10_CUDA_KERNEL_LAUNCH_CHECK(); } } else { if (post <= maxThreads) { length_max_kernel<T, true> <<<len_length, post, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length, numeric_min); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { length_max_kernel<T, true> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length, numeric_min); C10_CUDA_KERNEL_LAUNCH_CHECK(); } } return true; } enum { INDICES = 1, LENGTHS = 1 + (SparseFused ? 1 : 0) }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext, bool SparseFused = true> class CUDASparseLengthsWeightedSumOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsWeightedSumOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsWeightedSumOp() {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call( this, Input(INDICES)); } template <typename IndexType> bool DoRunWithType() { auto& dataInput = Input(DATA); auto& weightsInput = Input(WEIGHTS); auto& indicesInput = Input(INDICES); auto& lengthsInput = Input(LENGTHS); CAFFE_ENFORCE_EQ(1, weightsInput.dim(), "WEIGHTS must be a vector"); CAFFE_ENFORCE_EQ(1, indicesInput.dim(), "INDICES must be a vector"); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int64_t dataSize = dataInput.dim(0); // Either first dim the data or how much we pull in indexies from it const int64_t dataToReduceSize = indicesInput.dim(0); const int64_t outputSize = lengthsInput.dim(0); const int len_length = outputSize; auto shape = dataInput.sizes().vec(); shape[0] = outputSize; auto* output = Output(0, shape, at::dtype<T>()); T* out_data = output->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); const IndexType* indices = indicesInput.template data<IndexType>(); const T* in_data = dataInput.template data<T>(); const T* in_weights = weightsInput.template data<T>(); auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); int N = dataSize; int post = dataInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); size_t smem = sizeof(T) * post * multiple; sparse_length_weighted_sum_kernel<T, IndexType, true> <<<len_length, block, smem, context_.cuda_stream()>>>( in_data, in_weights, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { sparse_length_weighted_sum_kernel<T, IndexType, false> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, in_weights, out_data, prefix_sum_length_data, indices, N, post, len_length, dataToReduceSize); C10_CUDA_KERNEL_LAUNCH_CHECK(); } return true; } enum { DATA = 0, WEIGHTS = 1, INDICES = 2, LENGTHS = 3 }; private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename SIndex> __global__ void MaxSegmentKernel(int n, const SIndex* segment_ids, SIndex* max_segment) { typedef cub::BlockReduce<SIndex, CAFFE_CUDA_NUM_THREADS> BlockReduce; __shared__ typename BlockReduce::TempStorage temp_storage; int mx = 0; for (int j = threadIdx.x; j < n; j += blockDim.x) { mx = segment_ids[j] > mx ? segment_ids[j] : mx; } SIndex max_seg = BlockReduce(temp_storage).Reduce(mx, cub::Max()); if (threadIdx.x == 0) { *max_segment = max_seg; } } template <typename SIndex, typename T> __global__ void UnsortedSegmentSumKernel( int n, int slize_sz, const SIndex* segments, const T* data, T* out, int* scales) { CUDA_1D_KERNEL_LOOP(i, n) { int slice_idx = i / slize_sz; int j = i % slize_sz; SIndex segment = segments[slice_idx]; gpu_atomic_add(&out[segment * slize_sz + j], data[i]); if (scales && j == 0) { gpu_atomic_add(&scales[segment], 1); } } } template <typename SIndex, typename T> __global__ void SegmentScalingKernel(int m, int slize_sz, const int* scales, T* out) { CUDA_1D_KERNEL_LOOP(i, m) { int scale = scales[i / slize_sz]; out[i] = scale > 0 ? out[i] / scale : 0.0; // avoid 0/0 division } } template <typename T, typename SIndex, bool mean> class CUDAUnsortedSegmentSumOp : public Operator<CUDAContext> { public: USE_OPERATOR_FUNCTIONS(CUDAContext); CUDAUnsortedSegmentSumOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDAUnsortedSegmentSumOp() {} bool RunOnDevice() override { auto& data = Input(0); auto& segment_ids = Input(1); if (segment_ids.numel() == 0 || data.numel() == 0) { // Special handling for empty input auto dims = data.sizes().vec(); if (dims.size() > 0) { dims[0] = 0; } Output(0, dims, at::dtype<T>()); return true; } CAFFE_ENFORCE_EQ(1, segment_ids.dim(), "SEGMENT_IDS must be a vector"); int64_t slize_sz = data.size_from_dim(1); ReinitializeTensor(&K_tensor_, {1}, at::dtype<SIndex>().device(CUDA)); // Get maximum segment id so we can size the output. // This must be done synchronously with host. if (segment_ids.numel() > 4096) { // when the input size is large, device reduce is better. size_t tmp_storage_bytes = 0; // the first call to `Max` do nothing, but set correct tmp_storage_bytes. cub::DeviceReduce::Max( nullptr, tmp_storage_bytes, segment_ids.template data<SIndex>(), // input device data K_tensor_.template mutable_data<SIndex>(), // output device data segment_ids.numel(), // number of items context_.cuda_stream()); // the second call do the real computation. ReinitializeTensor( &buffer_tensor_, {static_cast<int64_t>(tmp_storage_bytes)}, at::dtype<char>().device(CUDA)); cub::DeviceReduce::Max( static_cast<void*>(buffer_tensor_.mutable_data<char>()), tmp_storage_bytes, segment_ids.template data<SIndex>(), // input device data K_tensor_.template mutable_data<SIndex>(), // output device data segment_ids.numel(), // number of items context_.cuda_stream()); } else { MaxSegmentKernel<SIndex> <<<1, CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( segment_ids.numel(), segment_ids.template data<SIndex>(), K_tensor_.mutable_data<SIndex>()); C10_CUDA_KERNEL_LAUNCH_CHECK(); } SIndex K = 0; context_.CopyBytesToCPU( sizeof(SIndex), K_tensor_.template data<SIndex>(), &K); context_.FinishDeviceComputation(); auto dims = data.sizes().vec(); dims[0] = K + 1; auto* output = Output(0, dims, at::dtype<T>()); // Clear the output as we will be accumulating the values math::Set<T, CUDAContext>( output->numel(), T(0), output->template mutable_data<T>(), &context_); if (!mean) { UnsortedSegmentSumKernel<SIndex, T> <<<CAFFE_GET_BLOCKS(data.numel()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( data.numel(), slize_sz, segment_ids.template data<SIndex>(), data.template data<T>(), output->template mutable_data<T>(), nullptr); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { // For mean, we need to compute scaling factors ReinitializeTensor( &scaling_factors_, {K + 1}, at::dtype<int>().device(CUDA)); math::Set<int, CUDAContext>( scaling_factors_.numel(), int(0), scaling_factors_.template mutable_data<int>(), &context_); UnsortedSegmentSumKernel<SIndex, T> <<<CAFFE_GET_BLOCKS(data.numel()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( data.numel(), slize_sz, segment_ids.template data<SIndex>(), data.template data<T>(), output->template mutable_data<T>(), scaling_factors_.template mutable_data<int>()); C10_CUDA_KERNEL_LAUNCH_CHECK(); // Divide by the scaling factors to get means SegmentScalingKernel<SIndex, T> <<<CAFFE_GET_BLOCKS(output->numel()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( output->numel(), slize_sz, scaling_factors_.template data<int>(), output->template mutable_data<T>()); C10_CUDA_KERNEL_LAUNCH_CHECK(); } return true; } private: Tensor buffer_tensor_; Tensor K_tensor_; Tensor scaling_factors_; // for mean }; template <typename SIndex> __global__ void segment_lengths_kernel(int N, const SIndex* X, SIndex* Y) { CUDA_1D_KERNEL_LOOP(i, N) { gpu_atomic_add(&Y[X[i]], 1); } } template <typename T, typename SIndex, bool LOGEXP = false> __global__ void sorted_segment_mean_kernel( const SIndex K, const int N, const SIndex* S, const SIndex* I, const T* X, T* Y) { for (int sId = blockIdx.x; sId < K; sId += gridDim.x) { const int start_index = sId > 0 ? S[sId] * N : 0; const int y_start_index = sId * N; for (int i = threadIdx.x; i < N; i += blockDim.x) { T sum = 0.0; for (int j = 0; j < I[sId]; ++j) { const T x_i_j = X[start_index + j * N + i]; sum += LOGEXP ? exp(x_i_j) : x_i_j; } const T norm_sum = sum / I[sId]; Y[y_start_index + i] = LOGEXP ? log(norm_sum) : norm_sum; } } } template <typename T, typename SIndex, bool LOGEXP, class Context = CUDAContext> class SortedSegmentRangeMeanOp : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; SortedSegmentRangeMeanOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~SortedSegmentRangeMeanOp() {} bool RunOnDevice() override { const auto& input = Input(0); const auto& indices = Input(1); int M = input.dim32(0); int N = input.size_from_dim(1); auto* output = Output(0); auto dims = input.sizes().vec(); SIndex K = 0; context_.CopyBytesToCPU( sizeof(SIndex), indices.template data<SIndex>() + indices.size() - 1, &K); context_.FinishDeviceComputation(); K += 1; dims[0] = K; if (segment_len_.size() != K) { segment_len_.Resize(K); segment_len_prefix_sum_.Resize(K); } output->Resize(dims); math::Set<SIndex, CUDAContext>( segment_len_.size(), 0, segment_len_.template mutable_data<SIndex>(), &context_); segment_lengths_kernel<<< CAFFE_GET_BLOCKS(indices.size()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( indices.size(), indices.template data<SIndex>(), segment_len_.template mutable_data<SIndex>()); C10_CUDA_KERNEL_LAUNCH_CHECK(); size_t temp_storage_bytes = 0; cub::DeviceScan::ExclusiveSum( nullptr, temp_storage_bytes, segment_len_.template data<SIndex>(), segment_len_prefix_sum_.template mutable_data<SIndex>(), K, context_.cuda_stream()); auto buffer_size = (temp_storage_bytes + sizeof(T)) / sizeof(T); prefix_buffer_.Resize(buffer_size); void* dev_temp_storage = static_cast<void*>(prefix_buffer_.mutable_data<T>()); cub::DeviceScan::ExclusiveSum( dev_temp_storage, temp_storage_bytes, segment_len_.template data<SIndex>(), segment_len_prefix_sum_.template mutable_data<SIndex>(), K, context_.cuda_stream()); sorted_segment_mean_kernel<T, SIndex, LOGEXP> <<<std::min(K, CAFFE_MAXIMUM_NUM_BLOCKS), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( K, N, segment_len_prefix_sum_.template data<SIndex>(), segment_len_.template data<SIndex>(), input.template data<T>(), output->template mutable_data<T>()); C10_CUDA_KERNEL_LAUNCH_CHECK(); return true; } private: Tensor segment_len_{CUDA}; // for mean Tensor segment_len_prefix_sum_{CUDA}; Tensor prefix_buffer_{CUDA}; }; template <typename T, typename SIndex, bool LOGEXP = false> __global__ void sorted_segment_mean_gradient_kernel( const int M, const int N, const T* X, const T* Y, const T* dY, const SIndex* I, const SIndex* S, T* dX) { CUDA_1D_KERNEL_LOOP(i, M * N) { const int sId = I[i / N]; const int sSize = S[sId]; const int yId = N * sId + i % N; dX[i] = LOGEXP ? dY[yId] * exp(X[i] - Y[yId]) / sSize : dY[yId] / sSize; } } template <typename T, typename SIndex, bool LOGEXP, class Context = CUDAContext> class SortedSegmentRangeMeanGradientOp : public Operator<Context> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; SortedSegmentRangeMeanGradientOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~SortedSegmentRangeMeanGradientOp() {} bool RunOnDevice() override { const auto& X = Input(0); const auto& Y = Input(1); const auto& dY = Input(2); const auto& I = Input(3); auto* dX = Output(0, X.sizes(), at::dtype<T>()); const int M = X.dim32(0); const int N = X.size_from_dim(1); SIndex K = 0; context_.CopyBytesToCPU( sizeof(SIndex), I.template data<SIndex>() + I.numel() - 1, &K); K += 1; if (segment_len_.numel() != K) { ReinitializeTensor(&segment_len_, {K}, at::dtype<SIndex>().device(CUDA)); } math::Set<SIndex, CUDAContext>( segment_len_.numel(), 0, segment_len_.template mutable_data<SIndex>(), &context_); segment_lengths_kernel<<< CAFFE_GET_BLOCKS(I.numel()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( I.numel(), I.template data<SIndex>(), segment_len_.template mutable_data<SIndex>()); C10_CUDA_KERNEL_LAUNCH_CHECK(); sorted_segment_mean_gradient_kernel<T, SIndex, LOGEXP> <<<CAFFE_GET_BLOCKS(dX->numel()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( M, N, X.template data<T>(), Y.template data<T>(), dY.template data<T>(), I.template data<SIndex>(), segment_len_.template data<SIndex>(), dX->template mutable_data<T>()); C10_CUDA_KERNEL_LAUNCH_CHECK(); return true; } private: Tensor segment_len_; // for mean }; REGISTER_CUDA_OPERATOR_STR( "LengthsSum", CUDASparseLengthsSumOp<float, CUDAContext, false>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsSum", CUDASparseLengthsSumOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "LengthsMean", CUDASparseLengthsMeanOp<float, CUDAContext, false>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsMean", CUDASparseLengthsMeanOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "LengthsMax", CUDASparseLengthsMaxOp<float, CUDAContext, false>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsMax", CUDASparseLengthsMaxOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "SparseLengthsWeightedSum", CUDASparseLengthsWeightedSumOp<float, CUDAContext, true>); REGISTER_CUDA_OPERATOR_STR( "UnsortedSegmentSum", CUDAUnsortedSegmentSumOp<float, int, false>); REGISTER_CUDA_OPERATOR_STR( "UnsortedSegmentMean", CUDAUnsortedSegmentSumOp<float, int, true>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeMean", SortedSegmentRangeMeanOp<float, int, false>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeLogMeanExp", SortedSegmentRangeMeanOp<float, int, true>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeMeanGradient", SortedSegmentRangeMeanGradientOp<float, int, false>); REGISTER_CUDA_OPERATOR_STR( "SortedSegmentRangeLogMeanExpGradient", SortedSegmentRangeMeanGradientOp<float, int, true>); template <typename T, class Context = CUDAContext> class CUDASparseLengthsSumGradientWithIndicesOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsSumGradientWithIndicesOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsSumGradientWithIndicesOp() {} bool RunOnDevice() override { auto& segmentGradsInput = Input(0); auto& lengthsInput = Input(1); auto& indicesInput = Input(2); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); T* out_data = dataGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = segmentGradsInput.template data<T>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); // calling cuda kernel with ExactBlock = true, Average = false length_sum_gradient_kernel<T, true, false> <<<len_length, block, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = false length_sum_gradient_kernel<T, false, false> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext> class CUDASparseLengthsMeanGradientWithIndicesOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsMeanGradientWithIndicesOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsMeanGradientWithIndicesOp() {} bool RunOnDevice() override { auto& segmentGradsInput = Input(0); auto& lengthsInput = Input(1); auto& indicesInput = Input(2); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); T* out_data = dataGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = segmentGradsInput.template data<T>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); // calling cuda kernel with ExactBlock = true, Average = true length_sum_gradient_kernel<T, true, true> <<<len_length, block, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { // calling cuda kernel with ExactBlock = false, Average = true length_sum_gradient_kernel<T, false, true> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext> class CUDASparseLengthsWeightedSumGradientWithIndicesOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsWeightedSumGradientWithIndicesOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsWeightedSumGradientWithIndicesOp() {} bool RunOnDevice() override { auto& weightsInput = Input(0); auto& segmentGradsInput = Input(1); auto& lengthsInput = Input(2); auto& indicesInput = Input(3); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); CAFFE_ENFORCE_EQ(1, weightsInput.dim(), "WEIGHTS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); T* out_data = dataGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = segmentGradsInput.template data<T>(); const T* in_weights = weightsInput.template data<T>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post < maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); length_weighted_sum_gradient_kernel<T, true> <<<len_length, block, 0, context_.cuda_stream()>>>( in_data, in_weights, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { length_weighted_sum_gradient_kernel<T, false> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, in_weights, out_data, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, bool ExactBlock = false> __global__ void length_max_gradient_kernel( const T* __restrict__ grad_in, T* __restrict__ grad_out, const T* data_in, const T* data_out, const int* __restrict__ prefix_sum_length_data, int N, int post, int len_length) { // len_length blocks int group = blockIdx.x; int start = group == 0 ? 0 : prefix_sum_length_data[group - 1]; int end = prefix_sum_length_data[group]; CUDA_KERNEL_ASSERT(start <= N); CUDA_KERNEL_ASSERT(end <= N); if (ExactBlock) { grad_out += threadIdx.x; grad_in += threadIdx.x; data_in += threadIdx.x; data_out += threadIdx.x; for (int line = start + threadIdx.y; line < end; line += blockDim.y) { if (data_in[line * post] == data_out[group * post]) { grad_out[line * post] = grad_in[group * post]; } else { grad_out[line * post] = 0; } } } else { for (int i = threadIdx.x; i < post; i += blockDim.x) { for (int line = start; line < end; ++line) { if (data_in[line * post + i] == data_out[group * post + i]) { grad_out[line * post + i] = grad_in[group * post + i]; } else { grad_out[line * post + i] = 0; } } } } } template <typename T, class Context = CUDAContext> class CUDALengthsMaxWithMainInputAndForwardOutputGradientOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDALengthsMaxWithMainInputAndForwardOutputGradientOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDALengthsMaxWithMainInputAndForwardOutputGradientOp() {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<int32_t, float>>::call(this, Input(3)); } template <typename IndexType> bool DoRunWithType() { auto& segmentGradsInput = Input(1); auto& lengthsInput = Input(2); auto& dataInput = Input(3); auto& dataOutput = Input(0); // based on CPU version CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); auto shape = dataInput.sizes().vec(); auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); const T* in_data = segmentGradsInput.template data<T>(); T* out_data = dataGradsOutput->template mutable_data<T>(); int N = dataInput.dim(0); int post = segmentGradsInput.size_from_dim(1); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } auto maxThreads = GetDeviceProperty(CaffeCudaGetDevice()).maxThreadsPerBlock; if (post <= maxThreads) { int multiple = std::min(maxThreads / post, SEGREDUCE_MINBLOCKS); dim3 block(post, multiple); length_max_gradient_kernel<T, true> <<<len_length, block, 0, context_.cuda_stream()>>>( in_data, out_data, dataInput.template data<T>(), dataOutput.template data<T>(), prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { length_max_gradient_kernel<T, false> <<<len_length, maxThreads, 0, context_.cuda_stream()>>>( in_data, out_data, dataInput.template data<T>(), dataOutput.template data<T>(), prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; template <typename T, class Context = CUDAContext> class CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp : public Operator<CUDAContext> { public: USE_OPERATOR_CONTEXT_FUNCTIONS; CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp( const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws) {} ~CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp() {} bool RunOnDevice() override { return DispatchHelper<TensorTypes<int32_t, int64_t>>::call(this, Input(4)); } template <typename IndexType> bool DoRunWithType() { auto& weightsInput = Input(0); auto& segmentGradsInput = Input(1); auto& lengthsInput = Input(2); auto& dataInput = Input(3); auto& indicesInput = Input(4); CAFFE_ENFORCE_EQ(1, lengthsInput.dim(), "LENGTHS must be a vector"); CAFFE_ENFORCE_EQ(1, weightsInput.dim(), "WEIGHTS must be a vector"); const int len_length = lengthsInput.dim(0); CAFFE_ENFORCE(segmentGradsInput.dim() > 0); CAFFE_ENFORCE(len_length == segmentGradsInput.dim(0)); auto shape = segmentGradsInput.sizes().vec(); int output_0dim = indicesInput.dim(0); shape[0] = output_0dim; auto* dataGradsOutput = Output(0, shape, at::dtype<T>()); auto* weightGradsOutput = Output(1, indicesInput.sizes(), at::dtype<T>()); T* out_data_grads = dataGradsOutput->template mutable_data<T>(); T* out_weight_grads = weightGradsOutput->template mutable_data<T>(); if (len_length <= 0) { // return early to avoid invalid empty kernel return true; } inclusive_scan_length_buffer_.ResizeLike(lengthsInput); inclusive_scan_wrapper( lengthsInput.template data<int>(), len_length, &inclusive_scan_buffer_, &inclusive_scan_length_buffer_, &context_); // compute output size using length auto* prefix_sum_length_data = inclusive_scan_length_buffer_.template data<int>(); const T* in_data = dataInput.template data<T>(); const T* in_grads = segmentGradsInput.template data<T>(); const T* in_weights = weightsInput.template data<T>(); const IndexType* indices = indicesInput.template data<IndexType>(); int N = output_0dim; int post = segmentGradsInput.size_from_dim(1); if (post > 128) { length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 512> <<<len_length, 512, 0, context_.cuda_stream()>>>( in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else if (post > 64) { length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 128> <<<len_length, 128, 0, context_.cuda_stream()>>>( in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else if (post > 32) { length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 64> <<<len_length, 64, 0, context_.cuda_stream()>>>( in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } else { length_weighted_sum_with_main_input_gradient_kernel<T, IndexType, 32> <<<len_length, 32, 0, context_.cuda_stream()>>>( in_grads, in_weights, in_data, indices, out_data_grads, out_weight_grads, prefix_sum_length_data, N, post, len_length); C10_CUDA_KERNEL_LAUNCH_CHECK(); } return true; } private: // menber field to manage memory Tensor inclusive_scan_buffer_{CUDA}; Tensor inclusive_scan_length_buffer_{CUDA}; }; // Needed because name is auto-generated in segment_reduction_op.cc:224 REGISTER_CUDA_OPERATOR_STR( "LengthsMaxWithMainInputAndForwardOutputGradient", CUDALengthsMaxWithMainInputAndForwardOutputGradientOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientWeightedSumGradient, CUDASparseLengthsWeightedSumGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientWeightedSumWithMainInputGradient, CUDASparseLengthsIndicesInGradientWeightedSumWithMainInputGradientOp< float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientSumGradient, CUDASparseLengthsSumGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( LengthsIndicesInGradientSumGradient, CUDASparseLengthsSumGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( SparseLengthsIndicesInGradientMeanGradient, CUDASparseLengthsMeanGradientWithIndicesOp<float, CUDAContext>); REGISTER_CUDA_OPERATOR( LengthsIndicesInGradientMeanGradient, CUDASparseLengthsMeanGradientWithIndicesOp<float, CUDAContext>); } // namespace caffe2 // Macro doesn't like comma using LengthsSumCUDAOp = caffe2::CUDASparseLengthsSumOp<float, caffe2::CUDAContext, false>; using LengthsMeanCUDAOp = caffe2::CUDASparseLengthsMeanOp<float, caffe2::CUDAContext, false>; using LengthsMaxCUDAOp = caffe2::CUDASparseLengthsMaxOp<float, caffe2::CUDAContext, false>; C10_EXPORT_CAFFE2_OP_TO_C10_CUDA(LengthsSum, LengthsSumCUDAOp); C10_EXPORT_CAFFE2_OP_TO_C10_CUDA(LengthsMean, LengthsMeanCUDAOp); C10_EXPORT_CAFFE2_OP_TO_C10_CUDA(LengthsMax, LengthsMaxCUDAOp); #undef SEGREDUCE_MINBLOCKS
2d38b095b1739c23b6812cc367a88f85ed1b70f0.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> // Function that catches the error void testCUDA(hipError_t error, const char *file, int line){ if (error != hipSuccess){ printf("Error in file %s at line %d \n", file , line); exit(EXIT_FAILURE); } } // Has to be define in the compilation in order to get the correct value of // of the values __FILE__ and __LINE__ #define testCUDA(error) (testCUDA(error, __FILE__,__LINE__)) __global__ void empty_k(void){ } int main (void){ int count; hipDeviceProp_t prop; hipLaunchKernelGGL(( empty_k), dim3(1),dim3(1), 0, 0, ); testCUDA(hipGetDeviceCount(&count)); printf("The number of devices available is %i GPUs \n", count); testCUDA(hipGetDeviceProperties(&prop, count-1)); printf("Name %s\n", prop.name); printf("Global memory size in octet (bytes): %1d \n", prop.totalGlobalMem); printf("Shared memory size per block: %i\n", prop.sharedMemPerBlock); printf("Number of registers per block: %i\n", prop.regsPerBlock); printf("Number of threads in a warp: %i\n", prop.warpSize); printf("Maximum number of threads that can be launched per block: %i \n", prop.maxThreadsPerBlock); printf("Maximum number of threads that can be launched: %i X %i X %i\n", prop.maxThreadsDim[0],prop.maxThreadsDim[1], prop.maxThreadsDim[2]); printf("Maximum grid size: %i X %i X %i\n", prop.maxGridSize[0], prop.maxGridSize[1],prop.maxGridSize[2]); printf("Total Constant Memory Size: %1d\n", prop.totalConstMem); printf("Major Compute capability: %i\n", prop.major); printf("Minor Compute capability: %i\n", prop.minor); printf("Clock Rate : %i\n", prop.clockRate); printf("Maximum 1D texture memory: %i\n", prop.maxTexture1D); printf("Could we overlap? %i \n", prop.deviceOverlap); printf("Number of multiprocessors: %i \n", prop.multiProcessorCount); printf("Is there a limit for kernel execution? %i \n", prop.kernelExecTimeoutEnabled); printf("Is my GPU a chipset? %i\n", prop.integrated); printf("Can we map the host memory? %i \n", prop.canMapHostMemory); printf("Can we launch concurrent kernels: %i\n", prop.concurrentKernels); printf("Do we have ECC memory %i\n", prop.ECCEnabled); return 0; }
2d38b095b1739c23b6812cc367a88f85ed1b70f0.cu
#include <stdio.h> // Function that catches the error void testCUDA(cudaError_t error, const char *file, int line){ if (error != cudaSuccess){ printf("Error in file %s at line %d \n", file , line); exit(EXIT_FAILURE); } } // Has to be define in the compilation in order to get the correct value of // of the values __FILE__ and __LINE__ #define testCUDA(error) (testCUDA(error, __FILE__,__LINE__)) __global__ void empty_k(void){ } int main (void){ int count; cudaDeviceProp prop; empty_k<<<1,1>>>(); testCUDA(cudaGetDeviceCount(&count)); printf("The number of devices available is %i GPUs \n", count); testCUDA(cudaGetDeviceProperties(&prop, count-1)); printf("Name %s\n", prop.name); printf("Global memory size in octet (bytes): %1d \n", prop.totalGlobalMem); printf("Shared memory size per block: %i\n", prop.sharedMemPerBlock); printf("Number of registers per block: %i\n", prop.regsPerBlock); printf("Number of threads in a warp: %i\n", prop.warpSize); printf("Maximum number of threads that can be launched per block: %i \n", prop.maxThreadsPerBlock); printf("Maximum number of threads that can be launched: %i X %i X %i\n", prop.maxThreadsDim[0],prop.maxThreadsDim[1], prop.maxThreadsDim[2]); printf("Maximum grid size: %i X %i X %i\n", prop.maxGridSize[0], prop.maxGridSize[1],prop.maxGridSize[2]); printf("Total Constant Memory Size: %1d\n", prop.totalConstMem); printf("Major Compute capability: %i\n", prop.major); printf("Minor Compute capability: %i\n", prop.minor); printf("Clock Rate : %i\n", prop.clockRate); printf("Maximum 1D texture memory: %i\n", prop.maxTexture1D); printf("Could we overlap? %i \n", prop.deviceOverlap); printf("Number of multiprocessors: %i \n", prop.multiProcessorCount); printf("Is there a limit for kernel execution? %i \n", prop.kernelExecTimeoutEnabled); printf("Is my GPU a chipset? %i\n", prop.integrated); printf("Can we map the host memory? %i \n", prop.canMapHostMemory); printf("Can we launch concurrent kernels: %i\n", prop.concurrentKernels); printf("Do we have ECC memory %i\n", prop.ECCEnabled); return 0; }
cdf6f16b6d79437791e66ad7937aa4f4ec3ac18c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "FEM.h" #include <Eigen/Dense> #include <Eigen/Sparse> #include <cmath> #include <vector> #include <memory> #include <fstream> #include <ctime> #include "GaussPoints.h" #include "ShapeFunctions.h" #include "Quadtree.h" using namespace std; using namespace Eigen; __device__ __host__ int CeilDiv(int a, int b) { return (a-1)/b + 1; } __device__ __host__ int CeilAlign(int a, int b) { return CeilDiv(a, b) * b; } #define BLOCK_SIZE 256 #define BLOCK_WARP 8 void FEM::MeshRefinement() { PhiCoordinateList.clear(); UCoordinateList.clear(); PhiVelocityCoordinateList.clear(); UVelocityCoordinateList.clear(); for (int i = 0; i < PHI.rows(); i++) { PhiCoordinateList[NodeCoordinates[i]] = PHI(i); UCoordinateList[NodeCoordinates[i]] = U(i); PhiVelocityCoordinateList[NodeCoordinates[i]] = PHIvelocity(i); UVelocityCoordinateList[NodeCoordinates[i]] = Uvelocity(i); } Quadtree_MeshGenerate(maxLv, gamma, LevelElementList, 10, PhiCoordinateList, UCoordinateList, PhiVelocityCoordinateList, UVelocityCoordinateList); // case = 10 Quadtree_AddNodes(LevelElementList, NodeCoordinateList); ReportElement(LevelElementList, FinalElementList, NodeCoordinateList, EFT, NodeCoordinates); ncSize = NodeCoordinates.size(); elemSize = EFT.size(); PHI.setZero(ncSize); U.setZero(ncSize); Theta.setZero(ncSize); PHIvelocity.setZero(ncSize); Uvelocity.setZero(ncSize); for (unsigned i = 0; i < ncSize; i++) { PHI(i) = PhiCoordinateList[NodeCoordinates[i]]; U(i) = UCoordinateList[NodeCoordinates[i]]; Theta(i) = 0; PHIvelocity(i) = PhiVelocityCoordinateList[NodeCoordinates[i]]; Uvelocity(i) = UVelocityCoordinateList[NodeCoordinates[i]]; } //fout_time << endl; //fout_time << EFT.size() << "\tElements" << endl; //fout_time << NodeCoordinateList.size() << "\tNodes" << endl; //fout_time << endl; hipFree(aPHI); hipFree(aU); hipFree(aEFT); hipFree(aNodeNum); hipFree(elementType); hipFree(aCoordX); hipFree(aCoordY); hipMalloc(&aPHI, sizeof(double)*ncSize); hipMalloc(&aU, sizeof(double)*ncSize); hipMallocManaged(&aEFT, sizeof(int)*elemSize*8); //Element at max 8 nodes hipMallocManaged(&aNodeNum, sizeof(int)*elemSize); hipMallocManaged(&elementType, sizeof(unsigned char)*elemSize); hipMallocManaged(&aCoordX, sizeof(double)*ncSize); hipMallocManaged(&aCoordY, sizeof(double)*ncSize); // copy EFT to array for(int i = 0; i < elemSize; ++i){ aNodeNum[i] = EFT[i].size(); for(int j = 0; j < EFT[i].size(); ++j){ aEFT[i * 8+j] = EFT[i][j]; } elementType[i] = (unsigned char)FinalElementList[i]->bitElementType.to_ulong(); } //copy elementType to array for(int i = 0; i < ncSize; ++i){ aCoordX[i] = NodeCoordinates[i].x; aCoordY[i] = NodeCoordinates[i].y; } // device pointer hipFree(adM11); hipFree(adM21); hipFree(adM22); hipFree(adK11); hipFree(adK21); hipFree(adK22); hipFree(adF1); hipMallocManaged((void **)&adM11, sizeof(float)*elemSize*64); hipMallocManaged((void **)&adM21, sizeof(float)*elemSize*64); hipMallocManaged((void **)&adM22, sizeof(float)*elemSize*64); hipMallocManaged((void **)&adK11, sizeof(float)*elemSize*64); hipMallocManaged((void **)&adK21, sizeof(float)*elemSize*64); hipMallocManaged((void **)&adK22, sizeof(float)*elemSize*64); hipMallocManaged((void **)&adF1, sizeof(float)*ncSize*4); delete[] matPosX; delete[] matPosY; matPosX = new int[elemSize*64]; matPosY = new int[elemSize*64]; for(int e = 0; e < elemSize; ++e){ int nNode = EFT[e].size(); for(int i = 0; i < 8; ++i){ for(int j = 0; j < 8; ++j){ int idx = e*64 + i*8 + j; if(i < nNode && j < nNode){ matPosX[idx] = EFT[e][i]; matPosY[idx] = EFT[e][j]; } else { matPosX[idx] = 0; matPosY[idx] = 0; } } } } mM11.resize(ncSize, ncSize); mM21.resize(ncSize, ncSize); mM22.resize(ncSize, ncSize); mK11.resize(ncSize, ncSize); mK21.resize(ncSize, ncSize); mK22.resize(ncSize, ncSize); } __device__ __host__ RowVectorXf cuShapeFunction(float xi, float eta, unsigned char bitElementType) { //RowVectorXf shape(numberOfNodes); float Ni [8] = {(1 - xi) * (1 - eta) / 4, (1 + xi) * (1 - eta) / 4, (1 + xi) * (1 + eta) / 4, (1 - xi) * (1 + eta) / 4, (1 - xi*xi) * (1 - eta) / 2, (1 - eta*eta) * (1 + xi) / 2, (1 - xi*xi) * (1 + eta) / 2, (1 - eta*eta) * (1 - xi) / 2}; RowVectorXf shape(8); switch((int)bitElementType){ //Q8 case(255): //11111111 break; //Q7 case(127): //01111111 Ni[7] = 0; shape.resize(7); break; case(191): //10111111 Ni[6] = 0; shape.resize(7); break; case(223): //11011111 Ni[5] = 0; shape.resize(7); break; case(239): //11101111 Ni[4] = 0; shape.resize(7); break; //Q6 case(63): //00111111 Ni[7] = Ni[6] = 0; shape.resize(6); break; case(159): //10011111 Ni[6] = Ni[5] = 0; shape.resize(6); break; case(207): //11001111 Ni[5] = Ni[4] = 0; shape.resize(6); break; case(111): //01101111 Ni[4] = Ni[7] = 0; shape.resize(6); break; case(175): //10101111 Ni[6] = Ni[4] = 0; shape.resize(6); break; case(95): //01011111 Ni[7] = Ni[5] = 0; shape.resize(6); break; //Q5 case(31): //00011111 Ni[7] = Ni[6] = Ni[5] = 0; shape.resize(5); break; case(143): //10001111 Ni[6] = Ni[5] = Ni[4] = 0; shape.resize(5); break; case(79): //01001111 Ni[7] = Ni[5] = Ni[4] = 0; shape.resize(5); break; case(47): //00101111 Ni[7] = Ni[6] = Ni[4] = 0; shape.resize(5); break; //Q4 case(15): //00001111 Ni[7] = Ni[6] = Ni[5] = Ni[4] = 0; shape.resize(4); break; } int cnt=4; for (int i = 4;i<8;++i) if (bitElementType&(1<<i)) shape(cnt++)=Ni[i]; shape(3) = Ni[3] - (Ni[6] + Ni[7]) / 2; shape(2) = Ni[2] - (Ni[5] + Ni[6]) / 2; shape(1) = Ni[1] - (Ni[4] + Ni[5]) / 2; shape(0) = Ni[0] - (Ni[7] + Ni[4]) / 2; return shape; } __device__ __host__ MatrixXf cuNaturalDerivatives(float xi, float eta, unsigned char bitElementType) { MatrixXf naturalDerivatives(2,8); float Ni_xi[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; float Ni_eta[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Ni_xi[4] = - xi * (1 - eta); Ni_eta[4] = -(1 - xi*xi) / 2; Ni_xi[5] = (1 - eta*eta) / 2; Ni_eta[5] = - eta * (1 + xi); Ni_xi[6] = - xi * (1 + eta); Ni_eta[6] = (1 - xi*xi) / 2; Ni_xi[7] = -(1 - eta*eta) / 2; Ni_eta[7] = - eta * (1 - xi); switch((int)bitElementType){ //Q8 case(255): //11111111 break; //Q7 case(127): //01111111 Ni_xi[7] = 0; Ni_eta[7] = 0; naturalDerivatives.resize(2,7); break; case(191): //10111111 Ni_xi[6] = 0; Ni_eta[6] = 0; naturalDerivatives.resize(2,7); break; case(223): //11011111 Ni_xi[5] = 0; Ni_eta[5] = 0; naturalDerivatives.resize(2,7); break; case(239): //11101111 Ni_xi[4] = 0; Ni_eta[4] = 0; naturalDerivatives.resize(2,7); break; //Q6 case(63): //00111111 Ni_xi[7] = Ni_xi[6] = 0; Ni_eta[7] = Ni_eta[6] = 0; naturalDerivatives.resize(2,6); break; case(159): //10011111 Ni_xi[6] = Ni_xi[5] = 0; Ni_eta[6] = Ni_eta[5] = 0; naturalDerivatives.resize(2,6); break; case(207): //11001111 Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,6); break; case(111): //01101111 Ni_xi[4] = Ni_xi[7] = 0; Ni_eta[4] = Ni_eta[7] = 0; naturalDerivatives.resize(2,6); break; case(175): //10101111 Ni_xi[6] = Ni_xi[4] = 0; Ni_eta[6] = Ni_eta[4] = 0; naturalDerivatives.resize(2,6); break; case(95): //01011111 Ni_xi[7] = Ni_xi[5] = 0; Ni_eta[7] = Ni_eta[5] = 0; naturalDerivatives.resize(2,6); break; //Q5 case(31): //00011111 Ni_xi[7] = Ni_xi[6] = Ni_xi[5] = 0; Ni_eta[7] = Ni_eta[6] = Ni_eta[5] = 0; naturalDerivatives.resize(2,5); break; case(143): //10001111 Ni_xi[6] = Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[6] = Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,5); break; case(79): //01001111 Ni_xi[7] = Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[7] = Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,5); break; case(47): //00101111 Ni_xi[7] = Ni_xi[6] = Ni_xi[4] = 0; Ni_eta[7] = Ni_eta[6] = Ni_eta[4] = 0; naturalDerivatives.resize(2,5); break; //Q4 case(15): //00001111 Ni_xi[7] = Ni_xi[6] = Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[7] = Ni_eta[6] = Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,4); break; } int cnt = 4; for (int i=4; i<8; ++i) { if (bitElementType & ( 1 << i ) ) { naturalDerivatives(0,cnt) = Ni_xi[i]; naturalDerivatives(1,cnt) = Ni_eta[i]; ++cnt; } } naturalDerivatives(0,0) = -(1 - eta) / 4 - (Ni_xi[7] + Ni_xi[4]) / 2; naturalDerivatives(1,0) = -(1 - xi) / 4 - (Ni_eta[7] + Ni_eta[4]) / 2; naturalDerivatives(0,1) = (1 - eta) / 4 - (Ni_xi[4] + Ni_xi[5]) / 2; naturalDerivatives(1,1) = -(1 + xi) / 4 - (Ni_eta[4] + Ni_eta[5]) / 2; naturalDerivatives(0,2) = (1 + eta) / 4 - (Ni_xi[5] + Ni_xi[6]) / 2; naturalDerivatives(1,2) = (1 + xi) / 4 - (Ni_eta[5] + Ni_eta[6]) / 2; naturalDerivatives(0,3) = -(1 + eta) / 4 - (Ni_xi[6] + Ni_xi[7]) / 2; naturalDerivatives(1,3) = (1 - xi) / 4 - (Ni_eta[6] + Ni_eta[7]) / 2; return naturalDerivatives; } __device__ float determinant(const Matrix2f& target){ return target(0,0)*target(1,1)-target(0,1)*target(1,0); } __device__ Matrix2f inverse(const Matrix2f& target){ float det=determinant(target); Matrix2f inv; inv(0,0)=target(1,1)/det; inv(1,1)=target(0,0)/det; inv(0,1)=-target(0,1)/det; inv(1,0)=-target(1,0)/det; return inv; } __device__ Matrix2f cuJacobian(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return naturalDerivatives * nodeCoord; } __device__ Matrix2f cuinvJacobian(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return inverse(cuJacobian(nodeCoord,naturalDerivatives)); } __device__ MatrixXf cuXYDerivatives(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return cuinvJacobian(nodeCoord,naturalDerivatives) * naturalDerivatives; } __device__ float cudetJacobian(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return determinant(cuJacobian(nodeCoord,naturalDerivatives)); } __device__ __host__ MatrixXf cu_get_cotangent(const VectorXf& phi, const MatrixXf& B) { //////////////////////////////////////////////////////////////////////// // phi = / phi1 \ B = / N1,x N2,x N3,x N4,x \ cot = / DERX \ // // | phi2 | \ N1,y N2,y N3,y N4,y / \ DERY / // // | phi3 | // // \ phi4 / // //////////////////////////////////////////////////////////////////////// return B * phi; // 2x1 } // g'(phi) - lambda*U*P'(phi) __device__ __host__ float cuF(float phi, float u, float theta, float lambda) { return phi * (1 - phi*phi) - lambda * u * pow(1 - phi*phi, 2.0); //return phi * (1 - phi*phi) - lambda * pow(1 - phi*phi, 2.0) * (u + 0.9 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta + 0.3 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); } __device__ __host__ float cuQ(float phi, float k) { //return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi); return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi) + (1 + phi) * 0.2 / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2 + (1 + phi) * 0.2 / 2; } __global__ void cu_element( float lambda, float tloop, float epsilon, const double* aPHI, const double* aU, const int* aEFT, const int* aNodeNum, const unsigned char* elementType, const double* aCoordX, const double* aCoordY, float* aM11, float* aM21, float* aM22, float* aK11, float* aK21, float* aK22, float* aF1, int ncSize, int elemSize ){ int e = blockIdx.x * blockDim.x + threadIdx.x; if (e >= elemSize) return; const float PI = 3.14159265358979323846; float C_inf = 3; // (wt%) float k = 0.14; // float G = 140 * 40; // (K/cm) float d0 = 5E-3; // (1E-6m) float alpha = 3000; // (1E-6m2/s) float Vp = 3000; // (1E-6m/s) float Ts = 273; // (K) float dT0 = 2.6 * C_inf * (1 - k) / k; // (K) float T0 = Ts - dT0 / 10; // (K) float a1 = 0.8839; float a2 = 0.6267; float W0 = d0 * lambda / a1; // (1E-6m) float Tau0 = a2 * lambda * W0 * W0 / alpha; // (s) float D = lambda * a2; // Gaussian point const float xis[4] = {-0.577350269189626, 0.577350269189626, 0.577350269189626, -0.577350269189626}; const float etas[4] = {-0.577350269189626, -0.577350269189626, 0.577350269189626, 0.577350269189626}; int m = 6; float RealTime = Tau0 * tloop; // (s) int numNodePerElement = aNodeNum[e]; unsigned char bitElementType = elementType[e]; MatrixXf elementNodesCoord(numNodePerElement,2); VectorXf phi(numNodePerElement); VectorXf u(numNodePerElement); for (unsigned i = 0; i < numNodePerElement; i++) { int nodeSerial = aEFT[e*8 + i]; elementNodesCoord(i, 0) = aCoordX[nodeSerial]; elementNodesCoord(i, 1) = aCoordY[nodeSerial]; phi(i) = aPHI[nodeSerial]; u(i) = aU[nodeSerial]; } MatrixXf Ce = MatrixXf::Zero(numNodePerElement, numNodePerElement); MatrixXf Ae = MatrixXf::Zero(numNodePerElement, numNodePerElement); MatrixXf Ee = MatrixXf::Zero(numNodePerElement, numNodePerElement); VectorXf Fe = VectorXf::Zero(numNodePerElement); // n x 1 RowVectorXf N0 = cuShapeFunction(0, 0, bitElementType); MatrixXf dN0 = cuNaturalDerivatives(0, 0, bitElementType); // 2 x n MatrixXf B0 = cuXYDerivatives(elementNodesCoord, dN0); // 2 x n MatrixXf cotangent = cu_get_cotangent(phi, B0); // 2 x 1 float DERX = cotangent(0); float DERY = cotangent(1); float angle = atan2(DERY, DERX); float as = 1 + epsilon * cos(m*(angle - PI / 6)); // A(theta) float asp = -m * epsilon * sin(m*(angle - PI / 6)); // A'(theta) float col1 = 0; for(int i = 0; i < N0.size(); ++i){ col1 += N0(i) * elementNodesCoord(i, 1); } float Temperature = T0 + G * 1E2 * (W0 * col1 - Vp*RealTime) * 1E-6; // (K) float theta = (Temperature - Ts) / dT0; int nGp = 4; for (int q=0; q<nGp; q++) { float xi = xis[q]; float eta = etas[q]; float W = 1; RowVectorXf N = cuShapeFunction(xi, eta, bitElementType); // 1 x n MatrixXf dN = cuNaturalDerivatives(xi, eta, bitElementType); // 2 x n MatrixXf B = cuXYDerivatives(elementNodesCoord, dN); // 2 x n float J = cudetJacobian(elementNodesCoord, dN); // 1 x 1 // matrixs of a element Ce += N.transpose() * N * W * J; // n x n Ae -= B.transpose() * B * W * J; // n x n Ee -= (B.row(1).transpose()*B.row(0) - B.row(0).transpose()*B.row(1)) * W * J; // n x n float Nphi = 0; float Nu = 0; for(int i = 0; i < N.size(); ++i){ Nphi += N(i) * phi(i); Nu += N(i) * u(i); } Fe += N.transpose() * cuF(Nphi, Nu, theta, lambda) * W * J; // n x 1 } int site[8] = {0}; // int ElementTypeToSite[8] = {2, 3, 0, 1, 2, 3, 0, 1}; int ElementTypeToSite[8] = {0, 1, 2, 3, 0, 1, 2, 3}; int cnt = 0; for(int i = 0; i < 8; ++i){ if(bitElementType & (1 << i)){ site[cnt] = ElementTypeToSite[i]; ++cnt; } } for (unsigned i=0; i<numNodePerElement; i++) { int x = aEFT[e * 8 + i]; for (unsigned j=0; j<numNodePerElement; j++) { int y = aEFT[e * 8 + j]; int idx = e*64 + i*8 + j; if (Ce(i, j) > 1.0E-12 || Ce(i, j) < -1.0E-12) { aM22[idx] = Ce(i, j); aM21[idx] = -0.5*Ce(i, j); aM11[idx] = as * as * Ce(i, j); } if ((Ae(i, j) > 1.0E-12 || Ae(i, j) < -1.0E-12) && (Ee(i, j) > 1.0E-12 || Ee(i, j) < -1.0E-12)){ float N0phi = 0; for(int i = 0; i < N0.size(); ++i){ N0phi += N0(i) * phi(i); } aK22[idx] = -D * cuQ(N0phi, 0.7) * Ae(i, j); aK11[idx] = -as * as * Ae(i, j) -as * asp * Ee(i, j); } else{ if (Ae(i, j) > 1.0E-12 || Ae(i, j) < -1.0E-12) { float N0phi = 0; for(int i = 0; i < N0.size(); ++i){ N0phi += N0(i) * phi(i); } aK22[idx] = -D * cuQ(N0phi, 0.7) * Ae(i, j); aK11[idx] = -as * as * Ae(i, j); } if (Ee(i, j) > 1.0E-12 || Ee(i, j) < -1.0E-12) aK11[idx] = -as * asp * Ee(i, j); } } if (Fe(i) > 1.0E-12 || Fe(i) < -1.0E-12) aF1[x+ncSize*site[i]] = Fe(i); } } __global__ void cu_sum(float* adF1, size_t ncSize){ size_t idx = blockIdx.x * blockDim.x + threadIdx.x; if(idx >= ncSize) return; int s = ncSize; for(int i = 1; i < 4; ++i){ adF1[idx] += adF1[idx + s*i]; } } void FEM::cu_find_matrixs(float lambda, float epsilon, unsigned tloop, float dt){ hipMemcpy(aPHI, PHI.data(), sizeof(double)*ncSize, hipMemcpyHostToDevice); hipMemcpy(aU, U.data(), sizeof(double)*ncSize, hipMemcpyHostToDevice); hipMemset(adM11, 0, sizeof(float)*elemSize*64); hipMemset(adM21, 0, sizeof(float)*elemSize*64); hipMemset(adM22, 0, sizeof(float)*elemSize*64); hipMemset(adK11, 0, sizeof(float)*elemSize*64); hipMemset(adK21, 0, sizeof(float)*elemSize*64); hipMemset(adK22, 0, sizeof(float)*elemSize*64); hipMemset(adF1, 0, sizeof(float)*ncSize*4); int blockSize = 256; hipLaunchKernelGGL(( cu_element), dim3(CeilDiv(elemSize, blockSize)), dim3(blockSize), 0, 0, lambda, tloop, epsilon, aPHI, aU, aEFT, aNodeNum, elementType, aCoordX, aCoordY, adM11, adM21, adM22, adK11, adK21, adK22, adF1, ncSize, elemSize); hipDeviceSynchronize(); hipLaunchKernelGGL(( cu_sum), dim3(CeilDiv(ncSize, blockSize)), dim3(blockSize), 0, 0, adF1, ncSize); hipDeviceSynchronize(); mM11.setZero(); mM21.setZero(); mM22.setZero(); mK11.setZero(); mK21.setZero(); mK22.setZero(); typedef Triplet<double> T; vector<T> tM11, tM21, tM22, tK11, tK21, tK22; for(int i = 0; i < elemSize*64; ++i){ int x = matPosX[i]; int y = matPosY[i]; tM11.push_back(T(x, y, adM11[i])); tM21.push_back(T(x, y, adM21[i])); tM22.push_back(T(x, y, adM22[i])); tK11.push_back(T(x, y, adK11[i])); tK21.push_back(T(x, y, adK21[i])); tK22.push_back(T(x, y, adK22[i])); } mM11.setFromTriplets(tM11.begin(), tM11.end()); mM21.setFromTriplets(tM21.begin(), tM21.end()); mM22.setFromTriplets(tM22.begin(), tM22.end()); mK11.setFromTriplets(tK11.begin(), tK11.end()); mK21.setFromTriplets(tK21.begin(), tK21.end()); mK22.setFromTriplets(tK22.begin(), tK22.end()); } void FEM::time_discretization( double lambda, double epsilon, unsigned tloop, double dt) { clock_t t; clock_t solver_time = 0; clock_t matrix_time = 0; clock_t scheme_time = 0; t = clock(); //-> solver BiCGSTAB<SparseMatrix<double> > solver; solver_time += clock() - t; //<- solver /////////////////////////////////////////////////////////////////////////////////////////////////// t = clock(); //-> scheme double rho = 0; double rhos = 0; double W1L4 = 1 / (1 + rho); double W1L6 = (3 + rho + rhos - rho*rhos) / (2 * (1 + rho) * (1 + rhos)); double lambda4 = 1; double lambda5 = 1 / (1 + rhos); unsigned nNode = ncSize; typedef Triplet<double> T; vector<T> tripletList_q; vector<T> tripletList_Up, tripletList_Down, tripletList_Left, tripletList_Right; for (unsigned i = 0; i < nNode; i++) { tripletList_Up.push_back(T(i, i, 1)); tripletList_Down.push_back(T(i + nNode, i, 1)); tripletList_Left.push_back(T(i, i, 1)); tripletList_Right.push_back(T(i, i + nNode, 1)); } SparseMatrix<double> Up(nNode * 2, nNode); Up.setFromTriplets(tripletList_Up.begin(), tripletList_Up.end()); SparseMatrix<double> Down(nNode * 2, nNode); Down.setFromTriplets(tripletList_Down.begin(), tripletList_Down.end()); SparseMatrix<double> Left(nNode, nNode * 2); Left.setFromTriplets(tripletList_Left.begin(), tripletList_Left.end()); SparseMatrix<double> Right(nNode, nNode * 2); Right.setFromTriplets(tripletList_Right.begin(), tripletList_Right.end()); VectorXd d1 = Up * PHI + Down * U; VectorXd v1; if (tloop == 0) { PHIvelocity *= 0; cu_find_matrixs(lambda, epsilon, tloop, dt); VectorXd vF1 = Map<VectorXf>(adF1, ncSize).cast<double>(); SparseMatrix<double> M = Up*(mM11)*Left + Down*(mM21)*Left + Down*(mM22)*Right; SparseMatrix<double> K = Up*(mK11)*Left + Down*(mK21)*Left + Down*(mK22)*Right; VectorXd F = Up * vF1; v1 = solver.compute(M).solve(F - K*d1); } else { v1 = Up * PHIvelocity + Down * Uvelocity; } VectorXd d_telda = d1 + W1L4 * v1 * dt; PHI = d_telda.topRows(nNode); U = d_telda.bottomRows(nNode); scheme_time += clock() - t; //<- scheme cu_find_matrixs(lambda, epsilon, tloop, dt); // find_matrixs(lambda, epsilon, tloop, dt); VectorXd vF1 = Map<VectorXf>(adF1, ncSize).cast<double>(); // cout << vF1 << endl; // exit(1); matrix_time += clock() - t; //<- matrix t = clock(); //-> scheme SparseMatrix<double> M = Up*(mM11)*Left + Down*(mM21)*Left + Down*(mM22)*Right; SparseMatrix<double> K = Up*(mK11)*Left + Down*(mK21)*Left + Down*(mK22)*Right; VectorXd F = Up * vF1; scheme_time += clock() - t; //<- scheme t = clock(); //-> solver VectorXd v_telda = solver.compute( M ).solve( F - K*d_telda ); solver_time += clock() - t; //<- solver t = clock(); //-> scheme VectorXd dv = (-v1 + v_telda) / W1L6; VectorXd d2 = d1 + lambda4 * v1 * dt + lambda5 * dv * dt; VectorXd v2 = v1 + dv; PHI = d2.topRows(nNode); U = d2.bottomRows(nNode); PHIvelocity = v2.topRows(nNode); Uvelocity = v2.bottomRows(nNode); scheme_time += clock() - t; //<- scheme //fout_time << "\tmatrix: " << 1.*matrix_time/CLOCKS_PER_SEC << " sec" << endl; //fout_time << "\tsolver: " << 1.*solver_time/CLOCKS_PER_SEC << " sec" << endl; //fout_time << "\tscheme: " << 1.*scheme_time/CLOCKS_PER_SEC << " sec" << endl; //cout << "\tmatrix: " << 1.*matrix_time/CLOCKS_PER_SEC << " sec" << endl; //cout << "\tsolver: " << 1.*solver_time/CLOCKS_PER_SEC << " sec" << endl; //cout << "\tscheme: " << 1.*scheme_time/CLOCKS_PER_SEC << " sec" << endl; } __device__ __host__ MatrixXd get_cotangent(const VectorXd& phi, const MatrixXd& B) { //////////////////////////////////////////////////////////////////////// // phi = / phi1 \ B = / N1,x N2,x N3,x N4,x \ cot = / DERX \ // // | phi2 | \ N1,y N2,y N3,y N4,y / \ DERY / // // | phi3 | // // \ phi4 / // //////////////////////////////////////////////////////////////////////// return B * phi; // 2x1 } // g'(phi) - lambda*U*P'(phi) __device__ __host__ double f(double phi, double u, double theta, double lambda) { return phi * (1 - phi*phi) - lambda * u * pow(1 - phi*phi, 2.0); //return phi * (1 - phi*phi) - lambda * pow(1 - phi*phi, 2.0) * (u + 0.9 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta + 0.3 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); } __device__ __host__ double q(double phi, double k) { //return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi); return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi) + (1 + phi) * 0.2 / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2 + (1 + phi) * 0.2 / 2; }
cdf6f16b6d79437791e66ad7937aa4f4ec3ac18c.cu
#include "FEM.h" #include <Eigen/Dense> #include <Eigen/Sparse> #include <cmath> #include <vector> #include <memory> #include <fstream> #include <ctime> #include "GaussPoints.h" #include "ShapeFunctions.h" #include "Quadtree.h" using namespace std; using namespace Eigen; __device__ __host__ int CeilDiv(int a, int b) { return (a-1)/b + 1; } __device__ __host__ int CeilAlign(int a, int b) { return CeilDiv(a, b) * b; } #define BLOCK_SIZE 256 #define BLOCK_WARP 8 void FEM::MeshRefinement() { PhiCoordinateList.clear(); UCoordinateList.clear(); PhiVelocityCoordinateList.clear(); UVelocityCoordinateList.clear(); for (int i = 0; i < PHI.rows(); i++) { PhiCoordinateList[NodeCoordinates[i]] = PHI(i); UCoordinateList[NodeCoordinates[i]] = U(i); PhiVelocityCoordinateList[NodeCoordinates[i]] = PHIvelocity(i); UVelocityCoordinateList[NodeCoordinates[i]] = Uvelocity(i); } Quadtree_MeshGenerate(maxLv, gamma, LevelElementList, 10, PhiCoordinateList, UCoordinateList, PhiVelocityCoordinateList, UVelocityCoordinateList); // case = 10 Quadtree_AddNodes(LevelElementList, NodeCoordinateList); ReportElement(LevelElementList, FinalElementList, NodeCoordinateList, EFT, NodeCoordinates); ncSize = NodeCoordinates.size(); elemSize = EFT.size(); PHI.setZero(ncSize); U.setZero(ncSize); Theta.setZero(ncSize); PHIvelocity.setZero(ncSize); Uvelocity.setZero(ncSize); for (unsigned i = 0; i < ncSize; i++) { PHI(i) = PhiCoordinateList[NodeCoordinates[i]]; U(i) = UCoordinateList[NodeCoordinates[i]]; Theta(i) = 0; PHIvelocity(i) = PhiVelocityCoordinateList[NodeCoordinates[i]]; Uvelocity(i) = UVelocityCoordinateList[NodeCoordinates[i]]; } //fout_time << endl; //fout_time << EFT.size() << "\tElements" << endl; //fout_time << NodeCoordinateList.size() << "\tNodes" << endl; //fout_time << endl; cudaFree(aPHI); cudaFree(aU); cudaFree(aEFT); cudaFree(aNodeNum); cudaFree(elementType); cudaFree(aCoordX); cudaFree(aCoordY); cudaMalloc(&aPHI, sizeof(double)*ncSize); cudaMalloc(&aU, sizeof(double)*ncSize); cudaMallocManaged(&aEFT, sizeof(int)*elemSize*8); //Element at max 8 nodes cudaMallocManaged(&aNodeNum, sizeof(int)*elemSize); cudaMallocManaged(&elementType, sizeof(unsigned char)*elemSize); cudaMallocManaged(&aCoordX, sizeof(double)*ncSize); cudaMallocManaged(&aCoordY, sizeof(double)*ncSize); // copy EFT to array for(int i = 0; i < elemSize; ++i){ aNodeNum[i] = EFT[i].size(); for(int j = 0; j < EFT[i].size(); ++j){ aEFT[i * 8+j] = EFT[i][j]; } elementType[i] = (unsigned char)FinalElementList[i]->bitElementType.to_ulong(); } //copy elementType to array for(int i = 0; i < ncSize; ++i){ aCoordX[i] = NodeCoordinates[i].x; aCoordY[i] = NodeCoordinates[i].y; } // device pointer cudaFree(adM11); cudaFree(adM21); cudaFree(adM22); cudaFree(adK11); cudaFree(adK21); cudaFree(adK22); cudaFree(adF1); cudaMallocManaged((void **)&adM11, sizeof(float)*elemSize*64); cudaMallocManaged((void **)&adM21, sizeof(float)*elemSize*64); cudaMallocManaged((void **)&adM22, sizeof(float)*elemSize*64); cudaMallocManaged((void **)&adK11, sizeof(float)*elemSize*64); cudaMallocManaged((void **)&adK21, sizeof(float)*elemSize*64); cudaMallocManaged((void **)&adK22, sizeof(float)*elemSize*64); cudaMallocManaged((void **)&adF1, sizeof(float)*ncSize*4); delete[] matPosX; delete[] matPosY; matPosX = new int[elemSize*64]; matPosY = new int[elemSize*64]; for(int e = 0; e < elemSize; ++e){ int nNode = EFT[e].size(); for(int i = 0; i < 8; ++i){ for(int j = 0; j < 8; ++j){ int idx = e*64 + i*8 + j; if(i < nNode && j < nNode){ matPosX[idx] = EFT[e][i]; matPosY[idx] = EFT[e][j]; } else { matPosX[idx] = 0; matPosY[idx] = 0; } } } } mM11.resize(ncSize, ncSize); mM21.resize(ncSize, ncSize); mM22.resize(ncSize, ncSize); mK11.resize(ncSize, ncSize); mK21.resize(ncSize, ncSize); mK22.resize(ncSize, ncSize); } __device__ __host__ RowVectorXf cuShapeFunction(float xi, float eta, unsigned char bitElementType) { //RowVectorXf shape(numberOfNodes); float Ni [8] = {(1 - xi) * (1 - eta) / 4, (1 + xi) * (1 - eta) / 4, (1 + xi) * (1 + eta) / 4, (1 - xi) * (1 + eta) / 4, (1 - xi*xi) * (1 - eta) / 2, (1 - eta*eta) * (1 + xi) / 2, (1 - xi*xi) * (1 + eta) / 2, (1 - eta*eta) * (1 - xi) / 2}; RowVectorXf shape(8); switch((int)bitElementType){ //Q8 case(255): //11111111 break; //Q7 case(127): //01111111 Ni[7] = 0; shape.resize(7); break; case(191): //10111111 Ni[6] = 0; shape.resize(7); break; case(223): //11011111 Ni[5] = 0; shape.resize(7); break; case(239): //11101111 Ni[4] = 0; shape.resize(7); break; //Q6 case(63): //00111111 Ni[7] = Ni[6] = 0; shape.resize(6); break; case(159): //10011111 Ni[6] = Ni[5] = 0; shape.resize(6); break; case(207): //11001111 Ni[5] = Ni[4] = 0; shape.resize(6); break; case(111): //01101111 Ni[4] = Ni[7] = 0; shape.resize(6); break; case(175): //10101111 Ni[6] = Ni[4] = 0; shape.resize(6); break; case(95): //01011111 Ni[7] = Ni[5] = 0; shape.resize(6); break; //Q5 case(31): //00011111 Ni[7] = Ni[6] = Ni[5] = 0; shape.resize(5); break; case(143): //10001111 Ni[6] = Ni[5] = Ni[4] = 0; shape.resize(5); break; case(79): //01001111 Ni[7] = Ni[5] = Ni[4] = 0; shape.resize(5); break; case(47): //00101111 Ni[7] = Ni[6] = Ni[4] = 0; shape.resize(5); break; //Q4 case(15): //00001111 Ni[7] = Ni[6] = Ni[5] = Ni[4] = 0; shape.resize(4); break; } int cnt=4; for (int i = 4;i<8;++i) if (bitElementType&(1<<i)) shape(cnt++)=Ni[i]; shape(3) = Ni[3] - (Ni[6] + Ni[7]) / 2; shape(2) = Ni[2] - (Ni[5] + Ni[6]) / 2; shape(1) = Ni[1] - (Ni[4] + Ni[5]) / 2; shape(0) = Ni[0] - (Ni[7] + Ni[4]) / 2; return shape; } __device__ __host__ MatrixXf cuNaturalDerivatives(float xi, float eta, unsigned char bitElementType) { MatrixXf naturalDerivatives(2,8); float Ni_xi[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; float Ni_eta[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; Ni_xi[4] = - xi * (1 - eta); Ni_eta[4] = -(1 - xi*xi) / 2; Ni_xi[5] = (1 - eta*eta) / 2; Ni_eta[5] = - eta * (1 + xi); Ni_xi[6] = - xi * (1 + eta); Ni_eta[6] = (1 - xi*xi) / 2; Ni_xi[7] = -(1 - eta*eta) / 2; Ni_eta[7] = - eta * (1 - xi); switch((int)bitElementType){ //Q8 case(255): //11111111 break; //Q7 case(127): //01111111 Ni_xi[7] = 0; Ni_eta[7] = 0; naturalDerivatives.resize(2,7); break; case(191): //10111111 Ni_xi[6] = 0; Ni_eta[6] = 0; naturalDerivatives.resize(2,7); break; case(223): //11011111 Ni_xi[5] = 0; Ni_eta[5] = 0; naturalDerivatives.resize(2,7); break; case(239): //11101111 Ni_xi[4] = 0; Ni_eta[4] = 0; naturalDerivatives.resize(2,7); break; //Q6 case(63): //00111111 Ni_xi[7] = Ni_xi[6] = 0; Ni_eta[7] = Ni_eta[6] = 0; naturalDerivatives.resize(2,6); break; case(159): //10011111 Ni_xi[6] = Ni_xi[5] = 0; Ni_eta[6] = Ni_eta[5] = 0; naturalDerivatives.resize(2,6); break; case(207): //11001111 Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,6); break; case(111): //01101111 Ni_xi[4] = Ni_xi[7] = 0; Ni_eta[4] = Ni_eta[7] = 0; naturalDerivatives.resize(2,6); break; case(175): //10101111 Ni_xi[6] = Ni_xi[4] = 0; Ni_eta[6] = Ni_eta[4] = 0; naturalDerivatives.resize(2,6); break; case(95): //01011111 Ni_xi[7] = Ni_xi[5] = 0; Ni_eta[7] = Ni_eta[5] = 0; naturalDerivatives.resize(2,6); break; //Q5 case(31): //00011111 Ni_xi[7] = Ni_xi[6] = Ni_xi[5] = 0; Ni_eta[7] = Ni_eta[6] = Ni_eta[5] = 0; naturalDerivatives.resize(2,5); break; case(143): //10001111 Ni_xi[6] = Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[6] = Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,5); break; case(79): //01001111 Ni_xi[7] = Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[7] = Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,5); break; case(47): //00101111 Ni_xi[7] = Ni_xi[6] = Ni_xi[4] = 0; Ni_eta[7] = Ni_eta[6] = Ni_eta[4] = 0; naturalDerivatives.resize(2,5); break; //Q4 case(15): //00001111 Ni_xi[7] = Ni_xi[6] = Ni_xi[5] = Ni_xi[4] = 0; Ni_eta[7] = Ni_eta[6] = Ni_eta[5] = Ni_eta[4] = 0; naturalDerivatives.resize(2,4); break; } int cnt = 4; for (int i=4; i<8; ++i) { if (bitElementType & ( 1 << i ) ) { naturalDerivatives(0,cnt) = Ni_xi[i]; naturalDerivatives(1,cnt) = Ni_eta[i]; ++cnt; } } naturalDerivatives(0,0) = -(1 - eta) / 4 - (Ni_xi[7] + Ni_xi[4]) / 2; naturalDerivatives(1,0) = -(1 - xi) / 4 - (Ni_eta[7] + Ni_eta[4]) / 2; naturalDerivatives(0,1) = (1 - eta) / 4 - (Ni_xi[4] + Ni_xi[5]) / 2; naturalDerivatives(1,1) = -(1 + xi) / 4 - (Ni_eta[4] + Ni_eta[5]) / 2; naturalDerivatives(0,2) = (1 + eta) / 4 - (Ni_xi[5] + Ni_xi[6]) / 2; naturalDerivatives(1,2) = (1 + xi) / 4 - (Ni_eta[5] + Ni_eta[6]) / 2; naturalDerivatives(0,3) = -(1 + eta) / 4 - (Ni_xi[6] + Ni_xi[7]) / 2; naturalDerivatives(1,3) = (1 - xi) / 4 - (Ni_eta[6] + Ni_eta[7]) / 2; return naturalDerivatives; } __device__ float determinant(const Matrix2f& target){ return target(0,0)*target(1,1)-target(0,1)*target(1,0); } __device__ Matrix2f inverse(const Matrix2f& target){ float det=determinant(target); Matrix2f inv; inv(0,0)=target(1,1)/det; inv(1,1)=target(0,0)/det; inv(0,1)=-target(0,1)/det; inv(1,0)=-target(1,0)/det; return inv; } __device__ Matrix2f cuJacobian(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return naturalDerivatives * nodeCoord; } __device__ Matrix2f cuinvJacobian(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return inverse(cuJacobian(nodeCoord,naturalDerivatives)); } __device__ MatrixXf cuXYDerivatives(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return cuinvJacobian(nodeCoord,naturalDerivatives) * naturalDerivatives; } __device__ float cudetJacobian(const MatrixXf& nodeCoord, const MatrixXf& naturalDerivatives) { return determinant(cuJacobian(nodeCoord,naturalDerivatives)); } __device__ __host__ MatrixXf cu_get_cotangent(const VectorXf& phi, const MatrixXf& B) { //////////////////////////////////////////////////////////////////////// // phi = / phi1 \ B = / N1,x N2,x N3,x N4,x \ cot = / DERX \ // // | phi2 | \ N1,y N2,y N3,y N4,y / \ DERY / // // | phi3 | // // \ phi4 / // //////////////////////////////////////////////////////////////////////// return B * phi; // 2x1 } // g'(phi) - lambda*U*P'(phi) __device__ __host__ float cuF(float phi, float u, float theta, float lambda) { return phi * (1 - phi*phi) - lambda * u * pow(1 - phi*phi, 2.0); //return phi * (1 - phi*phi) - lambda * pow(1 - phi*phi, 2.0) * (u + 0.9 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta + 0.3 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); } __device__ __host__ float cuQ(float phi, float k) { //return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi); return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi) + (1 + phi) * 0.2 / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2 + (1 + phi) * 0.2 / 2; } __global__ void cu_element( float lambda, float tloop, float epsilon, const double* aPHI, const double* aU, const int* aEFT, const int* aNodeNum, const unsigned char* elementType, const double* aCoordX, const double* aCoordY, float* aM11, float* aM21, float* aM22, float* aK11, float* aK21, float* aK22, float* aF1, int ncSize, int elemSize ){ int e = blockIdx.x * blockDim.x + threadIdx.x; if (e >= elemSize) return; const float PI = 3.14159265358979323846; float C_inf = 3; // (wt%) float k = 0.14; // float G = 140 * 40; // (K/cm) float d0 = 5E-3; // (1E-6m) float alpha = 3000; // (1E-6m2/s) float Vp = 3000; // (1E-6m/s) float Ts = 273; // (K) float dT0 = 2.6 * C_inf * (1 - k) / k; // (K) float T0 = Ts - dT0 / 10; // (K) float a1 = 0.8839; float a2 = 0.6267; float W0 = d0 * lambda / a1; // (1E-6m) float Tau0 = a2 * lambda * W0 * W0 / alpha; // (s) float D = lambda * a2; // Gaussian point const float xis[4] = {-0.577350269189626, 0.577350269189626, 0.577350269189626, -0.577350269189626}; const float etas[4] = {-0.577350269189626, -0.577350269189626, 0.577350269189626, 0.577350269189626}; int m = 6; float RealTime = Tau0 * tloop; // (s) int numNodePerElement = aNodeNum[e]; unsigned char bitElementType = elementType[e]; MatrixXf elementNodesCoord(numNodePerElement,2); VectorXf phi(numNodePerElement); VectorXf u(numNodePerElement); for (unsigned i = 0; i < numNodePerElement; i++) { int nodeSerial = aEFT[e*8 + i]; elementNodesCoord(i, 0) = aCoordX[nodeSerial]; elementNodesCoord(i, 1) = aCoordY[nodeSerial]; phi(i) = aPHI[nodeSerial]; u(i) = aU[nodeSerial]; } MatrixXf Ce = MatrixXf::Zero(numNodePerElement, numNodePerElement); MatrixXf Ae = MatrixXf::Zero(numNodePerElement, numNodePerElement); MatrixXf Ee = MatrixXf::Zero(numNodePerElement, numNodePerElement); VectorXf Fe = VectorXf::Zero(numNodePerElement); // n x 1 RowVectorXf N0 = cuShapeFunction(0, 0, bitElementType); MatrixXf dN0 = cuNaturalDerivatives(0, 0, bitElementType); // 2 x n MatrixXf B0 = cuXYDerivatives(elementNodesCoord, dN0); // 2 x n MatrixXf cotangent = cu_get_cotangent(phi, B0); // 2 x 1 float DERX = cotangent(0); float DERY = cotangent(1); float angle = atan2(DERY, DERX); float as = 1 + epsilon * cos(m*(angle - PI / 6)); // A(theta) float asp = -m * epsilon * sin(m*(angle - PI / 6)); // A'(theta) float col1 = 0; for(int i = 0; i < N0.size(); ++i){ col1 += N0(i) * elementNodesCoord(i, 1); } float Temperature = T0 + G * 1E2 * (W0 * col1 - Vp*RealTime) * 1E-6; // (K) float theta = (Temperature - Ts) / dT0; int nGp = 4; for (int q=0; q<nGp; q++) { float xi = xis[q]; float eta = etas[q]; float W = 1; RowVectorXf N = cuShapeFunction(xi, eta, bitElementType); // 1 x n MatrixXf dN = cuNaturalDerivatives(xi, eta, bitElementType); // 2 x n MatrixXf B = cuXYDerivatives(elementNodesCoord, dN); // 2 x n float J = cudetJacobian(elementNodesCoord, dN); // 1 x 1 // matrixs of a element Ce += N.transpose() * N * W * J; // n x n Ae -= B.transpose() * B * W * J; // n x n Ee -= (B.row(1).transpose()*B.row(0) - B.row(0).transpose()*B.row(1)) * W * J; // n x n float Nphi = 0; float Nu = 0; for(int i = 0; i < N.size(); ++i){ Nphi += N(i) * phi(i); Nu += N(i) * u(i); } Fe += N.transpose() * cuF(Nphi, Nu, theta, lambda) * W * J; // n x 1 } int site[8] = {0}; // int ElementTypeToSite[8] = {2, 3, 0, 1, 2, 3, 0, 1}; int ElementTypeToSite[8] = {0, 1, 2, 3, 0, 1, 2, 3}; int cnt = 0; for(int i = 0; i < 8; ++i){ if(bitElementType & (1 << i)){ site[cnt] = ElementTypeToSite[i]; ++cnt; } } for (unsigned i=0; i<numNodePerElement; i++) { int x = aEFT[e * 8 + i]; for (unsigned j=0; j<numNodePerElement; j++) { int y = aEFT[e * 8 + j]; int idx = e*64 + i*8 + j; if (Ce(i, j) > 1.0E-12 || Ce(i, j) < -1.0E-12) { aM22[idx] = Ce(i, j); aM21[idx] = -0.5*Ce(i, j); aM11[idx] = as * as * Ce(i, j); } if ((Ae(i, j) > 1.0E-12 || Ae(i, j) < -1.0E-12) && (Ee(i, j) > 1.0E-12 || Ee(i, j) < -1.0E-12)){ float N0phi = 0; for(int i = 0; i < N0.size(); ++i){ N0phi += N0(i) * phi(i); } aK22[idx] = -D * cuQ(N0phi, 0.7) * Ae(i, j); aK11[idx] = -as * as * Ae(i, j) -as * asp * Ee(i, j); } else{ if (Ae(i, j) > 1.0E-12 || Ae(i, j) < -1.0E-12) { float N0phi = 0; for(int i = 0; i < N0.size(); ++i){ N0phi += N0(i) * phi(i); } aK22[idx] = -D * cuQ(N0phi, 0.7) * Ae(i, j); aK11[idx] = -as * as * Ae(i, j); } if (Ee(i, j) > 1.0E-12 || Ee(i, j) < -1.0E-12) aK11[idx] = -as * asp * Ee(i, j); } } if (Fe(i) > 1.0E-12 || Fe(i) < -1.0E-12) aF1[x+ncSize*site[i]] = Fe(i); } } __global__ void cu_sum(float* adF1, size_t ncSize){ size_t idx = blockIdx.x * blockDim.x + threadIdx.x; if(idx >= ncSize) return; int s = ncSize; for(int i = 1; i < 4; ++i){ adF1[idx] += adF1[idx + s*i]; } } void FEM::cu_find_matrixs(float lambda, float epsilon, unsigned tloop, float dt){ cudaMemcpy(aPHI, PHI.data(), sizeof(double)*ncSize, cudaMemcpyHostToDevice); cudaMemcpy(aU, U.data(), sizeof(double)*ncSize, cudaMemcpyHostToDevice); cudaMemset(adM11, 0, sizeof(float)*elemSize*64); cudaMemset(adM21, 0, sizeof(float)*elemSize*64); cudaMemset(adM22, 0, sizeof(float)*elemSize*64); cudaMemset(adK11, 0, sizeof(float)*elemSize*64); cudaMemset(adK21, 0, sizeof(float)*elemSize*64); cudaMemset(adK22, 0, sizeof(float)*elemSize*64); cudaMemset(adF1, 0, sizeof(float)*ncSize*4); int blockSize = 256; cu_element<<<CeilDiv(elemSize, blockSize), blockSize>>>(lambda, tloop, epsilon, aPHI, aU, aEFT, aNodeNum, elementType, aCoordX, aCoordY, adM11, adM21, adM22, adK11, adK21, adK22, adF1, ncSize, elemSize); cudaDeviceSynchronize(); cu_sum<<<CeilDiv(ncSize, blockSize), blockSize>>>(adF1, ncSize); cudaDeviceSynchronize(); mM11.setZero(); mM21.setZero(); mM22.setZero(); mK11.setZero(); mK21.setZero(); mK22.setZero(); typedef Triplet<double> T; vector<T> tM11, tM21, tM22, tK11, tK21, tK22; for(int i = 0; i < elemSize*64; ++i){ int x = matPosX[i]; int y = matPosY[i]; tM11.push_back(T(x, y, adM11[i])); tM21.push_back(T(x, y, adM21[i])); tM22.push_back(T(x, y, adM22[i])); tK11.push_back(T(x, y, adK11[i])); tK21.push_back(T(x, y, adK21[i])); tK22.push_back(T(x, y, adK22[i])); } mM11.setFromTriplets(tM11.begin(), tM11.end()); mM21.setFromTriplets(tM21.begin(), tM21.end()); mM22.setFromTriplets(tM22.begin(), tM22.end()); mK11.setFromTriplets(tK11.begin(), tK11.end()); mK21.setFromTriplets(tK21.begin(), tK21.end()); mK22.setFromTriplets(tK22.begin(), tK22.end()); } void FEM::time_discretization( double lambda, double epsilon, unsigned tloop, double dt) { clock_t t; clock_t solver_time = 0; clock_t matrix_time = 0; clock_t scheme_time = 0; t = clock(); //-> solver BiCGSTAB<SparseMatrix<double> > solver; solver_time += clock() - t; //<- solver /////////////////////////////////////////////////////////////////////////////////////////////////// t = clock(); //-> scheme double rho = 0; double rhos = 0; double W1L4 = 1 / (1 + rho); double W1L6 = (3 + rho + rhos - rho*rhos) / (2 * (1 + rho) * (1 + rhos)); double lambda4 = 1; double lambda5 = 1 / (1 + rhos); unsigned nNode = ncSize; typedef Triplet<double> T; vector<T> tripletList_q; vector<T> tripletList_Up, tripletList_Down, tripletList_Left, tripletList_Right; for (unsigned i = 0; i < nNode; i++) { tripletList_Up.push_back(T(i, i, 1)); tripletList_Down.push_back(T(i + nNode, i, 1)); tripletList_Left.push_back(T(i, i, 1)); tripletList_Right.push_back(T(i, i + nNode, 1)); } SparseMatrix<double> Up(nNode * 2, nNode); Up.setFromTriplets(tripletList_Up.begin(), tripletList_Up.end()); SparseMatrix<double> Down(nNode * 2, nNode); Down.setFromTriplets(tripletList_Down.begin(), tripletList_Down.end()); SparseMatrix<double> Left(nNode, nNode * 2); Left.setFromTriplets(tripletList_Left.begin(), tripletList_Left.end()); SparseMatrix<double> Right(nNode, nNode * 2); Right.setFromTriplets(tripletList_Right.begin(), tripletList_Right.end()); VectorXd d1 = Up * PHI + Down * U; VectorXd v1; if (tloop == 0) { PHIvelocity *= 0; cu_find_matrixs(lambda, epsilon, tloop, dt); VectorXd vF1 = Map<VectorXf>(adF1, ncSize).cast<double>(); SparseMatrix<double> M = Up*(mM11)*Left + Down*(mM21)*Left + Down*(mM22)*Right; SparseMatrix<double> K = Up*(mK11)*Left + Down*(mK21)*Left + Down*(mK22)*Right; VectorXd F = Up * vF1; v1 = solver.compute(M).solve(F - K*d1); } else { v1 = Up * PHIvelocity + Down * Uvelocity; } VectorXd d_telda = d1 + W1L4 * v1 * dt; PHI = d_telda.topRows(nNode); U = d_telda.bottomRows(nNode); scheme_time += clock() - t; //<- scheme cu_find_matrixs(lambda, epsilon, tloop, dt); // find_matrixs(lambda, epsilon, tloop, dt); VectorXd vF1 = Map<VectorXf>(adF1, ncSize).cast<double>(); // cout << vF1 << endl; // exit(1); matrix_time += clock() - t; //<- matrix t = clock(); //-> scheme SparseMatrix<double> M = Up*(mM11)*Left + Down*(mM21)*Left + Down*(mM22)*Right; SparseMatrix<double> K = Up*(mK11)*Left + Down*(mK21)*Left + Down*(mK22)*Right; VectorXd F = Up * vF1; scheme_time += clock() - t; //<- scheme t = clock(); //-> solver VectorXd v_telda = solver.compute( M ).solve( F - K*d_telda ); solver_time += clock() - t; //<- solver t = clock(); //-> scheme VectorXd dv = (-v1 + v_telda) / W1L6; VectorXd d2 = d1 + lambda4 * v1 * dt + lambda5 * dv * dt; VectorXd v2 = v1 + dv; PHI = d2.topRows(nNode); U = d2.bottomRows(nNode); PHIvelocity = v2.topRows(nNode); Uvelocity = v2.bottomRows(nNode); scheme_time += clock() - t; //<- scheme //fout_time << "\tmatrix: " << 1.*matrix_time/CLOCKS_PER_SEC << " sec" << endl; //fout_time << "\tsolver: " << 1.*solver_time/CLOCKS_PER_SEC << " sec" << endl; //fout_time << "\tscheme: " << 1.*scheme_time/CLOCKS_PER_SEC << " sec" << endl; //cout << "\tmatrix: " << 1.*matrix_time/CLOCKS_PER_SEC << " sec" << endl; //cout << "\tsolver: " << 1.*solver_time/CLOCKS_PER_SEC << " sec" << endl; //cout << "\tscheme: " << 1.*scheme_time/CLOCKS_PER_SEC << " sec" << endl; } __device__ __host__ MatrixXd get_cotangent(const VectorXd& phi, const MatrixXd& B) { //////////////////////////////////////////////////////////////////////// // phi = / phi1 \ B = / N1,x N2,x N3,x N4,x \ cot = / DERX \ // // | phi2 | \ N1,y N2,y N3,y N4,y / \ DERY / // // | phi3 | // // \ phi4 / // //////////////////////////////////////////////////////////////////////// return B * phi; // 2x1 } // g'(phi) - lambda*U*P'(phi) __device__ __host__ double f(double phi, double u, double theta, double lambda) { return phi * (1 - phi*phi) - lambda * u * pow(1 - phi*phi, 2.0); //return phi * (1 - phi*phi) - lambda * pow(1 - phi*phi, 2.0) * (u + 0.9 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta); //return phi * (1 - phi*phi) - lambda * pow((1 - phi*phi), 2.0) * (u + theta + 0.3 * phi * (1 - phi*phi) * ((double(rand()) / RAND_MAX) - 0.5)); } __device__ __host__ double q(double phi, double k) { //return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi); return (phi >= 1) ? 0 : (1 - phi) / (1 + k - (1 - k) * phi) + (1 + phi) * 0.2 / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2; //return (phi >= 1) ? 0 : (1 - phi) / 2 + (1 + phi) * 0.2 / 2; }
52c521a72aca27bc6984e8f1c83e352502d28611.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "caffe2/operators/top_k.h" #include <algorithm> #include <array> #include <functional> #include <limits> #include <numeric> #include <vector> #include <thrust/sort.h> #include <thrust/system/hip/execution_policy.h> #include "caffe2/core/context.h" #include "caffe2/core/context_gpu.h" #include "caffe2/operators/top_k_heap_selection.cuh" #include "caffe2/operators/top_k_radix_selection.cuh" #include "caffe2/utils/math.h" namespace caffe2 { namespace { template <typename T, int kHeapSize, bool kSelectMax = true> void RunHeapSelectionImpl( const T* input, const TIndex outer_size, const TIndex inner_size, const int k, T* values, TIndex* indices, CUDAContext* context) { constexpr int kBlockSize = 256; constexpr int kNumWarps = kBlockSize / kWarpSize; constexpr int smem = kNumWarps * kHeapSize * (sizeof(T) + sizeof(TIndex)); constexpr T kInitVal = kSelectMax ? std::numeric_limits<T>::lowest() : std::numeric_limits<T>::max(); hipLaunchKernelGGL(( selectRowsViaHeap<T, TIndex, TIndex, kBlockSize, kHeapSize, kSelectMax>) , dim3(outer_size), dim3(kBlockSize), smem, context->cuda_stream(), input, values, indices, kInitVal, std::numeric_limits<TIndex>::max(), outer_size, inner_size, k); } template <typename T, bool kSelectMax = true> void RunRadixSelectionImpl( const T* input, const TIndex outer_size, const TIndex inner_size, const int k, T* values, TIndex* indices, CUDAContext* context) { const int block = ::min( math::roundUp(static_cast<int>(inner_size), kWarpSize), CAFFE_CUDA_NUM_THREADS); hipLaunchKernelGGL(( gatherTopK<T, kSelectMax, TIndex>) , dim3(outer_size), dim3(block), 0, context->cuda_stream(), input, inner_size, k, outer_size, values, indices); // Unfortunately the output is not currently sorted, and there is no batch // sorting utility available. Iterate over all of the slices and sort them // in-place using Thrust. for (int i = 0; i < outer_size; ++i) { thrust::sort_by_key( thrust::hip::par.on(context->cuda_stream()), values + i * k, values + i * k + k, indices + i * k, thrust::greater<T>()); } } template <typename T> void RunTopKOnLastDimCUDAImpl( const T* input, const TIndex outer_size, const TIndex inner_size, const int k, T* values, TIndex* indices, CUDAContext* context) { // If k is small, uses heap selection, otherwise uses radix selection. if (k < 32) { RunHeapSelectionImpl<T, 32>( input, outer_size, inner_size, k, values, indices, context); } else if (k < 128) { RunHeapSelectionImpl<T, 128>( input, outer_size, inner_size, k, values, indices, context); } else if (k < 512) { RunHeapSelectionImpl<T, 512>( input, outer_size, inner_size, k, values, indices, context); } else { RunRadixSelectionImpl<T>( input, outer_size, inner_size, k, values, indices, context); } } __global__ void FlattenIndicesCUDAKernel( const TIndex* src, const TIndex size, const TIndex stride, const TIndex n, const int k, TIndex* dst) { CUDA_1D_KERNEL_LOOP(i, size) { const TIndex x = i / stride / k; const TIndex y = i % stride; #if __CUDA_ARCH__ >= 350 dst[i] = __ldg(src + i) * stride + x * n * stride + y; #else dst[i] = src[i] * stride + x * n * stride + y; #endif } } template <typename T> __global__ void SetTopKGradientCUDAKernel( const T* values, const TIndex* indices, const TIndex size, const TIndex stride, const TIndex n, const int k, T* dst) { CUDA_1D_KERNEL_LOOP(i, size) { const TIndex x = i / stride / k; const TIndex y = i % stride; #if __CUDA_ARCH__ >= 350 dst[__ldg(indices + i) * stride + x * n * stride + y] = __ldg(values + i); #else dst[indices[i] * stride + x * n * stride + y] = values[i]; #endif } } } // namespace template <typename T> class TopKOp<T, CUDAContext> : public Operator<CUDAContext> { public: USE_OPERATOR_FUNCTIONS(CUDAContext); TopKOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws), OP_SINGLE_ARG(int, "k", k_, -1), OP_SINGLE_ARG(int, "axis", axis_, -1) { CAFFE_ENFORCE(k_ >= 1, "k argument must be >= 1"); } ~TopKOp(){}; bool RunOnDevice() override; private: const int k_; int axis_; // Buffers for CUDAContext. TensorCUDA input_transposed_buffer_; TensorCUDA values_transposed_buffer_; TensorCUDA indices_transposed_buffer_; // Shape tensors on device for CUDAContext. TensorCUDA input_dims_device_; TensorCUDA input_transposed_dims_device_; TensorCUDA input_axes_device_; TensorCUDA output_dims_device_; TensorCUDA output_transposed_dims_device_; TensorCUDA output_transposed_axes_device_; }; template <typename T> bool TopKOp<T, CUDAContext>::RunOnDevice() { const auto& input = Input(0); auto* values = Output(0); auto* indices = Output(1); auto* flatten_indices = OutputSize() > 2 ? Output(2) : nullptr; const std::vector<TIndex>& input_dims = input.dims(); if (axis_ == -1) { axis_ = input_dims.size() - 1; } CAFFE_ENFORCE_GE(axis_, 0); CAFFE_ENFORCE_LT(axis_, input_dims.size()); CAFFE_ENFORCE_LE( k_, input_dims[axis_], "k argument should not be greater than the axis dim."); const bool need_transpose = axis_ < input_dims.size() - 1; std::vector<TIndex> output_dims = input_dims; output_dims[axis_] = k_; const TIndex prev_size = std::accumulate( input_dims.cbegin(), input_dims.cbegin() + axis_, TIndex(1), std::multiplies<TIndex>()); const TIndex next_size = std::accumulate( input_dims.cbegin() + axis_ + 1, input_dims.cend(), TIndex(1), std::multiplies<TIndex>()); const TIndex outer_size = input.size() / input_dims[axis_]; const TIndex inner_size = input_dims[axis_]; values->Resize(output_dims); indices->Resize(output_dims); if (flatten_indices != nullptr) { flatten_indices->Resize(indices->size()); } const T* input_data = input.template data<T>(); T* values_data = values->template mutable_data<T>(); TIndex* indices_data = indices->template mutable_data<TIndex>(); TIndex* flatten_indices_data = flatten_indices == nullptr ? nullptr : flatten_indices->template mutable_data<TIndex>(); if (need_transpose) { const std::array<int, 3> X_dims = {static_cast<int>(prev_size), static_cast<int>(inner_size), static_cast<int>(next_size)}; const std::array<int, 3> Y_dims = {static_cast<int>(prev_size), static_cast<int>(next_size), static_cast<int>(inner_size)}; const std::array<int, 3> axes = {0, 2, 1}; input_transposed_buffer_.Resize( std::vector<TIndex>{outer_size, inner_size}); values_transposed_buffer_.Resize(std::vector<TIndex>{outer_size, k_}); indices_transposed_buffer_.Resize(std::vector<TIndex>{outer_size, k_}); math::Transpose( input.size(), 3, X_dims.data(), Y_dims.data(), axes.data(), input.template data<T>(), input_transposed_buffer_.mutable_data<T>(), &context_); input_data = input_transposed_buffer_.data<T>(); values_data = values_transposed_buffer_.mutable_data<T>(); indices_data = indices_transposed_buffer_.mutable_data<TIndex>(); } RunTopKOnLastDimCUDAImpl<T>( input_data, outer_size, inner_size, k_, values_data, indices_data, &context_); if (need_transpose) { const std::array<int, 3> X_dims = { static_cast<int>(prev_size), k_, static_cast<int>(next_size)}; const std::array<int, 3> Y_dims = { static_cast<int>(prev_size), static_cast<int>(next_size), k_}; const std::array<int, 3> axes = {0, 2, 1}; math::Transpose( values_transposed_buffer_.size(), 3, Y_dims.data(), X_dims.data(), axes.data(), values_transposed_buffer_.data<T>(), values->template mutable_data<T>(), &context_); math::Transpose( indices_transposed_buffer_.size(), 3, Y_dims.data(), X_dims.data(), axes.data(), indices_transposed_buffer_.data<TIndex>(), indices->template mutable_data<TIndex>(), &context_); } // Flatten the indices if needed. if (flatten_indices != nullptr) { hipLaunchKernelGGL(( FlattenIndicesCUDAKernel), dim3(CAFFE_GET_BLOCKS(indices->size())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), indices->template data<TIndex>(), indices->size(), next_size, inner_size, k_, flatten_indices->template mutable_data<TIndex>()); } return true; } REGISTER_CUDA_OPERATOR(TopK, TopKOp<float, CUDAContext>); template <typename T> class TopKGradientOp<T, CUDAContext> : public Operator<CUDAContext> { public: USE_OPERATOR_FUNCTIONS(CUDAContext); TopKGradientOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws), OP_SINGLE_ARG(int, "axis", axis_, -1) {} ~TopKGradientOp(){}; bool RunOnDevice() override; private: int axis_; }; template <typename T> bool TopKGradientOp<T, CUDAContext>::RunOnDevice() { const auto& values = Input(0); const auto& indices = Input(1); const auto& original_input = Input(2); auto* output = Output(0); const std::vector<TIndex>& values_dims = values.dims(); const std::vector<TIndex>& origin_dims = original_input.dims(); CAFFE_ENFORCE_EQ(values_dims.size(), origin_dims.size()); output->Resize(origin_dims); T* output_data = output->template mutable_data<T>(); if (axis_ == -1) { axis_ = values_dims.size() - 1; } const int k = values_dims[axis_]; math::Set<T, CUDAContext>(output->size(), T(0), output_data, &context_); const TIndex stride = std::accumulate( values_dims.cbegin() + axis_ + 1, values_dims.cend(), TIndex(1), std::multiplies<TIndex>()); hipLaunchKernelGGL(( SetTopKGradientCUDAKernel), dim3(CAFFE_GET_BLOCKS(indices.size())), dim3(CAFFE_CUDA_NUM_THREADS), 0, context_.cuda_stream(), values.template data<T>(), indices.template data<TIndex>(), values.size(), stride, origin_dims[axis_], k, output_data); return true; } REGISTER_CUDA_OPERATOR(TopKGradient, TopKGradientOp<float, CUDAContext>); } // namespace caffe2
52c521a72aca27bc6984e8f1c83e352502d28611.cu
#include "caffe2/operators/top_k.h" #include <algorithm> #include <array> #include <functional> #include <limits> #include <numeric> #include <vector> #include <thrust/sort.h> #include <thrust/system/cuda/execution_policy.h> #include "caffe2/core/context.h" #include "caffe2/core/context_gpu.h" #include "caffe2/operators/top_k_heap_selection.cuh" #include "caffe2/operators/top_k_radix_selection.cuh" #include "caffe2/utils/math.h" namespace caffe2 { namespace { template <typename T, int kHeapSize, bool kSelectMax = true> void RunHeapSelectionImpl( const T* input, const TIndex outer_size, const TIndex inner_size, const int k, T* values, TIndex* indices, CUDAContext* context) { constexpr int kBlockSize = 256; constexpr int kNumWarps = kBlockSize / kWarpSize; constexpr int smem = kNumWarps * kHeapSize * (sizeof(T) + sizeof(TIndex)); constexpr T kInitVal = kSelectMax ? std::numeric_limits<T>::lowest() : std::numeric_limits<T>::max(); selectRowsViaHeap<T, TIndex, TIndex, kBlockSize, kHeapSize, kSelectMax> <<<outer_size, kBlockSize, smem, context->cuda_stream()>>>( input, values, indices, kInitVal, std::numeric_limits<TIndex>::max(), outer_size, inner_size, k); } template <typename T, bool kSelectMax = true> void RunRadixSelectionImpl( const T* input, const TIndex outer_size, const TIndex inner_size, const int k, T* values, TIndex* indices, CUDAContext* context) { const int block = std::min( math::roundUp(static_cast<int>(inner_size), kWarpSize), CAFFE_CUDA_NUM_THREADS); gatherTopK<T, kSelectMax, TIndex> <<<outer_size, block, 0, context->cuda_stream()>>>( input, inner_size, k, outer_size, values, indices); // Unfortunately the output is not currently sorted, and there is no batch // sorting utility available. Iterate over all of the slices and sort them // in-place using Thrust. for (int i = 0; i < outer_size; ++i) { thrust::sort_by_key( thrust::cuda::par.on(context->cuda_stream()), values + i * k, values + i * k + k, indices + i * k, thrust::greater<T>()); } } template <typename T> void RunTopKOnLastDimCUDAImpl( const T* input, const TIndex outer_size, const TIndex inner_size, const int k, T* values, TIndex* indices, CUDAContext* context) { // If k is small, uses heap selection, otherwise uses radix selection. if (k < 32) { RunHeapSelectionImpl<T, 32>( input, outer_size, inner_size, k, values, indices, context); } else if (k < 128) { RunHeapSelectionImpl<T, 128>( input, outer_size, inner_size, k, values, indices, context); } else if (k < 512) { RunHeapSelectionImpl<T, 512>( input, outer_size, inner_size, k, values, indices, context); } else { RunRadixSelectionImpl<T>( input, outer_size, inner_size, k, values, indices, context); } } __global__ void FlattenIndicesCUDAKernel( const TIndex* src, const TIndex size, const TIndex stride, const TIndex n, const int k, TIndex* dst) { CUDA_1D_KERNEL_LOOP(i, size) { const TIndex x = i / stride / k; const TIndex y = i % stride; #if __CUDA_ARCH__ >= 350 dst[i] = __ldg(src + i) * stride + x * n * stride + y; #else dst[i] = src[i] * stride + x * n * stride + y; #endif } } template <typename T> __global__ void SetTopKGradientCUDAKernel( const T* values, const TIndex* indices, const TIndex size, const TIndex stride, const TIndex n, const int k, T* dst) { CUDA_1D_KERNEL_LOOP(i, size) { const TIndex x = i / stride / k; const TIndex y = i % stride; #if __CUDA_ARCH__ >= 350 dst[__ldg(indices + i) * stride + x * n * stride + y] = __ldg(values + i); #else dst[indices[i] * stride + x * n * stride + y] = values[i]; #endif } } } // namespace template <typename T> class TopKOp<T, CUDAContext> : public Operator<CUDAContext> { public: USE_OPERATOR_FUNCTIONS(CUDAContext); TopKOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws), OP_SINGLE_ARG(int, "k", k_, -1), OP_SINGLE_ARG(int, "axis", axis_, -1) { CAFFE_ENFORCE(k_ >= 1, "k argument must be >= 1"); } ~TopKOp(){}; bool RunOnDevice() override; private: const int k_; int axis_; // Buffers for CUDAContext. TensorCUDA input_transposed_buffer_; TensorCUDA values_transposed_buffer_; TensorCUDA indices_transposed_buffer_; // Shape tensors on device for CUDAContext. TensorCUDA input_dims_device_; TensorCUDA input_transposed_dims_device_; TensorCUDA input_axes_device_; TensorCUDA output_dims_device_; TensorCUDA output_transposed_dims_device_; TensorCUDA output_transposed_axes_device_; }; template <typename T> bool TopKOp<T, CUDAContext>::RunOnDevice() { const auto& input = Input(0); auto* values = Output(0); auto* indices = Output(1); auto* flatten_indices = OutputSize() > 2 ? Output(2) : nullptr; const std::vector<TIndex>& input_dims = input.dims(); if (axis_ == -1) { axis_ = input_dims.size() - 1; } CAFFE_ENFORCE_GE(axis_, 0); CAFFE_ENFORCE_LT(axis_, input_dims.size()); CAFFE_ENFORCE_LE( k_, input_dims[axis_], "k argument should not be greater than the axis dim."); const bool need_transpose = axis_ < input_dims.size() - 1; std::vector<TIndex> output_dims = input_dims; output_dims[axis_] = k_; const TIndex prev_size = std::accumulate( input_dims.cbegin(), input_dims.cbegin() + axis_, TIndex(1), std::multiplies<TIndex>()); const TIndex next_size = std::accumulate( input_dims.cbegin() + axis_ + 1, input_dims.cend(), TIndex(1), std::multiplies<TIndex>()); const TIndex outer_size = input.size() / input_dims[axis_]; const TIndex inner_size = input_dims[axis_]; values->Resize(output_dims); indices->Resize(output_dims); if (flatten_indices != nullptr) { flatten_indices->Resize(indices->size()); } const T* input_data = input.template data<T>(); T* values_data = values->template mutable_data<T>(); TIndex* indices_data = indices->template mutable_data<TIndex>(); TIndex* flatten_indices_data = flatten_indices == nullptr ? nullptr : flatten_indices->template mutable_data<TIndex>(); if (need_transpose) { const std::array<int, 3> X_dims = {static_cast<int>(prev_size), static_cast<int>(inner_size), static_cast<int>(next_size)}; const std::array<int, 3> Y_dims = {static_cast<int>(prev_size), static_cast<int>(next_size), static_cast<int>(inner_size)}; const std::array<int, 3> axes = {0, 2, 1}; input_transposed_buffer_.Resize( std::vector<TIndex>{outer_size, inner_size}); values_transposed_buffer_.Resize(std::vector<TIndex>{outer_size, k_}); indices_transposed_buffer_.Resize(std::vector<TIndex>{outer_size, k_}); math::Transpose( input.size(), 3, X_dims.data(), Y_dims.data(), axes.data(), input.template data<T>(), input_transposed_buffer_.mutable_data<T>(), &context_); input_data = input_transposed_buffer_.data<T>(); values_data = values_transposed_buffer_.mutable_data<T>(); indices_data = indices_transposed_buffer_.mutable_data<TIndex>(); } RunTopKOnLastDimCUDAImpl<T>( input_data, outer_size, inner_size, k_, values_data, indices_data, &context_); if (need_transpose) { const std::array<int, 3> X_dims = { static_cast<int>(prev_size), k_, static_cast<int>(next_size)}; const std::array<int, 3> Y_dims = { static_cast<int>(prev_size), static_cast<int>(next_size), k_}; const std::array<int, 3> axes = {0, 2, 1}; math::Transpose( values_transposed_buffer_.size(), 3, Y_dims.data(), X_dims.data(), axes.data(), values_transposed_buffer_.data<T>(), values->template mutable_data<T>(), &context_); math::Transpose( indices_transposed_buffer_.size(), 3, Y_dims.data(), X_dims.data(), axes.data(), indices_transposed_buffer_.data<TIndex>(), indices->template mutable_data<TIndex>(), &context_); } // Flatten the indices if needed. if (flatten_indices != nullptr) { FlattenIndicesCUDAKernel<<< CAFFE_GET_BLOCKS(indices->size()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( indices->template data<TIndex>(), indices->size(), next_size, inner_size, k_, flatten_indices->template mutable_data<TIndex>()); } return true; } REGISTER_CUDA_OPERATOR(TopK, TopKOp<float, CUDAContext>); template <typename T> class TopKGradientOp<T, CUDAContext> : public Operator<CUDAContext> { public: USE_OPERATOR_FUNCTIONS(CUDAContext); TopKGradientOp(const OperatorDef& operator_def, Workspace* ws) : Operator<CUDAContext>(operator_def, ws), OP_SINGLE_ARG(int, "axis", axis_, -1) {} ~TopKGradientOp(){}; bool RunOnDevice() override; private: int axis_; }; template <typename T> bool TopKGradientOp<T, CUDAContext>::RunOnDevice() { const auto& values = Input(0); const auto& indices = Input(1); const auto& original_input = Input(2); auto* output = Output(0); const std::vector<TIndex>& values_dims = values.dims(); const std::vector<TIndex>& origin_dims = original_input.dims(); CAFFE_ENFORCE_EQ(values_dims.size(), origin_dims.size()); output->Resize(origin_dims); T* output_data = output->template mutable_data<T>(); if (axis_ == -1) { axis_ = values_dims.size() - 1; } const int k = values_dims[axis_]; math::Set<T, CUDAContext>(output->size(), T(0), output_data, &context_); const TIndex stride = std::accumulate( values_dims.cbegin() + axis_ + 1, values_dims.cend(), TIndex(1), std::multiplies<TIndex>()); SetTopKGradientCUDAKernel<<< CAFFE_GET_BLOCKS(indices.size()), CAFFE_CUDA_NUM_THREADS, 0, context_.cuda_stream()>>>( values.template data<T>(), indices.template data<TIndex>(), values.size(), stride, origin_dims[axis_], k, output_data); return true; } REGISTER_CUDA_OPERATOR(TopKGradient, TopKGradientOp<float, CUDAContext>); } // namespace caffe2
b673a4dd4492143b911c100b0c547df54c8ec3e4.hip
// !!! This is a file automatically generated by hipify!!! #include "moe_cuda_kernel.h" #include <cstdio> #include <iostream> #include <vector> #include <hip/hip_runtime.h> #include <hip/hip_runtime.h> #include <rocblas.h> #include <helper_cuda.h> #include <ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h> #include "cuda_stream_manager.h" #include "cublas_wrapper.h" #ifdef MOE_USE_NCCL #include <rccl.h> template<typename scalar_t> void moe_cuda_global_fused_forward_impl( const scalar_t* input_buf, const scalar_t* weight, scalar_t* global_input_buf, scalar_t* global_output_buf, scalar_t* output_buf, const long* local_expert_count, const long* global_expert_count, long in_feat, long out_feat, long num_expert, long world_size, CudaStreamManager* smgr) { int ptr = 0; int send_ptr = 0; int recv_ptr = 0; int *expert_ptr = new int[num_expert * world_size]; expert_ptr[0] = 0; for (int i = 1; i < num_expert * world_size; ++i) { expert_ptr[i] = expert_ptr[i - 1] + local_expert_count[i - 1]; } scalar_t alpha = 1, beta = 0; for (int i = 0; i < num_expert; ++i) { int expert_count = 0; NCCL_SAFE_CALL(ncclGroupStart()); for (int j = 0; j < world_size; ++j) { int idx = i + j * num_expert; if (local_expert_count[idx]) { NCCL_SAFE_CALL(ncclSend( input_buf + expert_ptr[idx] * in_feat, local_expert_count[idx] * in_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); } if (global_expert_count[idx]) { NCCL_SAFE_CALL(ncclRecv( global_input_buf + recv_ptr * in_feat, global_expert_count[idx] * in_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); recv_ptr += global_expert_count[idx]; expert_count += global_expert_count[idx]; } } NCCL_SAFE_CALL(ncclGroupEnd()); checkCudaErrors(cublasXgemm( smgr->handle(i), HIPBLAS_OP_T, HIPBLAS_OP_N, out_feat, expert_count, in_feat, &alpha, weight + i * in_feat * out_feat, in_feat, global_input_buf + ptr * in_feat, in_feat, &beta, global_output_buf + out_feat * ptr, out_feat )); ptr += expert_count; NCCL_SAFE_CALL(ncclGroupStart()); for (int j = 0; j < world_size; ++j) { int idx = i + j * num_expert; if (global_expert_count[idx]) { NCCL_SAFE_CALL(ncclSend( global_output_buf + send_ptr * out_feat, global_expert_count[idx] * out_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); send_ptr += global_expert_count[idx]; } if (local_expert_count[idx]) { NCCL_SAFE_CALL(ncclRecv( output_buf + expert_ptr[idx] * out_feat, local_expert_count[idx] * out_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); } } NCCL_SAFE_CALL(ncclGroupEnd()); } delete [] expert_ptr; smgr->sync(num_expert); } std::vector<torch::Tensor> moe_cuda_global_fused_forward( torch::Tensor input_buf, torch::Tensor weight, torch::Tensor local_expert_count, torch::Tensor global_expert_count, long global_batch_size, long local_batch_size, long n_workers) { const auto num_expert = local_expert_count.size(0) / n_workers; const auto out_feat = weight.size(1); const auto in_feat = weight.size(2); auto smgr = getCudaStreamManager(input_buf.device().index()); auto global_input_buf = input_buf.new_empty({global_batch_size, in_feat}); auto global_output_buf = input_buf.new_empty({global_batch_size, out_feat}); auto output_buf = input_buf.new_empty({local_batch_size, out_feat}); AT_DISPATCH_FLOATING_TYPES_AND_HALF(input_buf.scalar_type(), "moe_cuda_global_fused_forward", ([&] { moe_cuda_global_fused_forward_impl( input_buf.data_ptr<scalar_t>(), weight.data_ptr<scalar_t>(), global_input_buf.data_ptr<scalar_t>(), global_output_buf.data_ptr<scalar_t>(), output_buf.data_ptr<scalar_t>(), local_expert_count.data_ptr<long>(), global_expert_count.data_ptr<long>(), in_feat, out_feat, num_expert, n_workers, smgr); })); return {output_buf, global_input_buf}; } #endif
b673a4dd4492143b911c100b0c547df54c8ec3e4.cu
#include "moe_cuda_kernel.h" #include <cstdio> #include <iostream> #include <vector> #include <cuda.h> #include <cuda_runtime.h> #include <cublas_v2.h> #include <helper_cuda.h> #include <c10/cuda/CUDAGuard.h> #include "cuda_stream_manager.h" #include "cublas_wrapper.h" #ifdef MOE_USE_NCCL #include <nccl.h> template<typename scalar_t> void moe_cuda_global_fused_forward_impl( const scalar_t* input_buf, const scalar_t* weight, scalar_t* global_input_buf, scalar_t* global_output_buf, scalar_t* output_buf, const long* local_expert_count, const long* global_expert_count, long in_feat, long out_feat, long num_expert, long world_size, CudaStreamManager* smgr) { int ptr = 0; int send_ptr = 0; int recv_ptr = 0; int *expert_ptr = new int[num_expert * world_size]; expert_ptr[0] = 0; for (int i = 1; i < num_expert * world_size; ++i) { expert_ptr[i] = expert_ptr[i - 1] + local_expert_count[i - 1]; } scalar_t alpha = 1, beta = 0; for (int i = 0; i < num_expert; ++i) { int expert_count = 0; NCCL_SAFE_CALL(ncclGroupStart()); for (int j = 0; j < world_size; ++j) { int idx = i + j * num_expert; if (local_expert_count[idx]) { NCCL_SAFE_CALL(ncclSend( input_buf + expert_ptr[idx] * in_feat, local_expert_count[idx] * in_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); } if (global_expert_count[idx]) { NCCL_SAFE_CALL(ncclRecv( global_input_buf + recv_ptr * in_feat, global_expert_count[idx] * in_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); recv_ptr += global_expert_count[idx]; expert_count += global_expert_count[idx]; } } NCCL_SAFE_CALL(ncclGroupEnd()); checkCudaErrors(cublasXgemm( smgr->handle(i), CUBLAS_OP_T, CUBLAS_OP_N, out_feat, expert_count, in_feat, &alpha, weight + i * in_feat * out_feat, in_feat, global_input_buf + ptr * in_feat, in_feat, &beta, global_output_buf + out_feat * ptr, out_feat )); ptr += expert_count; NCCL_SAFE_CALL(ncclGroupStart()); for (int j = 0; j < world_size; ++j) { int idx = i + j * num_expert; if (global_expert_count[idx]) { NCCL_SAFE_CALL(ncclSend( global_output_buf + send_ptr * out_feat, global_expert_count[idx] * out_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); send_ptr += global_expert_count[idx]; } if (local_expert_count[idx]) { NCCL_SAFE_CALL(ncclRecv( output_buf + expert_ptr[idx] * out_feat, local_expert_count[idx] * out_feat * sizeof(scalar_t), ncclChar, j, smgr->ncclcomm, smgr->stream(i))); } } NCCL_SAFE_CALL(ncclGroupEnd()); } delete [] expert_ptr; smgr->sync(num_expert); } std::vector<torch::Tensor> moe_cuda_global_fused_forward( torch::Tensor input_buf, torch::Tensor weight, torch::Tensor local_expert_count, torch::Tensor global_expert_count, long global_batch_size, long local_batch_size, long n_workers) { const auto num_expert = local_expert_count.size(0) / n_workers; const auto out_feat = weight.size(1); const auto in_feat = weight.size(2); auto smgr = getCudaStreamManager(input_buf.device().index()); auto global_input_buf = input_buf.new_empty({global_batch_size, in_feat}); auto global_output_buf = input_buf.new_empty({global_batch_size, out_feat}); auto output_buf = input_buf.new_empty({local_batch_size, out_feat}); AT_DISPATCH_FLOATING_TYPES_AND_HALF(input_buf.scalar_type(), "moe_cuda_global_fused_forward", ([&] { moe_cuda_global_fused_forward_impl( input_buf.data_ptr<scalar_t>(), weight.data_ptr<scalar_t>(), global_input_buf.data_ptr<scalar_t>(), global_output_buf.data_ptr<scalar_t>(), output_buf.data_ptr<scalar_t>(), local_expert_count.data_ptr<long>(), global_expert_count.data_ptr<long>(), in_feat, out_feat, num_expert, n_workers, smgr); })); return {output_buf, global_input_buf}; } #endif
a0218303e21f456c7bccb311f6dd47c8a21b15c6.hip
// !!! This is a file automatically generated by hipify!!! #include <torch/extension.h> #include <ATen/ATen.h> #include <ATen/hip/HIPContext.h> #include <hip/hip_runtime.h> #include <hip/hip_runtime.h> #include <vector> #include <iostream> #include <string.h> namespace { template <typename scalar_t> __device__ __forceinline__ scalar_t sigmoid(scalar_t z) { return 1.0 / (1.0 + exp(-z)); } template <typename scalar_t> __device__ __forceinline__ scalar_t d_sigmoid(scalar_t z) { const auto s = sigmoid(z); return (1.0 - s) * s; } template <typename scalar_t> __device__ __forceinline__ scalar_t d_tanh(scalar_t z) { const auto t = tanh(z); return 1 - (t * t); } template <typename scalar_t> __device__ __forceinline__ scalar_t elu(scalar_t z, scalar_t alpha = 1.0) { return fmaxf(0.0, z) + fminf(0.0, alpha * (exp(z) - 1.0)); } template <typename scalar_t> __device__ __forceinline__ scalar_t d_elu(scalar_t z, scalar_t alpha = 1.0) { const auto e = exp(z); const auto d_relu = z < 0.0 ? 0.0 : 1.0; return d_relu + (((alpha * (e - 1.0)) < 0.0) ? (alpha * e) : 0.0); } template <typename scalar_t> __global__ void lltm_cuda_forward_kernel( const torch::PackedTensorAccessor<scalar_t,3,torch::RestrictPtrTraits,size_t> gates, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> old_cell, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> new_h, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> new_cell, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> input_gate, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> output_gate, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> candidate_cell) { //batch index const int n = blockIdx.y; // column index const int c = blockIdx.x * blockDim.x + threadIdx.x; if (c < gates.size(2)){ input_gate[n][c] = sigmoid(gates[n][0][c]); output_gate[n][c] = sigmoid(gates[n][1][c]); candidate_cell[n][c] = elu(gates[n][2][c]); new_cell[n][c] = old_cell[n][c] + candidate_cell[n][c] * input_gate[n][c]; new_h[n][c] = tanh(new_cell[n][c]) * output_gate[n][c]; } } template <typename scalar_t> __global__ void lltm_cuda_backward_kernel( torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> d_old_cell, torch::PackedTensorAccessor<scalar_t,3,torch::RestrictPtrTraits,size_t> d_gates, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> grad_h, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> grad_cell, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> new_cell, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> input_gate, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> output_gate, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> candidate_cell, const torch::PackedTensorAccessor<scalar_t,3,torch::RestrictPtrTraits,size_t> gate_weights) { //batch index const int n = blockIdx.y; // column index const int c = blockIdx.x * blockDim.x + threadIdx.x; if (c < d_gates.size(2)){ const auto d_output_gate = tanh(new_cell[n][c]) * grad_h[n][c]; const auto d_tanh_new_cell = output_gate[n][c] * grad_h[n][c]; const auto d_new_cell = d_tanh(new_cell[n][c]) * d_tanh_new_cell + grad_cell[n][c]; d_old_cell[n][c] = d_new_cell; const auto d_candidate_cell = input_gate[n][c] * d_new_cell; const auto d_input_gate = candidate_cell[n][c] * d_new_cell; d_gates[n][0][c] = d_input_gate * d_sigmoid(gate_weights[n][0][c]); d_gates[n][1][c] = d_output_gate * d_sigmoid(gate_weights[n][1][c]); d_gates[n][2][c] = d_candidate_cell * d_elu(gate_weights[n][2][c]); } } } // namespace std::vector<torch::Tensor> lltm_cuda_forward( torch::Tensor input, torch::Tensor weights, torch::Tensor bias, torch::Tensor old_h, torch::Tensor old_cell) { hipSetDevice(input.get_device()); std::cout << input.get_device() << std::endl; std::cout << weights.get_device() << std::endl; std::cout << bias.get_device() << std::endl; std::cout << old_h.get_device() << std::endl; std::cout << old_cell.get_device() << std::endl; std::cout << "over" << std::endl; auto X = torch::cat({old_h, input}, /*dim=*/1); auto gate_weights = torch::addmm(bias, X, weights.transpose(0, 1)); const auto batch_size = old_cell.size(0); const auto state_size = old_cell.size(1); auto gates = gate_weights.reshape({batch_size, 3, state_size}); auto new_h = torch::zeros_like(old_cell); auto new_cell = torch::zeros_like(old_cell); auto input_gate = torch::zeros_like(old_cell); auto output_gate = torch::zeros_like(old_cell); auto candidate_cell = torch::zeros_like(old_cell); const int threads = 128; const dim3 blocks((state_size + threads - 1) / threads, batch_size); AT_DISPATCH_FLOATING_TYPES(gates.type(), "lltm_forward_cuda", ([&] { hipLaunchKernelGGL(( lltm_cuda_forward_kernel<scalar_t>), dim3(blocks), dim3(threads), 0, 0, gates.packed_accessor<scalar_t,3,torch::RestrictPtrTraits,size_t>(), old_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), new_h.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), new_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), input_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), output_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), candidate_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>()); })); return {new_h, new_cell, input_gate, output_gate, candidate_cell, X, gates}; } std::vector<torch::Tensor> lltm_cuda_backward( torch::Tensor grad_h, torch::Tensor grad_cell, torch::Tensor new_cell, torch::Tensor input_gate, torch::Tensor output_gate, torch::Tensor candidate_cell, torch::Tensor X, torch::Tensor gates, torch::Tensor weights) { auto d_old_cell = torch::zeros_like(new_cell); auto d_gates = torch::zeros_like(gates); const auto batch_size = new_cell.size(0); const auto state_size = new_cell.size(1); const int threads = 1024; const dim3 blocks((state_size + threads - 1) / threads, batch_size); AT_DISPATCH_FLOATING_TYPES(X.type(), "lltm_forward_cuda", ([&] { hipLaunchKernelGGL(( lltm_cuda_backward_kernel<scalar_t>), dim3(blocks), dim3(threads), 0, 0, d_old_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), d_gates.packed_accessor<scalar_t,3,torch::RestrictPtrTraits,size_t>(), grad_h.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), grad_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), new_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), input_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), output_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), candidate_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), gates.packed_accessor<scalar_t,3,torch::RestrictPtrTraits,size_t>()); })); auto d_gate_weights = d_gates.flatten(1, 2); auto d_weights = d_gate_weights.t().mm(X); auto d_bias = d_gate_weights.sum(/*dim=*/0, /*keepdim=*/true); auto d_X = d_gate_weights.mm(weights); auto d_old_h = d_X.slice(/*dim=*/1, 0, state_size); auto d_input = d_X.slice(/*dim=*/1, state_size); return {d_old_h, d_input, d_weights, d_bias, d_old_cell, d_gates}; }
a0218303e21f456c7bccb311f6dd47c8a21b15c6.cu
#include <torch/extension.h> #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <cuda.h> #include <cuda_runtime.h> #include <vector> #include <iostream> #include <string.h> namespace { template <typename scalar_t> __device__ __forceinline__ scalar_t sigmoid(scalar_t z) { return 1.0 / (1.0 + exp(-z)); } template <typename scalar_t> __device__ __forceinline__ scalar_t d_sigmoid(scalar_t z) { const auto s = sigmoid(z); return (1.0 - s) * s; } template <typename scalar_t> __device__ __forceinline__ scalar_t d_tanh(scalar_t z) { const auto t = tanh(z); return 1 - (t * t); } template <typename scalar_t> __device__ __forceinline__ scalar_t elu(scalar_t z, scalar_t alpha = 1.0) { return fmaxf(0.0, z) + fminf(0.0, alpha * (exp(z) - 1.0)); } template <typename scalar_t> __device__ __forceinline__ scalar_t d_elu(scalar_t z, scalar_t alpha = 1.0) { const auto e = exp(z); const auto d_relu = z < 0.0 ? 0.0 : 1.0; return d_relu + (((alpha * (e - 1.0)) < 0.0) ? (alpha * e) : 0.0); } template <typename scalar_t> __global__ void lltm_cuda_forward_kernel( const torch::PackedTensorAccessor<scalar_t,3,torch::RestrictPtrTraits,size_t> gates, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> old_cell, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> new_h, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> new_cell, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> input_gate, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> output_gate, torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> candidate_cell) { //batch index const int n = blockIdx.y; // column index const int c = blockIdx.x * blockDim.x + threadIdx.x; if (c < gates.size(2)){ input_gate[n][c] = sigmoid(gates[n][0][c]); output_gate[n][c] = sigmoid(gates[n][1][c]); candidate_cell[n][c] = elu(gates[n][2][c]); new_cell[n][c] = old_cell[n][c] + candidate_cell[n][c] * input_gate[n][c]; new_h[n][c] = tanh(new_cell[n][c]) * output_gate[n][c]; } } template <typename scalar_t> __global__ void lltm_cuda_backward_kernel( torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> d_old_cell, torch::PackedTensorAccessor<scalar_t,3,torch::RestrictPtrTraits,size_t> d_gates, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> grad_h, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> grad_cell, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> new_cell, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> input_gate, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> output_gate, const torch::PackedTensorAccessor<scalar_t,2,torch::RestrictPtrTraits,size_t> candidate_cell, const torch::PackedTensorAccessor<scalar_t,3,torch::RestrictPtrTraits,size_t> gate_weights) { //batch index const int n = blockIdx.y; // column index const int c = blockIdx.x * blockDim.x + threadIdx.x; if (c < d_gates.size(2)){ const auto d_output_gate = tanh(new_cell[n][c]) * grad_h[n][c]; const auto d_tanh_new_cell = output_gate[n][c] * grad_h[n][c]; const auto d_new_cell = d_tanh(new_cell[n][c]) * d_tanh_new_cell + grad_cell[n][c]; d_old_cell[n][c] = d_new_cell; const auto d_candidate_cell = input_gate[n][c] * d_new_cell; const auto d_input_gate = candidate_cell[n][c] * d_new_cell; d_gates[n][0][c] = d_input_gate * d_sigmoid(gate_weights[n][0][c]); d_gates[n][1][c] = d_output_gate * d_sigmoid(gate_weights[n][1][c]); d_gates[n][2][c] = d_candidate_cell * d_elu(gate_weights[n][2][c]); } } } // namespace std::vector<torch::Tensor> lltm_cuda_forward( torch::Tensor input, torch::Tensor weights, torch::Tensor bias, torch::Tensor old_h, torch::Tensor old_cell) { cudaSetDevice(input.get_device()); std::cout << input.get_device() << std::endl; std::cout << weights.get_device() << std::endl; std::cout << bias.get_device() << std::endl; std::cout << old_h.get_device() << std::endl; std::cout << old_cell.get_device() << std::endl; std::cout << "over" << std::endl; auto X = torch::cat({old_h, input}, /*dim=*/1); auto gate_weights = torch::addmm(bias, X, weights.transpose(0, 1)); const auto batch_size = old_cell.size(0); const auto state_size = old_cell.size(1); auto gates = gate_weights.reshape({batch_size, 3, state_size}); auto new_h = torch::zeros_like(old_cell); auto new_cell = torch::zeros_like(old_cell); auto input_gate = torch::zeros_like(old_cell); auto output_gate = torch::zeros_like(old_cell); auto candidate_cell = torch::zeros_like(old_cell); const int threads = 128; const dim3 blocks((state_size + threads - 1) / threads, batch_size); AT_DISPATCH_FLOATING_TYPES(gates.type(), "lltm_forward_cuda", ([&] { lltm_cuda_forward_kernel<scalar_t><<<blocks, threads>>>( gates.packed_accessor<scalar_t,3,torch::RestrictPtrTraits,size_t>(), old_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), new_h.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), new_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), input_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), output_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), candidate_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>()); })); return {new_h, new_cell, input_gate, output_gate, candidate_cell, X, gates}; } std::vector<torch::Tensor> lltm_cuda_backward( torch::Tensor grad_h, torch::Tensor grad_cell, torch::Tensor new_cell, torch::Tensor input_gate, torch::Tensor output_gate, torch::Tensor candidate_cell, torch::Tensor X, torch::Tensor gates, torch::Tensor weights) { auto d_old_cell = torch::zeros_like(new_cell); auto d_gates = torch::zeros_like(gates); const auto batch_size = new_cell.size(0); const auto state_size = new_cell.size(1); const int threads = 1024; const dim3 blocks((state_size + threads - 1) / threads, batch_size); AT_DISPATCH_FLOATING_TYPES(X.type(), "lltm_forward_cuda", ([&] { lltm_cuda_backward_kernel<scalar_t><<<blocks, threads>>>( d_old_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), d_gates.packed_accessor<scalar_t,3,torch::RestrictPtrTraits,size_t>(), grad_h.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), grad_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), new_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), input_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), output_gate.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), candidate_cell.packed_accessor<scalar_t,2,torch::RestrictPtrTraits,size_t>(), gates.packed_accessor<scalar_t,3,torch::RestrictPtrTraits,size_t>()); })); auto d_gate_weights = d_gates.flatten(1, 2); auto d_weights = d_gate_weights.t().mm(X); auto d_bias = d_gate_weights.sum(/*dim=*/0, /*keepdim=*/true); auto d_X = d_gate_weights.mm(weights); auto d_old_h = d_X.slice(/*dim=*/1, 0, state_size); auto d_input = d_X.slice(/*dim=*/1, state_size); return {d_old_h, d_input, d_weights, d_bias, d_old_cell, d_gates}; }
ed52fee34d3ef178fd76bad1a5ba68039b8ad985.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <unittest/unittest.h> #include <thrust/uninitialized_fill.h> #include <thrust/execution_policy.h> template<typename ExecutionPolicy, typename Iterator, typename T> __global__ void uninitialized_fill_kernel(ExecutionPolicy exec, Iterator first, Iterator last, T val) { thrust::uninitialized_fill(exec, first, last, val); } template<typename ExecutionPolicy> void TestUninitializedFillDevice(ExecutionPolicy exec) { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); hipLaunchKernelGGL(( uninitialized_fill_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin() + 1, v.begin() + 4, exemplar); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } ASSERT_EQUAL(v[0], 0); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 4); exemplar = 8; hipLaunchKernelGGL(( uninitialized_fill_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin() + 0, v.begin() + 3, exemplar); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], 7); ASSERT_EQUAL(v[4], 4); exemplar = 9; hipLaunchKernelGGL(( uninitialized_fill_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin() + 2, v.end(), exemplar); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } ASSERT_EQUAL(v[0], 8); ASSERT_EQUAL(v[1], 8); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 9); exemplar = 1; hipLaunchKernelGGL(( uninitialized_fill_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin(), v.end(), exemplar); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); } void TestUninitializedFillDeviceSeq() { TestUninitializedFillDevice(thrust::seq); } DECLARE_UNITTEST(TestUninitializedFillDeviceSeq); void TestUninitializedFillDeviceDevice() { TestUninitializedFillDevice(thrust::device); } DECLARE_UNITTEST(TestUninitializedFillDeviceDevice); void TestUninitializedFillCudaStreams() { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); hipStream_t s; hipStreamCreate(&s); thrust::uninitialized_fill(thrust::hip::par.on(s), v.begin(), v.end(), exemplar); hipStreamSynchronize(s); ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); hipStreamDestroy(s); } DECLARE_UNITTEST(TestUninitializedFillCudaStreams); template<typename ExecutionPolicy, typename Iterator1, typename Size, typename T, typename Iterator2> __global__ void uninitialized_fill_n_kernel(ExecutionPolicy exec, Iterator1 first, Size n, T val, Iterator2 result) { *result = thrust::uninitialized_fill_n(exec, first, n, val); } template<typename ExecutionPolicy> void TestUninitializedFillNDevice(ExecutionPolicy exec) { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); thrust::device_vector<Vector::iterator> iter_vec(1); hipLaunchKernelGGL(( uninitialized_fill_n_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin() + 1, 3, exemplar, iter_vec.begin()); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } Vector::iterator iter = iter_vec[0]; ASSERT_EQUAL(v[0], 0); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 4); ASSERT_EQUAL_QUIET(v.begin() + 4, iter); exemplar = 8; hipLaunchKernelGGL(( uninitialized_fill_n_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin() + 0, 3, exemplar, iter_vec.begin()); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); iter = iter_vec[0]; ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], 7); ASSERT_EQUAL(v[4], 4); ASSERT_EQUAL_QUIET(v.begin() + 3, iter); exemplar = 9; hipLaunchKernelGGL(( uninitialized_fill_n_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin() + 2, 3, exemplar, iter_vec.begin()); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } iter = iter_vec[0]; ASSERT_EQUAL(v[0], 8); ASSERT_EQUAL(v[1], 8); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 9); ASSERT_EQUAL_QUIET(v.end(), iter); exemplar = 1; hipLaunchKernelGGL(( uninitialized_fill_n_kernel), dim3(1),dim3(1), 0, 0, exec, v.begin(), v.size(), exemplar, iter_vec.begin()); { hipError_t const err = hipDeviceSynchronize(); ASSERT_EQUAL(hipSuccess, err); } iter = iter_vec[0]; ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); ASSERT_EQUAL_QUIET(v.end(), iter); } void TestUninitializedFillNDeviceSeq() { TestUninitializedFillNDevice(thrust::seq); } DECLARE_UNITTEST(TestUninitializedFillNDeviceSeq); void TestUninitializedFillNDeviceDevice() { TestUninitializedFillNDevice(thrust::device); } DECLARE_UNITTEST(TestUninitializedFillNDeviceDevice); void TestUninitializedFillNCudaStreams() { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); hipStream_t s; hipStreamCreate(&s); thrust::uninitialized_fill_n(thrust::hip::par.on(s), v.begin(), v.size(), exemplar); hipStreamSynchronize(s); ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); hipStreamDestroy(s); } DECLARE_UNITTEST(TestUninitializedFillNCudaStreams);
ed52fee34d3ef178fd76bad1a5ba68039b8ad985.cu
#include <unittest/unittest.h> #include <thrust/uninitialized_fill.h> #include <thrust/execution_policy.h> template<typename ExecutionPolicy, typename Iterator, typename T> __global__ void uninitialized_fill_kernel(ExecutionPolicy exec, Iterator first, Iterator last, T val) { thrust::uninitialized_fill(exec, first, last, val); } template<typename ExecutionPolicy> void TestUninitializedFillDevice(ExecutionPolicy exec) { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); uninitialized_fill_kernel<<<1,1>>>(exec, v.begin() + 1, v.begin() + 4, exemplar); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } ASSERT_EQUAL(v[0], 0); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 4); exemplar = 8; uninitialized_fill_kernel<<<1,1>>>(exec, v.begin() + 0, v.begin() + 3, exemplar); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], 7); ASSERT_EQUAL(v[4], 4); exemplar = 9; uninitialized_fill_kernel<<<1,1>>>(exec, v.begin() + 2, v.end(), exemplar); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } ASSERT_EQUAL(v[0], 8); ASSERT_EQUAL(v[1], 8); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 9); exemplar = 1; uninitialized_fill_kernel<<<1,1>>>(exec, v.begin(), v.end(), exemplar); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); } void TestUninitializedFillDeviceSeq() { TestUninitializedFillDevice(thrust::seq); } DECLARE_UNITTEST(TestUninitializedFillDeviceSeq); void TestUninitializedFillDeviceDevice() { TestUninitializedFillDevice(thrust::device); } DECLARE_UNITTEST(TestUninitializedFillDeviceDevice); void TestUninitializedFillCudaStreams() { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); cudaStream_t s; cudaStreamCreate(&s); thrust::uninitialized_fill(thrust::cuda::par.on(s), v.begin(), v.end(), exemplar); cudaStreamSynchronize(s); ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); cudaStreamDestroy(s); } DECLARE_UNITTEST(TestUninitializedFillCudaStreams); template<typename ExecutionPolicy, typename Iterator1, typename Size, typename T, typename Iterator2> __global__ void uninitialized_fill_n_kernel(ExecutionPolicy exec, Iterator1 first, Size n, T val, Iterator2 result) { *result = thrust::uninitialized_fill_n(exec, first, n, val); } template<typename ExecutionPolicy> void TestUninitializedFillNDevice(ExecutionPolicy exec) { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); thrust::device_vector<Vector::iterator> iter_vec(1); uninitialized_fill_n_kernel<<<1,1>>>(exec, v.begin() + 1, 3, exemplar, iter_vec.begin()); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } Vector::iterator iter = iter_vec[0]; ASSERT_EQUAL(v[0], 0); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 4); ASSERT_EQUAL_QUIET(v.begin() + 4, iter); exemplar = 8; uninitialized_fill_n_kernel<<<1,1>>>(exec, v.begin() + 0, 3, exemplar, iter_vec.begin()); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); iter = iter_vec[0]; ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], 7); ASSERT_EQUAL(v[4], 4); ASSERT_EQUAL_QUIET(v.begin() + 3, iter); exemplar = 9; uninitialized_fill_n_kernel<<<1,1>>>(exec, v.begin() + 2, 3, exemplar, iter_vec.begin()); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } iter = iter_vec[0]; ASSERT_EQUAL(v[0], 8); ASSERT_EQUAL(v[1], 8); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], 9); ASSERT_EQUAL_QUIET(v.end(), iter); exemplar = 1; uninitialized_fill_n_kernel<<<1,1>>>(exec, v.begin(), v.size(), exemplar, iter_vec.begin()); { cudaError_t const err = cudaDeviceSynchronize(); ASSERT_EQUAL(cudaSuccess, err); } iter = iter_vec[0]; ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); ASSERT_EQUAL_QUIET(v.end(), iter); } void TestUninitializedFillNDeviceSeq() { TestUninitializedFillNDevice(thrust::seq); } DECLARE_UNITTEST(TestUninitializedFillNDeviceSeq); void TestUninitializedFillNDeviceDevice() { TestUninitializedFillNDevice(thrust::device); } DECLARE_UNITTEST(TestUninitializedFillNDeviceDevice); void TestUninitializedFillNCudaStreams() { typedef thrust::device_vector<int> Vector; typedef Vector::value_type T; Vector v(5); v[0] = 0; v[1] = 1; v[2] = 2; v[3] = 3; v[4] = 4; T exemplar(7); cudaStream_t s; cudaStreamCreate(&s); thrust::uninitialized_fill_n(thrust::cuda::par.on(s), v.begin(), v.size(), exemplar); cudaStreamSynchronize(s); ASSERT_EQUAL(v[0], exemplar); ASSERT_EQUAL(v[1], exemplar); ASSERT_EQUAL(v[2], exemplar); ASSERT_EQUAL(v[3], exemplar); ASSERT_EQUAL(v[4], exemplar); cudaStreamDestroy(s); } DECLARE_UNITTEST(TestUninitializedFillNCudaStreams);
9aad0eeb161a1894ce948c482691f16f7dd5ac45.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> #include <stdlib.h> #include <iostream> #include <random> #include <math.h> #include "helper_cuda.h" #include "hipcub/hipcub.hpp" #include "variables.h" #include "energy.h" __global__ void energy_kernel(const float * const __restrict__ mx, const float * const __restrict__ my, const float * const __restrict__ mz, float * __restrict__ pE_afm_ex, float * __restrict__ pE_afm_an, float * __restrict__ pE_afm_dm, const float * const __restrict__ KA, const float * const __restrict__ mc, const float * const __restrict__ Jx_s, const float * const __restrict__ Jy_s, const float * const __restrict__ Jz_s, const float * const __restrict__ Jx_o, const float * const __restrict__ Jy_o, const float * const __restrict__ Jz_o, const float * const __restrict__ Dx_s, const float * const __restrict__ Dy_s, const float * const __restrict__ Dz_s, const float * const __restrict__ Dx_o, const float * const __restrict__ Dy_o, const float * const __restrict__ Dz_o, const float Hx, const float Hy, const float Hz, float * __restrict__ am1, float * __restrict__ am2, float * __restrict__ am3, const int L, const grid_color color, const float * const __restrict__ other_x, const float * const __restrict__ other_y, const float * const __restrict__ other_z){ int x = threadIdx.x + blockDim.x*blockIdx.x; int y = threadIdx.y + blockDim.y*blockIdx.y; int z = threadIdx.z + blockDim.z*blockIdx.z; if (x < L && y < 2*L && z < 2*L) { const int n = L*2; int index = 0, ixf = 0, idx_rb = 0; float px = 0.0f; float py = 0.0f; float pz = 0.0f; float ener = 0.0f; float E_afm_ex = 0.0f; float E_afm_an = 0.0f; float E_afm_dm = 0.0f; float xxm = 0.0f, zxm=0.0f; float xym = 0.0f, zym=0.0f; float xzm = 0.0f, zzm=0.0f; float xxp = 0.0f, zxp=0.0f; float xyp = 0.0f, zyp=0.0f; float xzp = 0.0f, zzp=0.0f; int rbzm = 0; int rbym = 0; int rbxm = 0; int rbzp = 0; int rbyp = 0; int rbxp = 0; ixf = 2*x + STRF(color, y, z); // i on full size matrix index = IX(ixf, y, z); idx_rb = RB(x, y, z); // index for color matrix /* for the neightbours in the matrix of the other colors, * the ones in X are same index and one more or one less, * depending on index parity. */ if (!(index&1)){ rbxp = RB(x, y, z); rbxm = RB(c(x - 1, L), y, z); } else { rbxp = RB(c(x + 1, L), y, z); rbxm = RB(x, y, z); } rbyp = RB(x, c(y + 1, n), z); rbzp = RB(x, y, c(z + 1, n)); rbym = RB(x, c(y - 1, n), z); rbzm = RB(x, y, c(z - 1, n)); px = mx[idx_rb]; py = my[idx_rb]; pz = mz[idx_rb]; // anisortopy energy E_afm_an = -KA[idx_rb]*(px*px) - (Hx*px + Hy*py + Hz*pz)*mc[idx_rb]; am1[idx_rb] = E_afm_an; xxm = other_x[rbxm]; zxm = other_z[rbxm]; xym = other_x[rbym]; zym = other_z[rbym]; xzm = other_x[rbzm]; zzm = other_z[rbzm]; xxp = other_x[rbxp]; zxp = other_z[rbxp]; xyp = other_x[rbyp]; zyp = other_z[rbyp]; xzp = other_x[rbzp]; zzp = other_z[rbzp]; // exchange energy E_afm_ex += (xxm*px + other_y[rbxm]*py + zxm*pz)*Jx_o[rbxm]; ener += (zxm*px - xxm*pz)*Dx_o[rbxm]; E_afm_ex += (xym*px + other_y[rbym]*py + zym*pz)*Jy_o[rbym]; ener += (zym*px - xym*pz)*Dy_o[rbym]; E_afm_ex += (xzm*px + other_y[rbzm]*py + zzm*pz)*Jz_o[rbzm]; ener += (zzm*px - xzm*pz)*Dz_o[rbzm]; E_afm_ex += (xxp*px + other_y[rbxp]*py + zxp*pz)*Jx_s[idx_rb]; ener += (zxp*px - xxp*pz)*Dx_s[idx_rb]; E_afm_ex += (xyp*px + other_y[rbyp]*py + zyp*pz)*Jy_s[idx_rb]; ener += (zyp*px - xyp*pz)*Dy_s[idx_rb]; E_afm_ex += (xzp*px + other_y[rbzp]*py + zzp*pz)*Jz_s[idx_rb]; ener += (zzp*px - xzp*pz)*Dz_s[idx_rb]; am2[idx_rb] = E_afm_ex; E_afm_dm = -(ener*(1 - 2*((ixf+y+z)&1))); am3[idx_rb] = E_afm_dm; } } __host__ void energy(const float * const __restrict__ mx_r, const float * const __restrict__ my_r, const float * const __restrict__ mz_r, const float * const __restrict__ mx_b, const float * const __restrict__ my_b, const float * const __restrict__ mz_b, float * __restrict__ pE_afm_ex, float * __restrict__ pE_afm_an, float * __restrict__ pE_afm_dm, const float * const __restrict__ KA_r, const float * const __restrict__ KA_b, const float * const __restrict__ mc_r, const float * const __restrict__ mc_b, const float * const __restrict__ Jx_r, const float * const __restrict__ Jy_r, const float * const __restrict__ Jz_r, const float * const __restrict__ Jx_b, const float * const __restrict__ Jy_b, const float * const __restrict__ Jz_b, const float * const __restrict__ Dx_r, const float * const __restrict__ Dy_r, const float * const __restrict__ Dz_r, const float * const __restrict__ Dx_b, const float * const __restrict__ Dy_b, const float * const __restrict__ Dz_b, const float Hx, const float Hy, const float Hz, float* am1, float* am2, float* am3, float* am4, float* am5, float* am6, float* aux_mat, void * d_ts, size_t d_ts_bytes, const int L, const dim3 blocks, const dim3 threads) { float E_afm_an = 0.0f; float E_afm_ex = 0.0f; float E_afm_dm = 0.0f; const int RBN = 4*L*L*L; hipLaunchKernelGGL(( energy_kernel), dim3(blocks), dim3(threads), 0, 0, mx_r, my_r, mz_r, &E_afm_ex, &E_afm_an, &E_afm_dm, KA_r, mc_r, Jx_r, Jy_r, Jz_r, Jx_b, Jy_b, Jz_b, Dx_r, Dy_r, Dz_r, Dx_b, Dy_b, Dz_b, Hx, Hy, Hz, am1, am2, am3, L, RED_TILES, mx_b, my_b, mz_b); getLastCudaError("energy red failed\n"); checkCudaErrors(hipDeviceSynchronize()); CubDebugExit(hipcub::DeviceReduce::Sum(d_ts, d_ts_bytes, am1, aux_mat, RBN)); getLastCudaError("reduct red energy 1 failed\n"); checkCudaErrors(hipDeviceSynchronize()); E_afm_an = aux_mat[0]; CubDebugExit(hipcub::DeviceReduce::Sum(d_ts, d_ts_bytes, am2, aux_mat, RBN)); getLastCudaError("reduct red energy 2 failed\n"); checkCudaErrors(hipDeviceSynchronize()); E_afm_ex = aux_mat[0]; CubDebugExit(hipcub::DeviceReduce::Sum(d_ts, d_ts_bytes, am3, aux_mat, RBN)); getLastCudaError("reduct red energy 3 failed\n"); checkCudaErrors(hipDeviceSynchronize()); E_afm_dm = aux_mat[0]; hipLaunchKernelGGL(( energy_kernel), dim3(blocks), dim3(threads), 0, 0, mx_b, my_b, mz_b, &E_afm_ex, &E_afm_an, &E_afm_dm, KA_b, mc_b, Jx_b, Jy_b, Jz_b, Jx_r, Jy_r, Jz_r, Dx_b, Dy_b, Dz_b, Dx_r, Dy_r, Dz_r, Hx, Hy, Hz, am4, am5, am6, L, BLACK_TILES, mx_r, my_r, mz_r); getLastCudaError("energy black failed\n"); checkCudaErrors(hipDeviceSynchronize()); CubDebugExit(hipcub::DeviceReduce::Sum(d_ts, d_ts_bytes, am4, aux_mat, RBN)); getLastCudaError("reduct black energy 1 failed\n"); checkCudaErrors(hipDeviceSynchronize()); E_afm_an += aux_mat[0]; CubDebugExit(hipcub::DeviceReduce::Sum(d_ts, d_ts_bytes, am5, aux_mat, RBN)); getLastCudaError("reduct black energy 2 failed\n"); checkCudaErrors(hipDeviceSynchronize()); E_afm_ex += aux_mat[0]; CubDebugExit(hipcub::DeviceReduce::Sum(d_ts, d_ts_bytes, am6, aux_mat, RBN)); getLastCudaError("reduct black energy 3 failed\n"); checkCudaErrors(hipDeviceSynchronize()); E_afm_dm += aux_mat[0]; *pE_afm_ex = 0.5f*E_afm_ex/(RBN*2); //la energia de intercambio se cuenta dos veces *pE_afm_dm = 0.5f*E_afm_dm/(RBN*2); //la energia de intercambio se cuenta dos veces *pE_afm_an = E_afm_an/(RBN*2); }
9aad0eeb161a1894ce948c482691f16f7dd5ac45.cu
#include <stdio.h> #include <stdlib.h> #include <iostream> #include <random> #include <math.h> #include "helper_cuda.h" #include "cub/cub.cuh" #include "variables.h" #include "energy.h" __global__ void energy_kernel(const float * const __restrict__ mx, const float * const __restrict__ my, const float * const __restrict__ mz, float * __restrict__ pE_afm_ex, float * __restrict__ pE_afm_an, float * __restrict__ pE_afm_dm, const float * const __restrict__ KA, const float * const __restrict__ mc, const float * const __restrict__ Jx_s, const float * const __restrict__ Jy_s, const float * const __restrict__ Jz_s, const float * const __restrict__ Jx_o, const float * const __restrict__ Jy_o, const float * const __restrict__ Jz_o, const float * const __restrict__ Dx_s, const float * const __restrict__ Dy_s, const float * const __restrict__ Dz_s, const float * const __restrict__ Dx_o, const float * const __restrict__ Dy_o, const float * const __restrict__ Dz_o, const float Hx, const float Hy, const float Hz, float * __restrict__ am1, float * __restrict__ am2, float * __restrict__ am3, const int L, const grid_color color, const float * const __restrict__ other_x, const float * const __restrict__ other_y, const float * const __restrict__ other_z){ int x = threadIdx.x + blockDim.x*blockIdx.x; int y = threadIdx.y + blockDim.y*blockIdx.y; int z = threadIdx.z + blockDim.z*blockIdx.z; if (x < L && y < 2*L && z < 2*L) { const int n = L*2; int index = 0, ixf = 0, idx_rb = 0; float px = 0.0f; float py = 0.0f; float pz = 0.0f; float ener = 0.0f; float E_afm_ex = 0.0f; float E_afm_an = 0.0f; float E_afm_dm = 0.0f; float xxm = 0.0f, zxm=0.0f; float xym = 0.0f, zym=0.0f; float xzm = 0.0f, zzm=0.0f; float xxp = 0.0f, zxp=0.0f; float xyp = 0.0f, zyp=0.0f; float xzp = 0.0f, zzp=0.0f; int rbzm = 0; int rbym = 0; int rbxm = 0; int rbzp = 0; int rbyp = 0; int rbxp = 0; ixf = 2*x + STRF(color, y, z); // i on full size matrix index = IX(ixf, y, z); idx_rb = RB(x, y, z); // index for color matrix /* for the neightbours in the matrix of the other colors, * the ones in X are same index and one more or one less, * depending on index parity. */ if (!(index&1)){ rbxp = RB(x, y, z); rbxm = RB(c(x - 1, L), y, z); } else { rbxp = RB(c(x + 1, L), y, z); rbxm = RB(x, y, z); } rbyp = RB(x, c(y + 1, n), z); rbzp = RB(x, y, c(z + 1, n)); rbym = RB(x, c(y - 1, n), z); rbzm = RB(x, y, c(z - 1, n)); px = mx[idx_rb]; py = my[idx_rb]; pz = mz[idx_rb]; // anisortopy energy E_afm_an = -KA[idx_rb]*(px*px) - (Hx*px + Hy*py + Hz*pz)*mc[idx_rb]; am1[idx_rb] = E_afm_an; xxm = other_x[rbxm]; zxm = other_z[rbxm]; xym = other_x[rbym]; zym = other_z[rbym]; xzm = other_x[rbzm]; zzm = other_z[rbzm]; xxp = other_x[rbxp]; zxp = other_z[rbxp]; xyp = other_x[rbyp]; zyp = other_z[rbyp]; xzp = other_x[rbzp]; zzp = other_z[rbzp]; // exchange energy E_afm_ex += (xxm*px + other_y[rbxm]*py + zxm*pz)*Jx_o[rbxm]; ener += (zxm*px - xxm*pz)*Dx_o[rbxm]; E_afm_ex += (xym*px + other_y[rbym]*py + zym*pz)*Jy_o[rbym]; ener += (zym*px - xym*pz)*Dy_o[rbym]; E_afm_ex += (xzm*px + other_y[rbzm]*py + zzm*pz)*Jz_o[rbzm]; ener += (zzm*px - xzm*pz)*Dz_o[rbzm]; E_afm_ex += (xxp*px + other_y[rbxp]*py + zxp*pz)*Jx_s[idx_rb]; ener += (zxp*px - xxp*pz)*Dx_s[idx_rb]; E_afm_ex += (xyp*px + other_y[rbyp]*py + zyp*pz)*Jy_s[idx_rb]; ener += (zyp*px - xyp*pz)*Dy_s[idx_rb]; E_afm_ex += (xzp*px + other_y[rbzp]*py + zzp*pz)*Jz_s[idx_rb]; ener += (zzp*px - xzp*pz)*Dz_s[idx_rb]; am2[idx_rb] = E_afm_ex; E_afm_dm = -(ener*(1 - 2*((ixf+y+z)&1))); am3[idx_rb] = E_afm_dm; } } __host__ void energy(const float * const __restrict__ mx_r, const float * const __restrict__ my_r, const float * const __restrict__ mz_r, const float * const __restrict__ mx_b, const float * const __restrict__ my_b, const float * const __restrict__ mz_b, float * __restrict__ pE_afm_ex, float * __restrict__ pE_afm_an, float * __restrict__ pE_afm_dm, const float * const __restrict__ KA_r, const float * const __restrict__ KA_b, const float * const __restrict__ mc_r, const float * const __restrict__ mc_b, const float * const __restrict__ Jx_r, const float * const __restrict__ Jy_r, const float * const __restrict__ Jz_r, const float * const __restrict__ Jx_b, const float * const __restrict__ Jy_b, const float * const __restrict__ Jz_b, const float * const __restrict__ Dx_r, const float * const __restrict__ Dy_r, const float * const __restrict__ Dz_r, const float * const __restrict__ Dx_b, const float * const __restrict__ Dy_b, const float * const __restrict__ Dz_b, const float Hx, const float Hy, const float Hz, float* am1, float* am2, float* am3, float* am4, float* am5, float* am6, float* aux_mat, void * d_ts, size_t d_ts_bytes, const int L, const dim3 blocks, const dim3 threads) { float E_afm_an = 0.0f; float E_afm_ex = 0.0f; float E_afm_dm = 0.0f; const int RBN = 4*L*L*L; energy_kernel<<<blocks, threads>>>(mx_r, my_r, mz_r, &E_afm_ex, &E_afm_an, &E_afm_dm, KA_r, mc_r, Jx_r, Jy_r, Jz_r, Jx_b, Jy_b, Jz_b, Dx_r, Dy_r, Dz_r, Dx_b, Dy_b, Dz_b, Hx, Hy, Hz, am1, am2, am3, L, RED_TILES, mx_b, my_b, mz_b); getLastCudaError("energy red failed\n"); checkCudaErrors(cudaDeviceSynchronize()); CubDebugExit(cub::DeviceReduce::Sum(d_ts, d_ts_bytes, am1, aux_mat, RBN)); getLastCudaError("reduct red energy 1 failed\n"); checkCudaErrors(cudaDeviceSynchronize()); E_afm_an = aux_mat[0]; CubDebugExit(cub::DeviceReduce::Sum(d_ts, d_ts_bytes, am2, aux_mat, RBN)); getLastCudaError("reduct red energy 2 failed\n"); checkCudaErrors(cudaDeviceSynchronize()); E_afm_ex = aux_mat[0]; CubDebugExit(cub::DeviceReduce::Sum(d_ts, d_ts_bytes, am3, aux_mat, RBN)); getLastCudaError("reduct red energy 3 failed\n"); checkCudaErrors(cudaDeviceSynchronize()); E_afm_dm = aux_mat[0]; energy_kernel<<<blocks, threads>>>(mx_b, my_b, mz_b, &E_afm_ex, &E_afm_an, &E_afm_dm, KA_b, mc_b, Jx_b, Jy_b, Jz_b, Jx_r, Jy_r, Jz_r, Dx_b, Dy_b, Dz_b, Dx_r, Dy_r, Dz_r, Hx, Hy, Hz, am4, am5, am6, L, BLACK_TILES, mx_r, my_r, mz_r); getLastCudaError("energy black failed\n"); checkCudaErrors(cudaDeviceSynchronize()); CubDebugExit(cub::DeviceReduce::Sum(d_ts, d_ts_bytes, am4, aux_mat, RBN)); getLastCudaError("reduct black energy 1 failed\n"); checkCudaErrors(cudaDeviceSynchronize()); E_afm_an += aux_mat[0]; CubDebugExit(cub::DeviceReduce::Sum(d_ts, d_ts_bytes, am5, aux_mat, RBN)); getLastCudaError("reduct black energy 2 failed\n"); checkCudaErrors(cudaDeviceSynchronize()); E_afm_ex += aux_mat[0]; CubDebugExit(cub::DeviceReduce::Sum(d_ts, d_ts_bytes, am6, aux_mat, RBN)); getLastCudaError("reduct black energy 3 failed\n"); checkCudaErrors(cudaDeviceSynchronize()); E_afm_dm += aux_mat[0]; *pE_afm_ex = 0.5f*E_afm_ex/(RBN*2); //la energia de intercambio se cuenta dos veces *pE_afm_dm = 0.5f*E_afm_dm/(RBN*2); //la energia de intercambio se cuenta dos veces *pE_afm_an = E_afm_an/(RBN*2); }
9f80ac532dd0e1c2c22874badb0dbedf7bac3dbc.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "support.h" __global__ void histogram_kernel( point* points, unsigned int* histogram, unsigned int chunk_size, unsigned int histo_row_count, unsigned int histo_col_count, float lat_max, float lat_min, float lon_max, float lon_min) { //Dynamic Shared Memory extern __shared__ unsigned int histogram_private[]; unsigned int histo_size = histo_col_count * histo_row_count; //Initialize private hisogram int i = 0; while((blockDim.x * i + threadIdx.x) < histo_size) { histogram_private[blockDim.x * i + threadIdx.x] = 0.0f; i++; } __syncthreads(); //Compute the private histograms i = blockDim.x * blockIdx.x + threadIdx.x; while(i < chunk_size) { int col = ((points[i].lon - lon_min) * histo_col_count / (lon_max - lon_min)); //int col = (int) col_f - (col_f % 1); int row = ((points[i].lat - lat_min) * histo_row_count / (lat_max - lat_min)); //int row = (int) row_f - (row_f % 1); if(col > (histo_col_count - 1)) col = histo_col_count - 1; if(row > (histo_row_count - 1)) row = histo_row_count - 1; atomicAdd(&(histogram_private[row * histo_col_count + col]), 1); i += blockDim.x * gridDim.x; } __syncthreads(); //Compute the global histogram i = 0; while((blockDim.x * i + threadIdx.x) < histo_size) { atomicAdd(&(histogram[blockDim.x * i + threadIdx.x]), histogram_private[blockDim.x * i + threadIdx.x]); i++; } }
9f80ac532dd0e1c2c22874badb0dbedf7bac3dbc.cu
#include "support.h" __global__ void histogram_kernel( point* points, unsigned int* histogram, unsigned int chunk_size, unsigned int histo_row_count, unsigned int histo_col_count, float lat_max, float lat_min, float lon_max, float lon_min) { //Dynamic Shared Memory extern __shared__ unsigned int histogram_private[]; unsigned int histo_size = histo_col_count * histo_row_count; //Initialize private hisogram int i = 0; while((blockDim.x * i + threadIdx.x) < histo_size) { histogram_private[blockDim.x * i + threadIdx.x] = 0.0f; i++; } __syncthreads(); //Compute the private histograms i = blockDim.x * blockIdx.x + threadIdx.x; while(i < chunk_size) { int col = ((points[i].lon - lon_min) * histo_col_count / (lon_max - lon_min)); //int col = (int) col_f - (col_f % 1); int row = ((points[i].lat - lat_min) * histo_row_count / (lat_max - lat_min)); //int row = (int) row_f - (row_f % 1); if(col > (histo_col_count - 1)) col = histo_col_count - 1; if(row > (histo_row_count - 1)) row = histo_row_count - 1; atomicAdd(&(histogram_private[row * histo_col_count + col]), 1); i += blockDim.x * gridDim.x; } __syncthreads(); //Compute the global histogram i = 0; while((blockDim.x * i + threadIdx.x) < histo_size) { atomicAdd(&(histogram[blockDim.x * i + threadIdx.x]), histogram_private[blockDim.x * i + threadIdx.x]); i++; } }
612025ae723ec3e75790c54f1bd44233fdd0f4b2.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include<stdio.h> #include<math.h> #define N 8 __global__ void exclusive_scan(int *d_in) { //Phase 1 (Uptree) int s = 1; __shared__ int temp_in[N]; int i = 2*s*(threadIdx.x+1)-1; temp_in[i] = d_in[i]; __syncthreads(); for(; s<=N-1; s<<=1) { if((i-s >= 0) && (i<N)) { //printf("s = %d, i= %d \n", s, i); int a = temp_in[i]; int b = temp_in[i-s]; __syncthreads(); temp_in[i] = a+b; //printf("Write in[%d] = %d\n", i, a+b); } __syncthreads(); } //Phase 2 (Downtree) if(threadIdx.x == 0) temp_in[N-1] = 0; for(s = s/2; s >= 1; s>>=1) { int i = 2*s*(threadIdx.x+1)-1; if((i-s >= 0) && (i<N)) { //printf("s = %d, i= %d \n", s, i); int r = temp_in[i]; int l = temp_in[i-s]; __syncthreads(); temp_in[i] = l+r; temp_in[i-s] = r; __syncthreads(); //printf("Write in[%d] = %d\n", i, a+b); } __syncthreads(); } d_in[i] = temp_in[i]; } int main() { int h_in[N]; int h_out[N]; //timer hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); h_in[0] = 3; h_in[1] = 1; h_in[2] = 7; h_in[3] = 0; h_in[4] = 4; h_in[5] = 1; h_in[6] = 6; h_in[7] = 3; int *d_in; //int *d_out; hipMalloc((void**) &d_in, N*sizeof(int)); //hipMalloc((void**) &d_out, N*sizeof(int)); hipMemcpy(d_in, &h_in, N*sizeof(int), hipMemcpyHostToDevice); hipEventRecord(start); //Implementing kernel call hipLaunchKernelGGL(( exclusive_scan), dim3(1), dim3(4), 0, 0, d_in); hipEventRecord(stop); hipMemcpy(&h_out, d_in, N*sizeof(int), hipMemcpyDeviceToHost); hipEventSynchronize(stop); float ms = 0; hipEventElapsedTime(&ms, start, stop); for(int i=0; i<N; i++) printf("out[%d] = %d\n", i, h_out[i]); hipFree(d_in); printf("Time used: %f milliseconds\n", ms); return -1; }
612025ae723ec3e75790c54f1bd44233fdd0f4b2.cu
#include<stdio.h> #include<math.h> #define N 8 __global__ void exclusive_scan(int *d_in) { //Phase 1 (Uptree) int s = 1; __shared__ int temp_in[N]; int i = 2*s*(threadIdx.x+1)-1; temp_in[i] = d_in[i]; __syncthreads(); for(; s<=N-1; s<<=1) { if((i-s >= 0) && (i<N)) { //printf("s = %d, i= %d \n", s, i); int a = temp_in[i]; int b = temp_in[i-s]; __syncthreads(); temp_in[i] = a+b; //printf("Write in[%d] = %d\n", i, a+b); } __syncthreads(); } //Phase 2 (Downtree) if(threadIdx.x == 0) temp_in[N-1] = 0; for(s = s/2; s >= 1; s>>=1) { int i = 2*s*(threadIdx.x+1)-1; if((i-s >= 0) && (i<N)) { //printf("s = %d, i= %d \n", s, i); int r = temp_in[i]; int l = temp_in[i-s]; __syncthreads(); temp_in[i] = l+r; temp_in[i-s] = r; __syncthreads(); //printf("Write in[%d] = %d\n", i, a+b); } __syncthreads(); } d_in[i] = temp_in[i]; } int main() { int h_in[N]; int h_out[N]; //timer cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); h_in[0] = 3; h_in[1] = 1; h_in[2] = 7; h_in[3] = 0; h_in[4] = 4; h_in[5] = 1; h_in[6] = 6; h_in[7] = 3; int *d_in; //int *d_out; cudaMalloc((void**) &d_in, N*sizeof(int)); //cudaMalloc((void**) &d_out, N*sizeof(int)); cudaMemcpy(d_in, &h_in, N*sizeof(int), cudaMemcpyHostToDevice); cudaEventRecord(start); //Implementing kernel call exclusive_scan<<<1, 4>>>(d_in); cudaEventRecord(stop); cudaMemcpy(&h_out, d_in, N*sizeof(int), cudaMemcpyDeviceToHost); cudaEventSynchronize(stop); float ms = 0; cudaEventElapsedTime(&ms, start, stop); for(int i=0; i<N; i++) printf("out[%d] = %d\n", i, h_out[i]); cudaFree(d_in); printf("Time used: %f milliseconds\n", ms); return -1; }
b3ae9a356683612f4914dcbeee04d5190b68fe9f.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 "scatter.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]; unsigned int *in = NULL; hipMalloc(&in, XSIZE*YSIZE); unsigned int *in_pos = NULL; hipMalloc(&in_pos, XSIZE*YSIZE); unsigned int *out = NULL; hipMalloc(&out, XSIZE*YSIZE); unsigned int *out_pos = NULL; hipMalloc(&out_pos, XSIZE*YSIZE); unsigned int n = 1; unsigned int *d_histScan = NULL; hipMalloc(&d_histScan, XSIZE*YSIZE); unsigned int mask = 1; unsigned int current_bits = 1; unsigned int nBins = 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(( scatter), dim3(gridBlock),dim3(threadBlock), 0, 0, in,in_pos,out,out_pos,n,d_histScan,mask,current_bits,nBins); hipDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) {hipLaunchKernelGGL(( scatter), dim3(gridBlock),dim3(threadBlock), 0, 0, in,in_pos,out,out_pos,n,d_histScan,mask,current_bits,nBins); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) {hipLaunchKernelGGL(( scatter), dim3(gridBlock),dim3(threadBlock), 0, 0, in,in_pos,out,out_pos,n,d_histScan,mask,current_bits,nBins); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
b3ae9a356683612f4914dcbeee04d5190b68fe9f.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 "scatter.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 int *in = NULL; cudaMalloc(&in, XSIZE*YSIZE); unsigned int *in_pos = NULL; cudaMalloc(&in_pos, XSIZE*YSIZE); unsigned int *out = NULL; cudaMalloc(&out, XSIZE*YSIZE); unsigned int *out_pos = NULL; cudaMalloc(&out_pos, XSIZE*YSIZE); unsigned int n = 1; unsigned int *d_histScan = NULL; cudaMalloc(&d_histScan, XSIZE*YSIZE); unsigned int mask = 1; unsigned int current_bits = 1; unsigned int nBins = 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); scatter<<<gridBlock,threadBlock>>>(in,in_pos,out,out_pos,n,d_histScan,mask,current_bits,nBins); cudaDeviceSynchronize(); for (int loop_counter = 0; loop_counter < 10; ++loop_counter) { scatter<<<gridBlock,threadBlock>>>(in,in_pos,out,out_pos,n,d_histScan,mask,current_bits,nBins); } auto start = steady_clock::now(); for (int loop_counter = 0; loop_counter < 1000; loop_counter++) { scatter<<<gridBlock,threadBlock>>>(in,in_pos,out,out_pos,n,d_histScan,mask,current_bits,nBins); } auto end = steady_clock::now(); auto usecs = duration_cast<duration<float, microseconds::period> >(end - start); cout <<'['<<usecs.count()<<','<<'('<<BLOCKX<<','<<BLOCKY<<')' << ','<<'('<<XSIZE<<','<<YSIZE<<')'<<']' << endl; } }}
5b77239c3957babc7b587f684ab52efd88fa6c4f.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" //===---------- target_impl.cu - NVPTX OpenMP GPU options ------- CUDA -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Definitions of target specific functions // //===----------------------------------------------------------------------===// #pragma omp declare target #include "common/debug.h" #include "target_impl.h" DEVICE void __kmpc_impl_unpack(uint64_t val, uint32_t &lo, uint32_t &hi) { asm volatile("mov.b64 {%0,%1}, %2;" : "=r"(lo), "=r"(hi) : "l"(val)); } DEVICE uint64_t __kmpc_impl_pack(uint32_t lo, uint32_t hi) { uint64_t val; asm volatile("mov.b64 %0, {%1,%2};" : "=l"(val) : "r"(lo), "r"(hi)); return val; } DEVICE __kmpc_impl_lanemask_t __kmpc_impl_lanemask_lt() { __kmpc_impl_lanemask_t res; asm("mov.u32 %0, %%lanemask_lt;" : "=r"(res)); return res; } DEVICE __kmpc_impl_lanemask_t __kmpc_impl_lanemask_gt() { __kmpc_impl_lanemask_t res; asm("mov.u32 %0, %%lanemask_gt;" : "=r"(res)); return res; } DEVICE uint32_t __kmpc_impl_smid() { uint32_t id; asm("mov.u32 %0, %%smid;" : "=r"(id)); return id; } DEVICE double __kmpc_impl_get_wtick() { // Timer precision is 1ns return ((double)1E-9); } DEVICE double __kmpc_impl_get_wtime() { unsigned long long nsecs; asm("mov.u64 %0, %%globaltimer;" : "=l"(nsecs)); return (double)nsecs * __kmpc_impl_get_wtick(); } DEVICE __kmpc_impl_lanemask_t __kmpc_impl_activemask() { unsigned int Mask; asm volatile("activemask.b32 %0;" : "=r"(Mask)); return Mask; } DEVICE void __kmpc_impl_syncthreads() { __syncthreads(); } DEVICE void __kmpc_impl_syncwarp(__kmpc_impl_lanemask_t Mask) { __nvvm_bar_warp_sync(Mask); } // NVPTX specific kernel initialization DEVICE void __kmpc_impl_target_init() { /* nvptx needs no extra setup */ } // Barrier until num_threads arrive. DEVICE void __kmpc_impl_named_sync(uint32_t num_threads) { // The named barrier for active parallel threads of a team in an L1 parallel // region to synchronize with each other. int barrier = 1; asm volatile("bar.sync %0, %1;" : : "r"(barrier), "r"(num_threads) : "memory"); } DEVICE void __kmpc_impl_threadfence() { __nvvm_membar_gl(); } DEVICE void __kmpc_impl_threadfence_block() { __nvvm_membar_cta(); } DEVICE void __kmpc_impl_threadfence_system() { __nvvm_membar_sys(); } // Calls to the NVPTX layer (assuming 1D layout) DEVICE int GetThreadIdInBlock() { return __nvvm_read_ptx_sreg_tid_x(); } DEVICE int GetBlockIdInKernel() { return __nvvm_read_ptx_sreg_ctaid_x(); } DEVICE int GetNumberOfBlocksInKernel() { return __nvvm_read_ptx_sreg_nctaid_x(); } DEVICE int GetNumberOfThreadsInBlock() { return __nvvm_read_ptx_sreg_ntid_x(); } DEVICE unsigned GetWarpId() { return GetThreadIdInBlock() / WARPSIZE; } DEVICE unsigned GetLaneId() { return GetThreadIdInBlock() & (WARPSIZE - 1); } // Atomics DEVICE uint32_t __kmpc_atomic_add(uint32_t *Address, uint32_t Val) { return __atomic_fetch_add(Address, Val, __ATOMIC_SEQ_CST); } DEVICE uint32_t __kmpc_atomic_inc(uint32_t *Address, uint32_t Val) { return __nvvm_atom_inc_gen_ui(Address, Val); } DEVICE uint32_t __kmpc_atomic_max(uint32_t *Address, uint32_t Val) { return __atomic_fetch_max(Address, Val, __ATOMIC_SEQ_CST); } DEVICE uint32_t __kmpc_atomic_exchange(uint32_t *Address, uint32_t Val) { uint32_t R; __atomic_exchange(Address, &Val, &R, __ATOMIC_SEQ_CST); return R; } DEVICE uint32_t __kmpc_atomic_cas(uint32_t *Address, uint32_t Compare, uint32_t Val) { (void)__atomic_compare_exchange(Address, &Compare, &Val, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); return Compare; } DEVICE unsigned long long __kmpc_atomic_exchange(unsigned long long *Address, unsigned long long Val) { unsigned long long R; __atomic_exchange(Address, &Val, &R, __ATOMIC_SEQ_CST); return R; } DEVICE unsigned long long __kmpc_atomic_add(unsigned long long *Address, unsigned long long Val) { return __atomic_fetch_add(Address, Val, __ATOMIC_SEQ_CST); } #define __OMP_SPIN 1000 #define UNSET 0u #define SET 1u DEVICE void __kmpc_impl_init_lock(omp_lock_t *lock) { __kmpc_impl_unset_lock(lock); } DEVICE void __kmpc_impl_destroy_lock(omp_lock_t *lock) { __kmpc_impl_unset_lock(lock); } DEVICE void __kmpc_impl_set_lock(omp_lock_t *lock) { // TODO: not sure spinning is a good idea here.. while (__kmpc_atomic_cas(lock, UNSET, SET) != UNSET) { int32_t start = __nvvm_read_ptx_sreg_clock(); int32_t now; for (;;) { now = __nvvm_read_ptx_sreg_clock(); int32_t cycles = now > start ? now - start : now + (0xffffffff - start); if (cycles >= __OMP_SPIN * GetBlockIdInKernel()) { break; } } } // wait for 0 to be the read value } DEVICE void __kmpc_impl_unset_lock(omp_lock_t *lock) { (void)__kmpc_atomic_exchange(lock, UNSET); } DEVICE int __kmpc_impl_test_lock(omp_lock_t *lock) { return __kmpc_atomic_add(lock, 0u); } DEVICE void *__kmpc_impl_malloc(size_t x) { return malloc(x); } DEVICE void __kmpc_impl_free(void *x) { free(x); } #pragma omp end declare target
5b77239c3957babc7b587f684ab52efd88fa6c4f.cu
//===---------- target_impl.cu - NVPTX OpenMP GPU options ------- CUDA -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // Definitions of target specific functions // //===----------------------------------------------------------------------===// #pragma omp declare target #include "common/debug.h" #include "target_impl.h" DEVICE void __kmpc_impl_unpack(uint64_t val, uint32_t &lo, uint32_t &hi) { asm volatile("mov.b64 {%0,%1}, %2;" : "=r"(lo), "=r"(hi) : "l"(val)); } DEVICE uint64_t __kmpc_impl_pack(uint32_t lo, uint32_t hi) { uint64_t val; asm volatile("mov.b64 %0, {%1,%2};" : "=l"(val) : "r"(lo), "r"(hi)); return val; } DEVICE __kmpc_impl_lanemask_t __kmpc_impl_lanemask_lt() { __kmpc_impl_lanemask_t res; asm("mov.u32 %0, %%lanemask_lt;" : "=r"(res)); return res; } DEVICE __kmpc_impl_lanemask_t __kmpc_impl_lanemask_gt() { __kmpc_impl_lanemask_t res; asm("mov.u32 %0, %%lanemask_gt;" : "=r"(res)); return res; } DEVICE uint32_t __kmpc_impl_smid() { uint32_t id; asm("mov.u32 %0, %%smid;" : "=r"(id)); return id; } DEVICE double __kmpc_impl_get_wtick() { // Timer precision is 1ns return ((double)1E-9); } DEVICE double __kmpc_impl_get_wtime() { unsigned long long nsecs; asm("mov.u64 %0, %%globaltimer;" : "=l"(nsecs)); return (double)nsecs * __kmpc_impl_get_wtick(); } DEVICE __kmpc_impl_lanemask_t __kmpc_impl_activemask() { unsigned int Mask; asm volatile("activemask.b32 %0;" : "=r"(Mask)); return Mask; } DEVICE void __kmpc_impl_syncthreads() { __syncthreads(); } DEVICE void __kmpc_impl_syncwarp(__kmpc_impl_lanemask_t Mask) { __nvvm_bar_warp_sync(Mask); } // NVPTX specific kernel initialization DEVICE void __kmpc_impl_target_init() { /* nvptx needs no extra setup */ } // Barrier until num_threads arrive. DEVICE void __kmpc_impl_named_sync(uint32_t num_threads) { // The named barrier for active parallel threads of a team in an L1 parallel // region to synchronize with each other. int barrier = 1; asm volatile("bar.sync %0, %1;" : : "r"(barrier), "r"(num_threads) : "memory"); } DEVICE void __kmpc_impl_threadfence() { __nvvm_membar_gl(); } DEVICE void __kmpc_impl_threadfence_block() { __nvvm_membar_cta(); } DEVICE void __kmpc_impl_threadfence_system() { __nvvm_membar_sys(); } // Calls to the NVPTX layer (assuming 1D layout) DEVICE int GetThreadIdInBlock() { return __nvvm_read_ptx_sreg_tid_x(); } DEVICE int GetBlockIdInKernel() { return __nvvm_read_ptx_sreg_ctaid_x(); } DEVICE int GetNumberOfBlocksInKernel() { return __nvvm_read_ptx_sreg_nctaid_x(); } DEVICE int GetNumberOfThreadsInBlock() { return __nvvm_read_ptx_sreg_ntid_x(); } DEVICE unsigned GetWarpId() { return GetThreadIdInBlock() / WARPSIZE; } DEVICE unsigned GetLaneId() { return GetThreadIdInBlock() & (WARPSIZE - 1); } // Atomics DEVICE uint32_t __kmpc_atomic_add(uint32_t *Address, uint32_t Val) { return __atomic_fetch_add(Address, Val, __ATOMIC_SEQ_CST); } DEVICE uint32_t __kmpc_atomic_inc(uint32_t *Address, uint32_t Val) { return __nvvm_atom_inc_gen_ui(Address, Val); } DEVICE uint32_t __kmpc_atomic_max(uint32_t *Address, uint32_t Val) { return __atomic_fetch_max(Address, Val, __ATOMIC_SEQ_CST); } DEVICE uint32_t __kmpc_atomic_exchange(uint32_t *Address, uint32_t Val) { uint32_t R; __atomic_exchange(Address, &Val, &R, __ATOMIC_SEQ_CST); return R; } DEVICE uint32_t __kmpc_atomic_cas(uint32_t *Address, uint32_t Compare, uint32_t Val) { (void)__atomic_compare_exchange(Address, &Compare, &Val, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST); return Compare; } DEVICE unsigned long long __kmpc_atomic_exchange(unsigned long long *Address, unsigned long long Val) { unsigned long long R; __atomic_exchange(Address, &Val, &R, __ATOMIC_SEQ_CST); return R; } DEVICE unsigned long long __kmpc_atomic_add(unsigned long long *Address, unsigned long long Val) { return __atomic_fetch_add(Address, Val, __ATOMIC_SEQ_CST); } #define __OMP_SPIN 1000 #define UNSET 0u #define SET 1u DEVICE void __kmpc_impl_init_lock(omp_lock_t *lock) { __kmpc_impl_unset_lock(lock); } DEVICE void __kmpc_impl_destroy_lock(omp_lock_t *lock) { __kmpc_impl_unset_lock(lock); } DEVICE void __kmpc_impl_set_lock(omp_lock_t *lock) { // TODO: not sure spinning is a good idea here.. while (__kmpc_atomic_cas(lock, UNSET, SET) != UNSET) { int32_t start = __nvvm_read_ptx_sreg_clock(); int32_t now; for (;;) { now = __nvvm_read_ptx_sreg_clock(); int32_t cycles = now > start ? now - start : now + (0xffffffff - start); if (cycles >= __OMP_SPIN * GetBlockIdInKernel()) { break; } } } // wait for 0 to be the read value } DEVICE void __kmpc_impl_unset_lock(omp_lock_t *lock) { (void)__kmpc_atomic_exchange(lock, UNSET); } DEVICE int __kmpc_impl_test_lock(omp_lock_t *lock) { return __kmpc_atomic_add(lock, 0u); } DEVICE void *__kmpc_impl_malloc(size_t x) { return malloc(x); } DEVICE void __kmpc_impl_free(void *x) { free(x); } #pragma omp end declare target
375adf0ede2166eed7fe8e21e8918467a4c854d9.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* -- MAGMA (version 1.6.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2014 @generated from zpotf2.cu normal z -> s, Sat Nov 15 19:53:59 2014 */ #include "common_magma.h" #define PRECISION_s //#if (GPUSHMEM < 200) #define sdot_max_bs 512 // 512 is max threads for 1.x cards //#else //#define sdot_max_bs 1024 //#endif void spotf2_sscal(magma_int_t n, float *x, magma_int_t incx); void spotf2_sdot(magma_int_t n, float *x, magma_int_t incx); #if defined(PRECISION_z) || defined(PRECISION_c) void slacgv(magma_int_t n, float *x, magma_int_t incx); #endif /** Purpose ------- spotf2 computes the Cholesky factorization of a real symmetric positive definite matrix A. The factorization has the form A = U**H * U, if UPLO = MagmaUpper, or A = L * L**H, if UPLO = MagmaLower, where U is an upper triangular matrix and L is lower triangular. This is the unblocked version of the algorithm, calling Level 2 BLAS. Arguments --------- @param[in] uplo magma_uplo_t Specifies whether the upper or lower triangular part of the symmetric matrix A is stored. - = MagmaUpper: Upper triangular - = MagmaLower: Lower triangular @param[in] n INTEGER The order of the matrix A. N >= 0 and N <= 512. @param[in,out] dA REAL array, dimension (LDDA,N) On entry, the symmetric matrix A. If UPLO = MagmaUpper, the leading n by n upper triangular part of A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced. If UPLO = MagmaLower, the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. \n On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U**H * U or A = L * L**H. @param[in] ldda INTEGER The leading dimension of the array A. LDDA >= max(1,N). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -k, the k-th argument had an illegal value - > 0: if INFO = k, the leading minor of order k is not positive definite, and the factorization could not be completed. @ingroup magma_sposv_aux ********************************************************************/ extern "C" magma_int_t magma_spotf2_gpu( magma_uplo_t uplo, magma_int_t n, magmaFloat_ptr dA, magma_int_t ldda, magma_int_t *info ) { #define dA(i_, j_) (dA + (i_) + (j_)*ldda) magma_int_t j; *info = 0; if ( uplo != MagmaUpper && uplo != MagmaLower) { *info = -1; } else if (n < 0 || n > sdot_max_bs) { *info = -2; } else if (ldda < max(1,n)) { *info = -4; } if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } // Quick return if possible if (n == 0) { return *info; } float alpha = MAGMA_S_NEG_ONE; float beta = MAGMA_S_ONE; if (uplo == MagmaUpper) { for(j = 0; j < n; j++) { spotf2_sdot(j, dA(0,j), 1); // including sdot product and update a(j,j) if (j < n) { #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(0, j), 1); #endif magma_sgemv( MagmaTrans, j, n-j-1, alpha, dA(0, j+1), ldda, dA(0, j), 1, beta, dA(j, j+1), ldda); #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(0, j), 1); #endif spotf2_sscal(n-j, dA(j,j), ldda); } } } else { for(j = 0; j < n; j++) { spotf2_sdot(j, dA(j,0), ldda); // including sdot product and update a(j,j) if (j < n) { #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(j, 0), ldda); #endif magma_sgemv( MagmaNoTrans, n-j-1, j, alpha, dA(j+1, 0), ldda, dA(j,0), ldda, beta, dA(j+1, j), 1 ); #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(j, 0), ldda); #endif spotf2_sscal(n-j, dA(j,j), 1); } } } return *info; } #define sscal_bs 32 #define sdot_bs 512 #define slacgv_bs 512 // dynamically allocated shared memory, set to size number of threads when the kernel is launched. // See CUDA Guide B.2.3 extern __shared__ float shared_data[]; __global__ void kernel_sdot(int n, float *x, int incx, int threadSize) { int tx = threadIdx.x; float *sdata = shared_data; float res = MAGMA_S_ZERO; if (tx < n) { res = x[tx*incx]; } sdata[tx] = MAGMA_S_REAL(res * MAGMA_S_CNJG(res)); __syncthreads(); for(int s = blockDim.x/2; s > 32; s >>= 1 ) { if (tx < s) { sdata[tx] += sdata[tx+s]; } __syncthreads(); } if (tx < 32) { volatile float* smem = sdata; smem[tx] += smem[tx+32]; smem[tx] += smem[tx+16]; smem[tx] += smem[tx+8]; smem[tx] += smem[tx+4]; smem[tx] += smem[tx+2]; smem[tx] += smem[tx+1]; } if (tx == 0) { float xreal = MAGMA_S_REAL(x[n*incx]); x[n*incx] = MAGMA_S_MAKE( sqrt(xreal - sdata[0]), 0 ); } } void spotf2_sdot(magma_int_t n, float *x, magma_int_t incx) { /* Specialized Sdot 1) performs sdot sum = x[0:n-1]*conj(x[0:n-1]) 2) updates x[n] = sqrt(x[n]-sum); */ if (n > sdot_max_bs) { fprintf( stderr, "n = %d > %d is not supported in spotf2_sdot\n", (int) n, (int) sdot_max_bs); return; } int threadSize; if (n <= 1024 && n > 512) { threadSize = 1024; } else if (n <= 512 && n > 256 ) { threadSize = 512; } else if (n <= 256 && n > 128) { threadSize = 256; } else if (n <= 128 && n > 64) { threadSize = 128; } else { threadSize = 64; } hipLaunchKernelGGL(( kernel_sdot), dim3(1), dim3(threadSize), threadSize * sizeof(float), magma_stream, n, x, incx, threadSize); } __global__ void kernel_sscal(int n, float *x, int incx) { int id = blockIdx.x * sscal_bs + threadIdx.x; __shared__ float factor; if (threadIdx.x == 0) { factor = MAGMA_S_MAKE(1.0/MAGMA_S_REAL(x[0]), 0.0); } __syncthreads(); if ( id < n && id >0) { x[id*incx] = x[id*incx] * factor; } } void spotf2_sscal(magma_int_t n, float *x, magma_int_t incx) { /* Specialized Sscal perform x[1:n-1]/x[0] */ dim3 threads(sscal_bs, 1, 1); int num_blocks = (n - 1)/sscal_bs + 1; dim3 grid(num_blocks,1); hipLaunchKernelGGL(( kernel_sscal), dim3(grid), dim3(threads), 0, magma_stream , n, x, incx); } #if defined(PRECISION_z) || defined(PRECISION_c) __global__ void kernel_slacgv(int n, float *x, int incx) { int id = blockIdx.x * slacgv_bs + threadIdx.x; if ( id < n ) { x[id*incx] = MAGMA_S_CNJG(x[id*incx]); } } /** Purpose ------- SLACGV conjugates a real vector of length N. Arguments --------- @param[in] n INTEGER The length of the vector X. N >= 0. @param[in,out] x REAL array, dimension (1+(N-1)*abs(INCX)) On entry, the vector of length N to be conjugated. On exit, X is overwritten with conjg(X). @param[in] incx INTEGER The spacing between successive elements of X. @ingroup magma_sposv_aux ********************************************************************/ void slacgv(magma_int_t n, float *x, magma_int_t incx) { dim3 threads(slacgv_bs, 1, 1); int num_blocks = (n - 1)/slacgv_bs + 1; dim3 grid(num_blocks,1); hipLaunchKernelGGL(( kernel_slacgv), dim3(grid), dim3(threads), 0, magma_stream , n, x, incx); } #endif // defined(PRECISION_z) || defined(PRECISION_c)
375adf0ede2166eed7fe8e21e8918467a4c854d9.cu
/* -- MAGMA (version 1.6.0) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date November 2014 @generated from zpotf2.cu normal z -> s, Sat Nov 15 19:53:59 2014 */ #include "common_magma.h" #define PRECISION_s //#if (GPUSHMEM < 200) #define sdot_max_bs 512 // 512 is max threads for 1.x cards //#else //#define sdot_max_bs 1024 //#endif void spotf2_sscal(magma_int_t n, float *x, magma_int_t incx); void spotf2_sdot(magma_int_t n, float *x, magma_int_t incx); #if defined(PRECISION_z) || defined(PRECISION_c) void slacgv(magma_int_t n, float *x, magma_int_t incx); #endif /** Purpose ------- spotf2 computes the Cholesky factorization of a real symmetric positive definite matrix A. The factorization has the form A = U**H * U, if UPLO = MagmaUpper, or A = L * L**H, if UPLO = MagmaLower, where U is an upper triangular matrix and L is lower triangular. This is the unblocked version of the algorithm, calling Level 2 BLAS. Arguments --------- @param[in] uplo magma_uplo_t Specifies whether the upper or lower triangular part of the symmetric matrix A is stored. - = MagmaUpper: Upper triangular - = MagmaLower: Lower triangular @param[in] n INTEGER The order of the matrix A. N >= 0 and N <= 512. @param[in,out] dA REAL array, dimension (LDDA,N) On entry, the symmetric matrix A. If UPLO = MagmaUpper, the leading n by n upper triangular part of A contains the upper triangular part of the matrix A, and the strictly lower triangular part of A is not referenced. If UPLO = MagmaLower, the leading n by n lower triangular part of A contains the lower triangular part of the matrix A, and the strictly upper triangular part of A is not referenced. \n On exit, if INFO = 0, the factor U or L from the Cholesky factorization A = U**H * U or A = L * L**H. @param[in] ldda INTEGER The leading dimension of the array A. LDDA >= max(1,N). @param[out] info INTEGER - = 0: successful exit - < 0: if INFO = -k, the k-th argument had an illegal value - > 0: if INFO = k, the leading minor of order k is not positive definite, and the factorization could not be completed. @ingroup magma_sposv_aux ********************************************************************/ extern "C" magma_int_t magma_spotf2_gpu( magma_uplo_t uplo, magma_int_t n, magmaFloat_ptr dA, magma_int_t ldda, magma_int_t *info ) { #define dA(i_, j_) (dA + (i_) + (j_)*ldda) magma_int_t j; *info = 0; if ( uplo != MagmaUpper && uplo != MagmaLower) { *info = -1; } else if (n < 0 || n > sdot_max_bs) { *info = -2; } else if (ldda < max(1,n)) { *info = -4; } if (*info != 0) { magma_xerbla( __func__, -(*info) ); return *info; } // Quick return if possible if (n == 0) { return *info; } float alpha = MAGMA_S_NEG_ONE; float beta = MAGMA_S_ONE; if (uplo == MagmaUpper) { for(j = 0; j < n; j++) { spotf2_sdot(j, dA(0,j), 1); // including sdot product and update a(j,j) if (j < n) { #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(0, j), 1); #endif magma_sgemv( MagmaTrans, j, n-j-1, alpha, dA(0, j+1), ldda, dA(0, j), 1, beta, dA(j, j+1), ldda); #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(0, j), 1); #endif spotf2_sscal(n-j, dA(j,j), ldda); } } } else { for(j = 0; j < n; j++) { spotf2_sdot(j, dA(j,0), ldda); // including sdot product and update a(j,j) if (j < n) { #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(j, 0), ldda); #endif magma_sgemv( MagmaNoTrans, n-j-1, j, alpha, dA(j+1, 0), ldda, dA(j,0), ldda, beta, dA(j+1, j), 1 ); #if defined(PRECISION_z) || defined(PRECISION_c) slacgv(j, dA(j, 0), ldda); #endif spotf2_sscal(n-j, dA(j,j), 1); } } } return *info; } #define sscal_bs 32 #define sdot_bs 512 #define slacgv_bs 512 // dynamically allocated shared memory, set to size number of threads when the kernel is launched. // See CUDA Guide B.2.3 extern __shared__ float shared_data[]; __global__ void kernel_sdot(int n, float *x, int incx, int threadSize) { int tx = threadIdx.x; float *sdata = shared_data; float res = MAGMA_S_ZERO; if (tx < n) { res = x[tx*incx]; } sdata[tx] = MAGMA_S_REAL(res * MAGMA_S_CNJG(res)); __syncthreads(); for(int s = blockDim.x/2; s > 32; s >>= 1 ) { if (tx < s) { sdata[tx] += sdata[tx+s]; } __syncthreads(); } if (tx < 32) { volatile float* smem = sdata; smem[tx] += smem[tx+32]; smem[tx] += smem[tx+16]; smem[tx] += smem[tx+8]; smem[tx] += smem[tx+4]; smem[tx] += smem[tx+2]; smem[tx] += smem[tx+1]; } if (tx == 0) { float xreal = MAGMA_S_REAL(x[n*incx]); x[n*incx] = MAGMA_S_MAKE( sqrt(xreal - sdata[0]), 0 ); } } void spotf2_sdot(magma_int_t n, float *x, magma_int_t incx) { /* Specialized Sdot 1) performs sdot sum = x[0:n-1]*conj(x[0:n-1]) 2) updates x[n] = sqrt(x[n]-sum); */ if (n > sdot_max_bs) { fprintf( stderr, "n = %d > %d is not supported in spotf2_sdot\n", (int) n, (int) sdot_max_bs); return; } int threadSize; if (n <= 1024 && n > 512) { threadSize = 1024; } else if (n <= 512 && n > 256 ) { threadSize = 512; } else if (n <= 256 && n > 128) { threadSize = 256; } else if (n <= 128 && n > 64) { threadSize = 128; } else { threadSize = 64; } kernel_sdot<<< 1, threadSize, threadSize * sizeof(float), magma_stream>>> (n, x, incx, threadSize); } __global__ void kernel_sscal(int n, float *x, int incx) { int id = blockIdx.x * sscal_bs + threadIdx.x; __shared__ float factor; if (threadIdx.x == 0) { factor = MAGMA_S_MAKE(1.0/MAGMA_S_REAL(x[0]), 0.0); } __syncthreads(); if ( id < n && id >0) { x[id*incx] = x[id*incx] * factor; } } void spotf2_sscal(magma_int_t n, float *x, magma_int_t incx) { /* Specialized Sscal perform x[1:n-1]/x[0] */ dim3 threads(sscal_bs, 1, 1); int num_blocks = (n - 1)/sscal_bs + 1; dim3 grid(num_blocks,1); kernel_sscal<<< grid, threads, 0, magma_stream >>> (n, x, incx); } #if defined(PRECISION_z) || defined(PRECISION_c) __global__ void kernel_slacgv(int n, float *x, int incx) { int id = blockIdx.x * slacgv_bs + threadIdx.x; if ( id < n ) { x[id*incx] = MAGMA_S_CNJG(x[id*incx]); } } /** Purpose ------- SLACGV conjugates a real vector of length N. Arguments --------- @param[in] n INTEGER The length of the vector X. N >= 0. @param[in,out] x REAL array, dimension (1+(N-1)*abs(INCX)) On entry, the vector of length N to be conjugated. On exit, X is overwritten with conjg(X). @param[in] incx INTEGER The spacing between successive elements of X. @ingroup magma_sposv_aux ********************************************************************/ void slacgv(magma_int_t n, float *x, magma_int_t incx) { dim3 threads(slacgv_bs, 1, 1); int num_blocks = (n - 1)/slacgv_bs + 1; dim3 grid(num_blocks,1); kernel_slacgv<<< grid, threads, 0, magma_stream >>> (n, x, incx); } #endif // defined(PRECISION_z) || defined(PRECISION_c)
b460dd908a2d2013e595afd9bb5d5eec064c7982.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include"MGPU_Cufft.h" #include "cuda_aid.cuh" extern int cufftMultiGPUPlan(GPU_INFO *gpu_info,int NGPU,int Nx,int Ny,int Nz,MGPU_HANDLE *mgpu_handle){ mgpu_handle->rank_xy=2; mgpu_handle->rank_z=1; mgpu_handle->Nx=Nx; mgpu_handle->Ny=Ny; mgpu_handle->Nz=Nz; mgpu_handle->plan_z=(hipfftHandle*)malloc(sizeof(hipfftHandle)*NGPU); mgpu_handle->plan_xy=(hipfftHandle*)malloc(sizeof(hipfftHandle)*NGPU); mgpu_handle->plan_xy_back=(hipfftHandle*)malloc(sizeof(hipfftHandle)*NGPU); mgpu_handle->dim_xy[0]=Ny; mgpu_handle->dim_xy[1]=Nx; mgpu_handle->dim_z[0]=Nz; mgpu_handle->NxNy=Nx*Ny; mgpu_handle->Nxh1=Nx/2+1; mgpu_handle->Nz_cu=mgpu_handle->Nz/NGPU; mgpu_handle->Ny_cu=mgpu_handle->Nz/NGPU; mgpu_handle->Nxh1Ny=mgpu_handle->Nxh1*mgpu_handle->Ny; mgpu_handle->Nxh1Ny_cu=mgpu_handle->Nxh1*Ny/NGPU; mgpu_handle->Nx_block=mgpu_handle->Nxh1; mgpu_handle->Ny_block=Ny/NGPU; mgpu_handle->Nz_block=Nz/NGPU; mgpu_handle->trans_block_size=mgpu_handle->Nxh1*Ny*Nz/(NGPU*NGPU); //printf("%d %d %d\n",Nx,Ny,Nz); //printf("%d %d %d\n",mgpu_handle->trans_block_size,mgpu_handle->Nxh1Ny_cu,mgpu_handle->Nxh1); for (int i=0; i < gpu_info->GPU_N; i++){ checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[i])); checkCufft(hipfftPlanMany(&mgpu_handle->plan_xy[i],mgpu_handle->rank_xy,mgpu_handle->dim_xy,NULL,1,0,NULL,1,0,HIPFFT_D2Z,mgpu_handle->Nz_cu)); hipDeviceSynchronize(); checkCufft(hipfftPlanMany(&mgpu_handle->plan_xy_back[i],mgpu_handle->rank_xy,mgpu_handle->dim_xy,NULL,1,0,NULL,1,0,HIPFFT_Z2D,mgpu_handle->Nz_cu)); checkCufft(hipfftPlanMany(&mgpu_handle->plan_z[i],mgpu_handle->rank_z,mgpu_handle->dim_z,NULL,1,0,NULL,1,0,HIPFFT_Z2Z,mgpu_handle->Nxh1Ny_cu)); hipDeviceSynchronize(); } printf("all init\n"); mgpu_handle->Trans_matrix.resize(gpu_info->GPU_N*(gpu_info->GPU_N)); for (int i=0; i < gpu_info->GPU_N; i++){ for (int j=0; j < gpu_info->GPU_N; j++){ checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[i])); checkCudaErrors(hipMalloc(&(mgpu_handle->Trans_matrix[i*(gpu_info->GPU_N)+j]), sizeof(hipfftDoubleComplex)* mgpu_handle->trans_block_size)); } } printf("all init malloc\n"); return 1; } extern int Matrix_Transpose(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<hipfftDoubleComplex*> data_out_cu,std::vector<hipfftDoubleComplex*> data_rotate_cu,int sign){ //! copy data in transpose matrix int gpu_index,block_index; dim3 grid(mgpu_handle->Nxh1,mgpu_handle->Ny_block,mgpu_handle->Nz_block); if(sign==1){ //printf("%d %d %d %d\n",mgpu_handle->Nx_block,mgpu_handle->Ny_block,mgpu_handle->Nz_block,mgpu_handle->Nxh1Ny); for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); for(block_index=0;block_index<gpu_info->GPU_N;block_index++){ hipLaunchKernelGGL(( matrix_transpose_block), dim3(grid),dim3(1), 0, 0, data_out_cu[gpu_index],data_rotate_cu[block_index],block_index,gpu_index,gpu_info->GPU_N); } hipDeviceSynchronize(); } } else if(sign==2){ for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); //display_GPU_Complex_data<<<4,1>>>(data_rotate_cu[gpu_index],gpu_index); for(block_index=0;block_index<gpu_info->GPU_N;block_index++){ hipLaunchKernelGGL(( matrix_transpose_block_back), dim3(grid),dim3(1), 0, 0, data_out_cu[gpu_index],data_rotate_cu[block_index],block_index,gpu_index,gpu_info->GPU_N); } } hipDeviceSynchronize(); } return 0; } extern int FFTMGPU_Exe_Forward(GPU_INFO *gpu_info,CUFFT_INFO *cufft_info,MGPU_HANDLE *mgpu_handle){ ExeGPUD2Z(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,1); ExeGPUZ2Z(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_rotate_cu,1); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,2); return 0; } extern int FFTMGPU_Exe_Backward(GPU_INFO *gpu_info,CUFFT_INFO *cufft_info,MGPU_HANDLE *mgpu_handle){ dim3 grid; int gpu_index; ExeGPUZ2Z(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_rotate_cu,2); hipEvent_t stop,start; hipError_t error; float msecTotal,msec; error=hipEventCreate(&start); error=hipEventCreate(&stop); error=hipEventCreate(&start); error=hipEventCreate(&stop); error=hipEventRecord(start,NULL); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,2); error=hipDeviceSynchronize(); if(error!=hipSuccess) printf("something wrong!before \n"); error=hipEventRecord(stop,NULL); hipEventSynchronize(stop); error=hipEventElapsedTime(&msec,start,stop); printf("time=%0.10f\n",msec); ExeGPUZ2D(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); // return 0; } extern int Test_fft_mgpu(GPU_INFO *gpu_info,CUFFT_INFO *cufft_info,MGPU_HANDLE *mgpu_handle){ int gpu_index; hipfftHandle plan; dim3 grid(cufft_info->Nx,cufft_info->Ny,cufft_info->Nz),block(1,1,1); hipfftDoubleComplex *data_out; hipfftDoubleReal *data_in; hipMalloc((void**)&data_in,sizeof(hipfftDoubleReal)*cufft_info->NxNyNz); hipMalloc((void**)&data_out,sizeof(hipfftDoubleComplex)*cufft_info->Nxh1NyNz); checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[0])); hipLaunchKernelGGL(( initialize_GPU_double_data), dim3(grid),dim3(1), 0, 0, data_in,0,cufft_info->NxNyNz); for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); hipLaunchKernelGGL(( initialize_GPU_double_data), dim3(grid),dim3(1), 0, 0, cufft_info->device_in_cu[gpu_index],gpu_index,cufft_info->NxNyNz_gpu); //initialize_GPU_cufftDoubleComplex_data2<<<8,block>>>(cufft_info->device_out_cu[gpu_index],gpu_index,cufft_info->Nxh1NyNz_gpu); hipDeviceSynchronize(); } for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); hipStreamSynchronize(cufft_info->stream[gpu_index]); } int n[3]={256,256,256}; if (hipfftPlanMany(&plan, 3, n, NULL, 1, 16, NULL, 1, 0, HIPFFT_Z2D,1) != HIPFFT_SUCCESS){ fprintf(stderr, "CUFFT Error: Unable to create plan\n"); return 0; } FFTMGPU_Exe_Forward(gpu_info,cufft_info,mgpu_handle); FFTMGPU_Exe_Backward(gpu_info,cufft_info,mgpu_handle); //hipfftExecD2Z(plan,data_in,data_out); //hipfftExecZ2D(plan,data_out,data_in); /* display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[1],1); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[2],2); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[3],3); /* display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[1],1); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[2],2); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[3],3); /* checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[0])); if (hipfftPlanMany(&plan, 3, n, NULL, 1, 16, NULL, 1, 0, HIPFFT_Z2D,1) != HIPFFT_SUCCESS){ fprintf(stderr, "CUFFT Error: Unable to create plan\n"); return 0; } if (hipfftExecZ2D(plan, data,data_d) != HIPFFT_SUCCESS){ fprintf(stderr, "CUFFT Error: Unable to execute plan\n"); return 0; } if (hipDeviceSynchronize() != hipSuccess){ fprintf(stderr, "Cuda error: Failed to synchronize\n"); return 0; } display_GPU_double_data<<<grid,1>>>(data_d,0); //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); //ExeGPUD2Z(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); /* ExeGPUZ2D(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[gpu_index],gpu_index); } //FFTMGPU_Exe_Forward(gpu_info,cufft_info,mgpu_handle); //FFTMGPU_Exe_Backward(gpu_info,cufft_info,mgpu_handle); getLastCudaError("reduceKernel() execution failed.\n"); grid.x=cufft_info->Nx;grid.y=cufft_info->Ny;grid.z=cufft_info->Nz_cu; for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); hipStreamSynchronize(cufft_info->stream[gpu_index]); } printf("results----------------\n"); /* display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[1],1); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[2],2); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[3],3); /* grid.x=cufft_info->Nxh1;grid.y=cufft_info->Ny;grid.z=cufft_info->Nz_cu; display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); hipDeviceSynchronize(); display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[1],1); hipDeviceSynchronize(); display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[2],2); hipDeviceSynchronize(); display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[3],3); //getCudaLastError(); hipDeviceSynchronize(); grid.x=5;grid.y=8;grid.z=1; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); /* //display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); ExeGPUD2Z(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); grid.x=5;grid.y=8;grid.z=2; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); hipDeviceSynchronize(); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,1); grid.x=cufft_info->Nz;grid.y=1;grid.z=1; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_rotate_cu[0],0); ExeGPUZ2Z(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_rotate_cu); grid.x=5;grid.y=8;grid.z=2; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_rotate_cu[0],0); hipDeviceSynchronize(); printf("--------"); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_out_cu,2); grid.x=5;grid.y=8;grid.z=1; display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); //display_GPU_Complex_pblock_data<<<grid,1>>>(cufft_info->device_rotate_cu[0],0,4); /* for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); if(gpu_index==0){ display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[gpu_index],0);//mgpu_handle->Trans_matrix[i] hipDeviceSynchronize(); //matrix_transpose<<<grid,1>>>(mgpu_handle->Trans_matrix[0]); hipDeviceSynchronize(); printf("-------------\n"); //display_GPU_Complex_data<<<grid,1>>>(mgpu_handle->Trans_matrix[0],0);//mgpu_handle->Trans_matrix[i] hipDeviceSynchronize(); } } */ return 0; } extern int ExeGPUD2Z(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<double*> data_in_cu,std::vector<hipfftDoubleComplex*> data_out_cu){ for (int gpu_index=0; gpu_index < gpu_info->GPU_N; gpu_index++){ checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); checkCufft(hipfftExecD2Z(mgpu_handle->plan_xy[gpu_index],data_in_cu[gpu_index],data_out_cu[gpu_index])); //checkCudaErrors(hipMemcpy(data_in_cu[], g0, buf_size, hipMemcpyDefault)); } hipDeviceSynchronize(); return 0; } extern int ExeGPUZ2D(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<double*> data_in_cu,std::vector<hipfftDoubleComplex*> data_out_cu){ for (int gpu_index=0; gpu_index < gpu_info->GPU_N; gpu_index++){ checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); checkCufft(hipfftExecZ2D(mgpu_handle->plan_xy_back[gpu_index],data_out_cu[gpu_index],data_in_cu[gpu_index])); //checkCudaErrors(hipMemcpy(data_in_cu[], g0, buf_size, hipMemcpyDefault)); } hipDeviceSynchronize(); return 0; } extern int ExeGPUZ2Z(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<hipfftDoubleComplex*> data_out_cu,std::vector<hipfftDoubleComplex*> data_rotate_cu,int sign){ for (int gpu_index=0; gpu_index < gpu_info->GPU_N; gpu_index++){ checkCudaErrors(hipSetDevice(gpu_info->whichGPUs[gpu_index])); if(sign==1){ checkCufft(hipfftExecZ2Z(mgpu_handle->plan_z[gpu_index],data_out_cu[gpu_index],data_rotate_cu[gpu_index],HIPFFT_FORWARD)); } else if(sign==2){ checkCufft(hipfftExecZ2Z(mgpu_handle->plan_z[gpu_index],data_out_cu[gpu_index],data_rotate_cu[gpu_index],HIPFFT_BACKWARD)); } } hipDeviceSynchronize(); return 0; }
b460dd908a2d2013e595afd9bb5d5eec064c7982.cu
#include"MGPU_Cufft.h" #include "cuda_aid.cuh" extern int cufftMultiGPUPlan(GPU_INFO *gpu_info,int NGPU,int Nx,int Ny,int Nz,MGPU_HANDLE *mgpu_handle){ mgpu_handle->rank_xy=2; mgpu_handle->rank_z=1; mgpu_handle->Nx=Nx; mgpu_handle->Ny=Ny; mgpu_handle->Nz=Nz; mgpu_handle->plan_z=(cufftHandle*)malloc(sizeof(cufftHandle)*NGPU); mgpu_handle->plan_xy=(cufftHandle*)malloc(sizeof(cufftHandle)*NGPU); mgpu_handle->plan_xy_back=(cufftHandle*)malloc(sizeof(cufftHandle)*NGPU); mgpu_handle->dim_xy[0]=Ny; mgpu_handle->dim_xy[1]=Nx; mgpu_handle->dim_z[0]=Nz; mgpu_handle->NxNy=Nx*Ny; mgpu_handle->Nxh1=Nx/2+1; mgpu_handle->Nz_cu=mgpu_handle->Nz/NGPU; mgpu_handle->Ny_cu=mgpu_handle->Nz/NGPU; mgpu_handle->Nxh1Ny=mgpu_handle->Nxh1*mgpu_handle->Ny; mgpu_handle->Nxh1Ny_cu=mgpu_handle->Nxh1*Ny/NGPU; mgpu_handle->Nx_block=mgpu_handle->Nxh1; mgpu_handle->Ny_block=Ny/NGPU; mgpu_handle->Nz_block=Nz/NGPU; mgpu_handle->trans_block_size=mgpu_handle->Nxh1*Ny*Nz/(NGPU*NGPU); //printf("%d %d %d\n",Nx,Ny,Nz); //printf("%d %d %d\n",mgpu_handle->trans_block_size,mgpu_handle->Nxh1Ny_cu,mgpu_handle->Nxh1); for (int i=0; i < gpu_info->GPU_N; i++){ checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[i])); checkCufft(cufftPlanMany(&mgpu_handle->plan_xy[i],mgpu_handle->rank_xy,mgpu_handle->dim_xy,NULL,1,0,NULL,1,0,CUFFT_D2Z,mgpu_handle->Nz_cu)); cudaDeviceSynchronize(); checkCufft(cufftPlanMany(&mgpu_handle->plan_xy_back[i],mgpu_handle->rank_xy,mgpu_handle->dim_xy,NULL,1,0,NULL,1,0,CUFFT_Z2D,mgpu_handle->Nz_cu)); checkCufft(cufftPlanMany(&mgpu_handle->plan_z[i],mgpu_handle->rank_z,mgpu_handle->dim_z,NULL,1,0,NULL,1,0,CUFFT_Z2Z,mgpu_handle->Nxh1Ny_cu)); cudaDeviceSynchronize(); } printf("all init\n"); mgpu_handle->Trans_matrix.resize(gpu_info->GPU_N*(gpu_info->GPU_N)); for (int i=0; i < gpu_info->GPU_N; i++){ for (int j=0; j < gpu_info->GPU_N; j++){ checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[i])); checkCudaErrors(cudaMalloc(&(mgpu_handle->Trans_matrix[i*(gpu_info->GPU_N)+j]), sizeof(cufftDoubleComplex)* mgpu_handle->trans_block_size)); } } printf("all init malloc\n"); return 1; } extern int Matrix_Transpose(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<cufftDoubleComplex*> data_out_cu,std::vector<cufftDoubleComplex*> data_rotate_cu,int sign){ //! copy data in transpose matrix int gpu_index,block_index; dim3 grid(mgpu_handle->Nxh1,mgpu_handle->Ny_block,mgpu_handle->Nz_block); if(sign==1){ //printf("%d %d %d %d\n",mgpu_handle->Nx_block,mgpu_handle->Ny_block,mgpu_handle->Nz_block,mgpu_handle->Nxh1Ny); for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); for(block_index=0;block_index<gpu_info->GPU_N;block_index++){ matrix_transpose_block<<<grid,1>>>(data_out_cu[gpu_index],data_rotate_cu[block_index],block_index,gpu_index,gpu_info->GPU_N); } cudaDeviceSynchronize(); } } else if(sign==2){ for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); //display_GPU_Complex_data<<<4,1>>>(data_rotate_cu[gpu_index],gpu_index); for(block_index=0;block_index<gpu_info->GPU_N;block_index++){ matrix_transpose_block_back<<<grid,1>>>(data_out_cu[gpu_index],data_rotate_cu[block_index],block_index,gpu_index,gpu_info->GPU_N); } } cudaDeviceSynchronize(); } return 0; } extern int FFTMGPU_Exe_Forward(GPU_INFO *gpu_info,CUFFT_INFO *cufft_info,MGPU_HANDLE *mgpu_handle){ ExeGPUD2Z(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,1); ExeGPUZ2Z(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_rotate_cu,1); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,2); return 0; } extern int FFTMGPU_Exe_Backward(GPU_INFO *gpu_info,CUFFT_INFO *cufft_info,MGPU_HANDLE *mgpu_handle){ dim3 grid; int gpu_index; ExeGPUZ2Z(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_rotate_cu,2); cudaEvent_t stop,start; cudaError_t error; float msecTotal,msec; error=cudaEventCreate(&start); error=cudaEventCreate(&stop); error=cudaEventCreate(&start); error=cudaEventCreate(&stop); error=cudaEventRecord(start,NULL); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,2); error=cudaDeviceSynchronize(); if(error!=cudaSuccess) printf("something wrong!before \n"); error=cudaEventRecord(stop,NULL); cudaEventSynchronize(stop); error=cudaEventElapsedTime(&msec,start,stop); printf("time=%0.10f\n",msec); ExeGPUZ2D(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); // return 0; } extern int Test_fft_mgpu(GPU_INFO *gpu_info,CUFFT_INFO *cufft_info,MGPU_HANDLE *mgpu_handle){ int gpu_index; cufftHandle plan; dim3 grid(cufft_info->Nx,cufft_info->Ny,cufft_info->Nz),block(1,1,1); cufftDoubleComplex *data_out; cufftDoubleReal *data_in; cudaMalloc((void**)&data_in,sizeof(cufftDoubleReal)*cufft_info->NxNyNz); cudaMalloc((void**)&data_out,sizeof(cufftDoubleComplex)*cufft_info->Nxh1NyNz); checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[0])); initialize_GPU_double_data<<<grid,1>>>(data_in,0,cufft_info->NxNyNz); for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); initialize_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[gpu_index],gpu_index,cufft_info->NxNyNz_gpu); //initialize_GPU_cufftDoubleComplex_data2<<<8,block>>>(cufft_info->device_out_cu[gpu_index],gpu_index,cufft_info->Nxh1NyNz_gpu); cudaDeviceSynchronize(); } for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); cudaStreamSynchronize(cufft_info->stream[gpu_index]); } int n[3]={256,256,256}; if (cufftPlanMany(&plan, 3, n, NULL, 1, 16, NULL, 1, 0, CUFFT_Z2D,1) != CUFFT_SUCCESS){ fprintf(stderr, "CUFFT Error: Unable to create plan\n"); return 0; } FFTMGPU_Exe_Forward(gpu_info,cufft_info,mgpu_handle); FFTMGPU_Exe_Backward(gpu_info,cufft_info,mgpu_handle); //cufftExecD2Z(plan,data_in,data_out); //cufftExecZ2D(plan,data_out,data_in); /* display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[1],1); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[2],2); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[3],3); /* display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[1],1); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[2],2); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[3],3); /* checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[0])); if (cufftPlanMany(&plan, 3, n, NULL, 1, 16, NULL, 1, 0, CUFFT_Z2D,1) != CUFFT_SUCCESS){ fprintf(stderr, "CUFFT Error: Unable to create plan\n"); return 0; } if (cufftExecZ2D(plan, data,data_d) != CUFFT_SUCCESS){ fprintf(stderr, "CUFFT Error: Unable to execute plan\n"); return 0; } if (cudaDeviceSynchronize() != cudaSuccess){ fprintf(stderr, "Cuda error: Failed to synchronize\n"); return 0; } display_GPU_double_data<<<grid,1>>>(data_d,0); //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); //ExeGPUD2Z(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); /* ExeGPUZ2D(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[gpu_index],gpu_index); } //FFTMGPU_Exe_Forward(gpu_info,cufft_info,mgpu_handle); //FFTMGPU_Exe_Backward(gpu_info,cufft_info,mgpu_handle); getLastCudaError("reduceKernel() execution failed.\n"); grid.x=cufft_info->Nx;grid.y=cufft_info->Ny;grid.z=cufft_info->Nz_cu; for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); cudaStreamSynchronize(cufft_info->stream[gpu_index]); } printf("results----------------\n"); /* display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[1],1); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[2],2); display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[3],3); /* grid.x=cufft_info->Nxh1;grid.y=cufft_info->Ny;grid.z=cufft_info->Nz_cu; display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); cudaDeviceSynchronize(); display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[1],1); cudaDeviceSynchronize(); display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[2],2); cudaDeviceSynchronize(); display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[3],3); //getCudaLastError(); cudaDeviceSynchronize(); grid.x=5;grid.y=8;grid.z=1; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); /* //display_GPU_double_data<<<grid,1>>>(cufft_info->device_in_cu[0],0); ExeGPUD2Z(gpu_info,mgpu_handle,cufft_info->device_in_cu,cufft_info->device_out_cu); grid.x=5;grid.y=8;grid.z=2; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); cudaDeviceSynchronize(); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_out_cu,cufft_info->device_rotate_cu,1); grid.x=cufft_info->Nz;grid.y=1;grid.z=1; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_rotate_cu[0],0); ExeGPUZ2Z(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_rotate_cu); grid.x=5;grid.y=8;grid.z=2; //display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_rotate_cu[0],0); cudaDeviceSynchronize(); printf("--------"); Matrix_Transpose(gpu_info,mgpu_handle,cufft_info->device_rotate_cu,cufft_info->device_out_cu,2); grid.x=5;grid.y=8;grid.z=1; display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[0],0); //display_GPU_Complex_pblock_data<<<grid,1>>>(cufft_info->device_rotate_cu[0],0,4); /* for(gpu_index=0;gpu_index<gpu_info->GPU_N;gpu_index++) { checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); if(gpu_index==0){ display_GPU_Complex_data<<<grid,1>>>(cufft_info->device_out_cu[gpu_index],0);//mgpu_handle->Trans_matrix[i] cudaDeviceSynchronize(); //matrix_transpose<<<grid,1>>>(mgpu_handle->Trans_matrix[0]); cudaDeviceSynchronize(); printf("-------------\n"); //display_GPU_Complex_data<<<grid,1>>>(mgpu_handle->Trans_matrix[0],0);//mgpu_handle->Trans_matrix[i] cudaDeviceSynchronize(); } } */ return 0; } extern int ExeGPUD2Z(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<double*> data_in_cu,std::vector<cufftDoubleComplex*> data_out_cu){ for (int gpu_index=0; gpu_index < gpu_info->GPU_N; gpu_index++){ checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); checkCufft(cufftExecD2Z(mgpu_handle->plan_xy[gpu_index],data_in_cu[gpu_index],data_out_cu[gpu_index])); //checkCudaErrors(cudaMemcpy(data_in_cu[], g0, buf_size, cudaMemcpyDefault)); } cudaDeviceSynchronize(); return 0; } extern int ExeGPUZ2D(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<double*> data_in_cu,std::vector<cufftDoubleComplex*> data_out_cu){ for (int gpu_index=0; gpu_index < gpu_info->GPU_N; gpu_index++){ checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); checkCufft(cufftExecZ2D(mgpu_handle->plan_xy_back[gpu_index],data_out_cu[gpu_index],data_in_cu[gpu_index])); //checkCudaErrors(cudaMemcpy(data_in_cu[], g0, buf_size, cudaMemcpyDefault)); } cudaDeviceSynchronize(); return 0; } extern int ExeGPUZ2Z(GPU_INFO *gpu_info,MGPU_HANDLE *mgpu_handle,std::vector<cufftDoubleComplex*> data_out_cu,std::vector<cufftDoubleComplex*> data_rotate_cu,int sign){ for (int gpu_index=0; gpu_index < gpu_info->GPU_N; gpu_index++){ checkCudaErrors(cudaSetDevice(gpu_info->whichGPUs[gpu_index])); if(sign==1){ checkCufft(cufftExecZ2Z(mgpu_handle->plan_z[gpu_index],data_out_cu[gpu_index],data_rotate_cu[gpu_index],CUFFT_FORWARD)); } else if(sign==2){ checkCufft(cufftExecZ2Z(mgpu_handle->plan_z[gpu_index],data_out_cu[gpu_index],data_rotate_cu[gpu_index],CUFFT_INVERSE)); } } cudaDeviceSynchronize(); return 0; }
e0677f803295dc9e4a179176c6e6997171de4ed4.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "cudapars.h" #include "paramssteeringtest1.h" ///////////////////////////////////// // standard imports ///////////////////////////////////// #include <stdio.h> #include <math.h> #include "step.h" ///////////////////////////////////// // kernel function (CUDA device) ///////////////////////////////////// #include "gradops_hdmne5.cuh" __global__ void hyperdifmomsourcene5_parallel(struct params *p, real *w, real *wnew, real *wmod, real *dwn1, real *wd, int order, int ordero, real *wtemp, int field, int dim, int ii, int ii0, real dt) { // compute the global index in the vector from // the number of the current block, blockIdx, // the number of threads per block, blockDim, // and the number of the current thread within the block, threadIdx //int i = blockIdx.x * blockDim.x + threadIdx.x; //int j = blockIdx.y * blockDim.y + threadIdx.y; int iindex = blockIdx.x * blockDim.x + threadIdx.x; int i,j; int ii1; real fip,fim1; int index,k; int ni=p->n[0]; int nj=p->n[1]; //real dt=p->dt; real dy=p->dx[1]; real dx=p->dx[0]; //real g=p->g; // dt=1.0; //dt=0.05; //enum vars rho, mom1, mom2, mom3, energy, b1, b2, b3; int ip,jp,ipg,jpg; jp=iindex/(ni/(p->npgp[0])); ip=iindex-(jp*(ni/(p->npgp[0]))); for(ipg=0;ipg<(p->npgp[0]);ipg++) for(jpg=0;jpg<(p->npgp[1]);jpg++) { i=ip*(p->npgp[0])+ipg; j=jp*(p->npgp[1])+jpg; //if(i>1 && j >1 && i<((p->n[0])-2) && j<((p->n[1])-2)) if(i>0 && j >0 && i<((p->n[0])-1) && j<((p->n[1])-1)) //if( i<((p->n[0])) && j<((p->n[1]))) { // if(i<((p->n[0])) && j<((p->n[1]))) dwn1[fencode_hdmne5(p,i,j,mom1+ii0)]=(grad1_hdmne5(wtemp,p,i,j,tmp7,ii)); // dwn1[fencode_hdmne5(p,i,j,mom1+ii0)]=0.0; } } __syncthreads(); for(ipg=0;ipg<(p->npgp[0]);ipg++) for(jpg=0;jpg<(p->npgp[1]);jpg++) { i=ip*(p->npgp[0])+ipg; j=jp*(p->npgp[1])+jpg; if(i>0 && j >0 && i<((p->n[0])-1) && j<((p->n[1])-1)) // if(i<((p->n[0])) && j<((p->n[1]))) dwn1[fencode_hdmne5(p,i,j,energy)]=(grad1_hdmne5(wtemp,p,i,j,tmp8,ii)); } __syncthreads(); } ///////////////////////////////////// // error checking routine ///////////////////////////////////// void checkErrors_hdmne5ne(char *label) { // we need to synchronise first to catch errors due to // asynchroneous operations that would otherwise // potentially go unnoticed hipError_t err; err = hipDeviceSynchronize(); if (err != hipSuccess) { char *e = (char*) hipGetErrorString(err); fprintf(stderr, "CUDA Error: %s (at %s)", e, label); } err = hipGetLastError(); if (err != hipSuccess) { char *e = (char*) hipGetErrorString(err); fprintf(stderr, "CUDA Error: %s (at %s)", e, label); } } int cuhyperdifmomsourcene5(struct params **p, real **w, real **wnew, struct params **d_p, real **d_w, real **d_wnew, real **d_wmod, real **d_dwn1, real **d_wd, int order, int ordero, real **d_wtemp, int field, int dim, int ii, int ii0, real dt) { //printf("calling propagate solution\n"); //dim3 dimBlock(blocksize, blocksize); //dim3 dimGrid(((*p)->n[0])/dimBlock.x,((*p)->n[1])/dimBlock.y); dim3 dimBlock(dimblock, 1); //dim3 dimGrid(((*p)->n[0])/dimBlock.x,((*p)->n[1])/dimBlock.y); dim3 dimGrid(((*p)->n[0])/dimBlock.x,((*p)->n[1])/dimBlock.y); int numBlocks = (((*p)->n[0])*((*p)->n[1])+numThreadsPerBlock-1) / numThreadsPerBlock; //__global__ void prop_parallel(struct params *p, real *b, real *w, real *wnew, real *wmod, // real *dwn1, real *dwn2, real *dwn3, real *dwn4, real *wd) //init_parallel(struct params *p, real *b, real *u, real *v, real *h) hipLaunchKernelGGL(( hyperdifmomsourcene5_parallel), dim3(numBlocks), dim3(numThreadsPerBlock), 0, 0, *d_p,*d_w,*d_wnew, *d_wmod, *d_dwn1, *d_wd, order,ordero,*d_wtemp, field, dim,ii,ii0,dt); //prop_parallel<<<dimGrid,dimBlock>>>(*d_p,*d_b,*d_u,*d_v,*d_h); //printf("called prop\n"); hipDeviceSynchronize(); //boundary_parallel<<<numBlocks, numThreadsPerBlock>>>(*d_p,*d_b,*d_w,*d_wnew); //printf("called boundary\n"); //hipDeviceSynchronize(); //update_parallel<<<numBlocks, numThreadsPerBlock>>>(*d_p,*d_b,*d_w,*d_wnew); //printf("called update\n"); // hipDeviceSynchronize(); // hipMemcpy(*w, *d_w, NVAR*((*p)->n[0])* ((*p)->n[1])*sizeof(real), hipMemcpyDeviceToHost); //hipMemcpy(*wnew, *d_wnew, NVAR*((*p)->n[0])* ((*p)->n[1])*sizeof(real), hipMemcpyDeviceToHost); //hipMemcpy(*b, *d_b, (((*p)->n[0])* ((*p)->n[1]))*sizeof(real), hipMemcpyDeviceToHost); //checkErrors("copy data from device"); }
e0677f803295dc9e4a179176c6e6997171de4ed4.cu
#include "cudapars.h" #include "paramssteeringtest1.h" ///////////////////////////////////// // standard imports ///////////////////////////////////// #include <stdio.h> #include <math.h> #include "step.h" ///////////////////////////////////// // kernel function (CUDA device) ///////////////////////////////////// #include "gradops_hdmne5.cuh" __global__ void hyperdifmomsourcene5_parallel(struct params *p, real *w, real *wnew, real *wmod, real *dwn1, real *wd, int order, int ordero, real *wtemp, int field, int dim, int ii, int ii0, real dt) { // compute the global index in the vector from // the number of the current block, blockIdx, // the number of threads per block, blockDim, // and the number of the current thread within the block, threadIdx //int i = blockIdx.x * blockDim.x + threadIdx.x; //int j = blockIdx.y * blockDim.y + threadIdx.y; int iindex = blockIdx.x * blockDim.x + threadIdx.x; int i,j; int ii1; real fip,fim1; int index,k; int ni=p->n[0]; int nj=p->n[1]; //real dt=p->dt; real dy=p->dx[1]; real dx=p->dx[0]; //real g=p->g; // dt=1.0; //dt=0.05; //enum vars rho, mom1, mom2, mom3, energy, b1, b2, b3; int ip,jp,ipg,jpg; jp=iindex/(ni/(p->npgp[0])); ip=iindex-(jp*(ni/(p->npgp[0]))); for(ipg=0;ipg<(p->npgp[0]);ipg++) for(jpg=0;jpg<(p->npgp[1]);jpg++) { i=ip*(p->npgp[0])+ipg; j=jp*(p->npgp[1])+jpg; //if(i>1 && j >1 && i<((p->n[0])-2) && j<((p->n[1])-2)) if(i>0 && j >0 && i<((p->n[0])-1) && j<((p->n[1])-1)) //if( i<((p->n[0])) && j<((p->n[1]))) { // if(i<((p->n[0])) && j<((p->n[1]))) dwn1[fencode_hdmne5(p,i,j,mom1+ii0)]=(grad1_hdmne5(wtemp,p,i,j,tmp7,ii)); // dwn1[fencode_hdmne5(p,i,j,mom1+ii0)]=0.0; } } __syncthreads(); for(ipg=0;ipg<(p->npgp[0]);ipg++) for(jpg=0;jpg<(p->npgp[1]);jpg++) { i=ip*(p->npgp[0])+ipg; j=jp*(p->npgp[1])+jpg; if(i>0 && j >0 && i<((p->n[0])-1) && j<((p->n[1])-1)) // if(i<((p->n[0])) && j<((p->n[1]))) dwn1[fencode_hdmne5(p,i,j,energy)]=(grad1_hdmne5(wtemp,p,i,j,tmp8,ii)); } __syncthreads(); } ///////////////////////////////////// // error checking routine ///////////////////////////////////// void checkErrors_hdmne5ne(char *label) { // we need to synchronise first to catch errors due to // asynchroneous operations that would otherwise // potentially go unnoticed cudaError_t err; err = cudaThreadSynchronize(); if (err != cudaSuccess) { char *e = (char*) cudaGetErrorString(err); fprintf(stderr, "CUDA Error: %s (at %s)", e, label); } err = cudaGetLastError(); if (err != cudaSuccess) { char *e = (char*) cudaGetErrorString(err); fprintf(stderr, "CUDA Error: %s (at %s)", e, label); } } int cuhyperdifmomsourcene5(struct params **p, real **w, real **wnew, struct params **d_p, real **d_w, real **d_wnew, real **d_wmod, real **d_dwn1, real **d_wd, int order, int ordero, real **d_wtemp, int field, int dim, int ii, int ii0, real dt) { //printf("calling propagate solution\n"); //dim3 dimBlock(blocksize, blocksize); //dim3 dimGrid(((*p)->n[0])/dimBlock.x,((*p)->n[1])/dimBlock.y); dim3 dimBlock(dimblock, 1); //dim3 dimGrid(((*p)->n[0])/dimBlock.x,((*p)->n[1])/dimBlock.y); dim3 dimGrid(((*p)->n[0])/dimBlock.x,((*p)->n[1])/dimBlock.y); int numBlocks = (((*p)->n[0])*((*p)->n[1])+numThreadsPerBlock-1) / numThreadsPerBlock; //__global__ void prop_parallel(struct params *p, real *b, real *w, real *wnew, real *wmod, // real *dwn1, real *dwn2, real *dwn3, real *dwn4, real *wd) //init_parallel(struct params *p, real *b, real *u, real *v, real *h) hyperdifmomsourcene5_parallel<<<numBlocks, numThreadsPerBlock>>>(*d_p,*d_w,*d_wnew, *d_wmod, *d_dwn1, *d_wd, order,ordero,*d_wtemp, field, dim,ii,ii0,dt); //prop_parallel<<<dimGrid,dimBlock>>>(*d_p,*d_b,*d_u,*d_v,*d_h); //printf("called prop\n"); cudaThreadSynchronize(); //boundary_parallel<<<numBlocks, numThreadsPerBlock>>>(*d_p,*d_b,*d_w,*d_wnew); //printf("called boundary\n"); //cudaThreadSynchronize(); //update_parallel<<<numBlocks, numThreadsPerBlock>>>(*d_p,*d_b,*d_w,*d_wnew); //printf("called update\n"); // cudaThreadSynchronize(); // cudaMemcpy(*w, *d_w, NVAR*((*p)->n[0])* ((*p)->n[1])*sizeof(real), cudaMemcpyDeviceToHost); //cudaMemcpy(*wnew, *d_wnew, NVAR*((*p)->n[0])* ((*p)->n[1])*sizeof(real), cudaMemcpyDeviceToHost); //cudaMemcpy(*b, *d_b, (((*p)->n[0])* ((*p)->n[1]))*sizeof(real), cudaMemcpyDeviceToHost); //checkErrors("copy data from device"); }
b6ce6de510d37afcb5aa046d88dc7f64e715bd91.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <stdlib.h> #include <time.h> #include <GL/glut.h> #include <GL/gl.h> #include <malloc.h> #include <signal.h> #include <hip/hip_runtime_api.h> /****************************************************************************** Displays two grey scale images. On the left is an image that has come from an image processing pipeline, just after colour thresholding. On the right is the result of applying an edge detection convolution operator to the left image. This program performs that convolution. Things to note: - A single unsigned char stores a pixel intensity value. 0 is black, 256 is white. - The colour mode used is GL_LUMINANCE. This uses a single number to represent a pixel's intensity. In this case we want 256 shades of grey, which is best stored in eight bits, so GL_UNSIGNED_BYTE is specified as the pixel data type. To compile adapt the code below wo match your filenames: nvcc -o ip_coursework_006 ip_coursework_006.cu -lglut -lGL -lm To result: ./ip_coursework_006 Dr Kevan Buckley, University of Wolverhampton, 2018 ******************************************************************************/ #define width 100 #define height 72 unsigned char image[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,255,255,0,0,0,0,0,0,0, 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,255,0, 0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255, 255,0,255,255,255,255,0,0,0,0,0,0,255,255,0,0,255,255,255, 0,255,255,255,255,255,255,0,255,255,255,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,0,0,0,0,0,255,255,0,0,255,255,255,255, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,0,0,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,0,0,0,255,0,0,0,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,255,0,0,0,0,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,0,0,0,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,255, 0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,0,255,255,0,0,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,0,255,255,0,255,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,255,0,0,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0, 0,255,0,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,0,0,0,255,0,0,0,0,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,0,255,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,255, 255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,0,0,255,255,0,0,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,255,0,0, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,0,0,255,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,0, 0,255,255,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,255,255,0,0,255,255,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,0, 0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,255,0,0,0,255,255,0,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,255,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,255,0,0, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0, 0,0,0,255,255,255,255,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,255,0,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0, 0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,255,255,255,255,255,255,0,0,255,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,0,255,255,255, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255, 255,255,255,0,0,0,0,0,0,255,255,255,255,0,0,0,0,0,255, 0,0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,0,255,0, 0,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,0,255,255,255,255,255,0,255,255,0,0,0,0,0,0,0, 0,0,0,255,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,0,0,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,255,255,0,0,0,0,0,255,255,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 255,0,0,0,0,255,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,255,255,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,255,0,0,0,255,255,255,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,255, 255,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,255,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,255,255,255,0,0,0,0,0,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,0,0, 0,255,0,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,0,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,255,255,255,0,0,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,0,255,0,0,0,0,0,255,0,0,0,0,0,0,0,255,255,255, 0,0,255,255,255,255,255,255,255,255,0,0,255,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,255,0,0,0, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 255,255,255,255,255,0,255,255,255,255,255,255,255,255,255,255,0,255,255, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0, 255,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0, 0,255,255,255,255,255,255,255,255,255,0,255,255,255,255,255,255,255,255, 255,255,0,255,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,255,255,0,255,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0, 0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,255,255,0,255,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,255,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255, 255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,255,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,255,255,0,0,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,0,255,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,0, 0,255,255,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,255,0,0,0,0,0,255, 255,255,0,255,255,255,255,255,255,255,255,255,0,255,255,255,255,255,255, 255,255,255,255,255,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,0,0,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,255,255,0,255,255,255,255,255,255,255,255,255,255,0,255, 255,255,255,255,255,255,0,0,255,255,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,255,255,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,0,0,0,0,0,0,255,255,0,0,255,255,255,255,255,255, 255,0,255,0,255,255,255,255,255,255,0,0,0,0,255,255,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,255,0, 0,0,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,0,0,255,255,0,0,0,0,0,0,0,0,0,255,0,255,255,0, 0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,0,0,255,0,0,255,0,0,0,0,0,255, 255,255,0,0,0,0,0,0,0,255,0,0,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,0,0,0,255,255,255,0,255,255,255,255,255,255,255,0, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,255,255,255, 255,255,0,0,0,255,255,255,255,255,255,0,255,255,255,255,255,255,255, 255,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,0,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0, 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; unsigned char results[width * height]; //static void key_pressed(unsigned char key, int x, int y); //void stgint callback(int signal_number); //static void display(); //void tidy_and_exit(); __global__ void detect_edges(unsigned char *in, unsigned char *out) { unsigned int i = blockIdx.x ; int x; int y; int b; int d; int f; int h; int r; y = i / 100; x = i - (100 * y); if (x == 0 || y == 0 || x == width - 1 || y == height - 1) { out[i] = 0; } else { b = i + 100; d = i - 1; f = i + 1; h = i - 100; r = (in[i] * 4) + (in[b] * -1) + (in[d] * -1) + (in[f] * -1) + (in[h] * -1); if (r > 0) { // if the result is positive this is an edge pixel out[i] = 255; } else { out[i] = 0; } } } void tidy_and_exit() { exit(0); } void sigint_callback(int signal_number){ printf("\nInterrupt from keyboard\n"); tidy_and_exit(); } static void display() { glClear(GL_COLOR_BUFFER_BIT); glRasterPos4i(-1, -1, 0, 1); glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, image); glRasterPos4i(0, -1, 0, 1); glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, results); glFlush(); } static void key_pressed(unsigned char key, int x, int y) { switch(key){ case 27: // escape tidy_and_exit(); break; default: printf("\nPress escape to exit\n"); break; } } int time_difference(struct timespec *start, struct timespec *finish, long long int *difference) { long long int ds = finish->tv_sec - start->tv_sec; long long int dn = finish->tv_nsec - start->tv_nsec; if(dn < 0 ) { ds--; dn += 1000000000; } *difference = ds * 1000000000 + dn; return !(*difference > 0); } int main(int argc, char **argv) { signal(SIGINT, sigint_callback); printf("image dimensions %dx%d\n", width, height); unsigned char *d_results; unsigned char *d_image; hipMalloc((void**)&d_results, sizeof(unsigned char) * (width * height)); hipMalloc((void**)&d_image, sizeof(unsigned char) * (width * height) ); hipMemcpy(d_image, &image, sizeof(unsigned char) * (width * height), hipMemcpyHostToDevice); hipMemcpy(&d_results, &results, sizeof(unsigned char) * (width * height), hipMemcpyHostToDevice); struct timespec start, finish; long long int time_elapsed; clock_gettime(CLOCK_MONOTONIC, &start); hipLaunchKernelGGL(( detect_edges) , dim3(7200), dim3(1), 0, 0, d_image, d_results); hipDeviceSynchronize(); clock_gettime(CLOCK_MONOTONIC, &finish); time_difference(&start, &finish, &time_elapsed); printf("Time elapsed was %lldns or %0.9lfs\n", time_elapsed, (time_elapsed/1.0e9)); hipMemcpy(&results, d_results, sizeof(unsigned char) * (width * height), hipMemcpyDeviceToHost); hipMemcpy(&image, &d_image, sizeof(unsigned char) * (width * height), hipMemcpyDeviceToHost); hipFree(&d_image); hipFree(&d_results); glutInit(&argc, argv); glutInitWindowSize(width * 2,height); glutInitDisplayMode(GLUT_SINGLE | GLUT_LUMINANCE); glutCreateWindow("6CS005 Image Progessing Courework"); glutDisplayFunc(display); glutKeyboardFunc(key_pressed); glClearColor(0.0, 1.0, 0.0, 1.0); glutMainLoop(); tidy_and_exit(); return 0; }
b6ce6de510d37afcb5aa046d88dc7f64e715bd91.cu
#include <stdio.h> #include <stdlib.h> #include <time.h> #include <GL/glut.h> #include <GL/gl.h> #include <malloc.h> #include <signal.h> #include <cuda_runtime_api.h> /****************************************************************************** Displays two grey scale images. On the left is an image that has come from an image processing pipeline, just after colour thresholding. On the right is the result of applying an edge detection convolution operator to the left image. This program performs that convolution. Things to note: - A single unsigned char stores a pixel intensity value. 0 is black, 256 is white. - The colour mode used is GL_LUMINANCE. This uses a single number to represent a pixel's intensity. In this case we want 256 shades of grey, which is best stored in eight bits, so GL_UNSIGNED_BYTE is specified as the pixel data type. To compile adapt the code below wo match your filenames: nvcc -o ip_coursework_006 ip_coursework_006.cu -lglut -lGL -lm To result: ./ip_coursework_006 Dr Kevan Buckley, University of Wolverhampton, 2018 ******************************************************************************/ #define width 100 #define height 72 unsigned char image[] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,255,255,0,0,0,0,0,0,0, 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,255,0, 0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255, 255,0,255,255,255,255,0,0,0,0,0,0,255,255,0,0,255,255,255, 0,255,255,255,255,255,255,0,255,255,255,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,0,0,0,0,0,255,255,0,0,255,255,255,255, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,0,0,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0, 0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,0,0,0,255,0,0,0,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,255,0,0,0,0,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,0,0,0,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,255, 0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,0,255,255,0,0,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,0,255,255,0,255,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,255,0,0,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0, 0,255,0,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,0,0,0,255,0,0,0,0,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,0,255,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,255, 255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,0,0,255,255,0,0,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,255,0,0, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,0,0,255,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,0, 0,255,255,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,255,255,0,0,255,255,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,0, 0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,255,0,0,0,255,255,0,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,255,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,255,0,0, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0, 0,0,0,255,255,255,255,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,255,0,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0, 0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,255,255,255,255,255,255,0,0,255,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,0,255,255,255, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255, 255,255,255,0,0,0,0,0,0,255,255,255,255,0,0,0,0,0,255, 0,0,0,0,0,0,0,0,0,0,0,0,255,255,0,0,0,255,0, 0,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,0,255,255,255,255,255,0,255,255,0,0,0,0,0,0,0, 0,0,0,255,0,0,0,0,0,0,0,0,0,0,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,0,0,255,0,0,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,255,255,0,0,0,0,0,255,255,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 255,0,0,0,0,255,0,0,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,255,255,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,255,0,0,0,255,255,255,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,255, 255,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,255,0,0,0,0,0,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,255,255,255,0,0,0,0,0,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,0,0,0, 0,255,0,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,0,0,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,255,255,255,0,0,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,0,255,0,0,0,0,0,255,0,0,0,0,0,0,0,255,255,255, 0,0,255,255,255,255,255,255,255,255,0,0,255,0,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,255,0,0,0, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 255,255,255,255,255,0,255,255,255,255,255,255,255,255,255,255,0,255,255, 0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0, 255,255,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0, 0,255,255,255,255,255,255,255,255,255,0,255,255,255,255,255,255,255,255, 255,255,0,255,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,0,255,255,0,255,0,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0, 0,0,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,0,255,255,0,255,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,255,0,0,0,0,0,0,0,0,0,255,255,255,255,255,255,255, 255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,255,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,0,0,255,255,0,0,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,0,255,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,0, 0,255,255,0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,255,0,0,0,0,0,255, 255,255,0,255,255,255,255,255,255,255,255,255,0,255,255,255,255,255,255, 255,255,255,255,255,0,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,0,0,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,255,255,0,255,255,255,255,255,255,255,255,255,255,0,255, 255,255,255,255,255,255,0,0,255,255,0,0,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,0,255,255,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,0,0,0,0,0,0,0,255,255,0,0,255,255,255,255,255,255, 255,0,255,0,255,255,255,255,255,255,0,0,0,0,255,255,0,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,255,255,0, 0,0,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,0,0,0,0,0,0,0,0,0,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 0,0,0,255,255,0,0,0,0,0,0,0,0,0,255,0,255,255,0, 0,0,0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,0,0, 0,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,0,0,0,0,255,0,0,255,0,0,0,0,0,255, 255,255,0,0,0,0,0,0,0,255,0,0,0,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0,0,0, 0,0,0,0,0,0,0,255,255,255,0,255,255,255,255,255,255,255,0, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,0,0,0,0,0,255,255,255, 255,255,0,0,0,255,255,255,255,255,255,0,255,255,255,255,255,255,255, 255,255,255,0,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255, 255,0,0,0,0,255,0,255,255,255,255,255,255,255,255,255,255,255,255, 255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,255,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0, 255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,255,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,255,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; unsigned char results[width * height]; //static void key_pressed(unsigned char key, int x, int y); //void stgint callback(int signal_number); //static void display(); //void tidy_and_exit(); __global__ void detect_edges(unsigned char *in, unsigned char *out) { unsigned int i = blockIdx.x ; int x; int y; int b; int d; int f; int h; int r; y = i / 100; x = i - (100 * y); if (x == 0 || y == 0 || x == width - 1 || y == height - 1) { out[i] = 0; } else { b = i + 100; d = i - 1; f = i + 1; h = i - 100; r = (in[i] * 4) + (in[b] * -1) + (in[d] * -1) + (in[f] * -1) + (in[h] * -1); if (r > 0) { // if the result is positive this is an edge pixel out[i] = 255; } else { out[i] = 0; } } } void tidy_and_exit() { exit(0); } void sigint_callback(int signal_number){ printf("\nInterrupt from keyboard\n"); tidy_and_exit(); } static void display() { glClear(GL_COLOR_BUFFER_BIT); glRasterPos4i(-1, -1, 0, 1); glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, image); glRasterPos4i(0, -1, 0, 1); glDrawPixels(width, height, GL_LUMINANCE, GL_UNSIGNED_BYTE, results); glFlush(); } static void key_pressed(unsigned char key, int x, int y) { switch(key){ case 27: // escape tidy_and_exit(); break; default: printf("\nPress escape to exit\n"); break; } } int time_difference(struct timespec *start, struct timespec *finish, long long int *difference) { long long int ds = finish->tv_sec - start->tv_sec; long long int dn = finish->tv_nsec - start->tv_nsec; if(dn < 0 ) { ds--; dn += 1000000000; } *difference = ds * 1000000000 + dn; return !(*difference > 0); } int main(int argc, char **argv) { signal(SIGINT, sigint_callback); printf("image dimensions %dx%d\n", width, height); unsigned char *d_results; unsigned char *d_image; cudaMalloc((void**)&d_results, sizeof(unsigned char) * (width * height)); cudaMalloc((void**)&d_image, sizeof(unsigned char) * (width * height) ); cudaMemcpy(d_image, &image, sizeof(unsigned char) * (width * height), cudaMemcpyHostToDevice); cudaMemcpy(&d_results, &results, sizeof(unsigned char) * (width * height), cudaMemcpyHostToDevice); struct timespec start, finish; long long int time_elapsed; clock_gettime(CLOCK_MONOTONIC, &start); detect_edges <<<7200, 1>>>(d_image, d_results); cudaThreadSynchronize(); clock_gettime(CLOCK_MONOTONIC, &finish); time_difference(&start, &finish, &time_elapsed); printf("Time elapsed was %lldns or %0.9lfs\n", time_elapsed, (time_elapsed/1.0e9)); cudaMemcpy(&results, d_results, sizeof(unsigned char) * (width * height), cudaMemcpyDeviceToHost); cudaMemcpy(&image, &d_image, sizeof(unsigned char) * (width * height), cudaMemcpyDeviceToHost); cudaFree(&d_image); cudaFree(&d_results); glutInit(&argc, argv); glutInitWindowSize(width * 2,height); glutInitDisplayMode(GLUT_SINGLE | GLUT_LUMINANCE); glutCreateWindow("6CS005 Image Progessing Courework"); glutDisplayFunc(display); glutKeyboardFunc(key_pressed); glClearColor(0.0, 1.0, 0.0, 1.0); glutMainLoop(); tidy_and_exit(); return 0; }
edffee55598faefed8f534f7e01bd2fdb2a2edb8.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/TensorIterator.h> #include <ATen/native/BinaryOps.h> // NOTE: CUDA on Windows requires that the enclosing function // of a __device__ lambda not have internal linkage. namespace at { namespace native { void atan2_kernel_cuda(TensorIteratorBase& iter) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(iter.common_dtype(), "atan2_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { return ::atan2(a, b); }); }); } void hypot_kernel_cuda(TensorIterator& iter) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(iter.common_dtype(), "hypot_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { return ::hypot(a, b); }); }); } REGISTER_DISPATCH(atan2_stub, &atan2_kernel_cuda); REGISTER_DISPATCH(hypot_stub, &hypot_kernel_cuda); }} // namespace at::native
edffee55598faefed8f534f7e01bd2fdb2a2edb8.cu
#include <ATen/Dispatch.h> #include <ATen/native/DispatchStub.h> #include <ATen/native/cuda/Loops.cuh> #include <ATen/native/TensorIterator.h> #include <ATen/native/BinaryOps.h> // NOTE: CUDA on Windows requires that the enclosing function // of a __device__ lambda not have internal linkage. namespace at { namespace native { void atan2_kernel_cuda(TensorIteratorBase& iter) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(iter.common_dtype(), "atan2_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { return ::atan2(a, b); }); }); } void hypot_kernel_cuda(TensorIterator& iter) { AT_DISPATCH_FLOATING_TYPES_AND_HALF(iter.common_dtype(), "hypot_cuda", [&]() { gpu_kernel_with_scalars(iter, []GPU_LAMBDA(scalar_t a, scalar_t b) -> scalar_t { return ::hypot(a, b); }); }); } REGISTER_DISPATCH(atan2_stub, &atan2_kernel_cuda); REGISTER_DISPATCH(hypot_stub, &hypot_kernel_cuda); }} // namespace at::native
8bb052c4ccde83f8ada0ac6f2f8ba4bd4291f874.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" __global__ void transposeNoBankConflicts(float *odata, float *idata, int width, int height) { __shared__ float tile[TILE_DIM][TILE_DIM+1]; int xIndex = blockIdx.x * TILE_DIM + threadIdx.x; int yIndex = blockIdx.y * TILE_DIM + threadIdx.y; int index_in = xIndex + (yIndex)*width; xIndex = blockIdx.y * TILE_DIM + threadIdx.x; yIndex = blockIdx.x * TILE_DIM + threadIdx.y; int index_out = xIndex + (yIndex)*height; for (int i=0; i<TILE_DIM; i+=BLOCK_ROWS) { tile[threadIdx.y+i][threadIdx.x] = idata[index_in+i*width]; } __syncthreads(); for (int i=0; i<TILE_DIM; i+=BLOCK_ROWS) { odata[index_out+i*height] = tile[threadIdx.x][threadIdx.y+i]; } }
8bb052c4ccde83f8ada0ac6f2f8ba4bd4291f874.cu
#include "includes.h" __global__ void transposeNoBankConflicts(float *odata, float *idata, int width, int height) { __shared__ float tile[TILE_DIM][TILE_DIM+1]; int xIndex = blockIdx.x * TILE_DIM + threadIdx.x; int yIndex = blockIdx.y * TILE_DIM + threadIdx.y; int index_in = xIndex + (yIndex)*width; xIndex = blockIdx.y * TILE_DIM + threadIdx.x; yIndex = blockIdx.x * TILE_DIM + threadIdx.y; int index_out = xIndex + (yIndex)*height; for (int i=0; i<TILE_DIM; i+=BLOCK_ROWS) { tile[threadIdx.y+i][threadIdx.x] = idata[index_in+i*width]; } __syncthreads(); for (int i=0; i<TILE_DIM; i+=BLOCK_ROWS) { odata[index_out+i*height] = tile[threadIdx.x][threadIdx.y+i]; } }
4e4e577fa96479e98b6b117eed80d4fb35601cf3.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" extern "C" { __global__ void stanh(const int lengthA, const double alpha, const double *a, double *b) { int i = threadIdx.x + blockIdx.x * blockDim.x; if (i<lengthA) { b[i] = alpha*tanh(a[i]); } } }
4e4e577fa96479e98b6b117eed80d4fb35601cf3.cu
extern "C" { __global__ void stanh(const int lengthA, const double alpha, const double *a, double *b) { int i = threadIdx.x + blockIdx.x * blockDim.x; if (i<lengthA) { b[i] = alpha*tanh(a[i]); } } }
ec383054b3b4d6ceb60c91ac3babdbe78bd573db.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <stdlib.h> #include <hip/hip_runtime.h> #define LEN 1<<22 struct __align__(8) innerStruct { float x; float y; }; inline void checkCuda(hipError_t result) { #if defined(DEBUG) || defined(_DEBUG) if (result != hipSuccess) { printf_s("Error: %s : %d", __FILE__, __LINE__); printf_s("CUDA Runtime Error: %d: %s\n", result, hipGetErrorString(result)); exit(1); } #endif } void initialInnerStruct(innerStruct *ip, int size) { for (int i = 0; i < size; i++) { ip[i].x = (float)(rand() & 0xFF) / 100.0f; } return; } void testInnerStructHost(innerStruct *a, innerStruct *c, const int N) { for (int idx = 0; idx < N; idx++) { c[idx].x = a[idx].x + 10.f; } return; } void checkInnerStruct(innerStruct *hostRef, innerStruct *gpuRef, const int N) { double epsilon = 1.0E-8; bool match = 1; for (int i = 0; i < N; i++) { if (abs(hostRef[i].x - gpuRef[i].x) > epsilon) { match = 0; printf_s("different on %dth element: host %f gpu %f\n", i, hostRef[i].x, gpuRef[i].x); break; } } if (!match) printf("Arrays do not match.\n\n"); } __global__ void testInnerStruct(innerStruct *data, innerStruct * result, const int N) { unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < N) { innerStruct tmp = data[i]; tmp.x += 10.f; result[i] = tmp; } } __global__ void warmup(innerStruct *data, innerStruct * result, const int N) { unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < N) { innerStruct tmp = data[i]; tmp.x += 10.f; result[i] = tmp; } } int main(int argc, char **argv) { // set up device int dev = 0; hipDeviceProp_t deviceProp; checkCuda(hipGetDeviceProperties(&deviceProp, dev)); printf_s("%s test struct of array at ", argv[0]); printf_s("device %d: %s \n", dev, deviceProp.name); checkCuda(hipSetDevice(dev)); // allocate host memory int nElem = LEN; size_t nBytes = nElem * sizeof(innerStruct); innerStruct *h_a = (innerStruct *)malloc(nBytes); innerStruct *hostRef = (innerStruct *)malloc(nBytes); innerStruct *gpuRef = (innerStruct *)malloc(nBytes); // initialize host array initialInnerStruct(h_a, nElem); testInnerStructHost(h_a, hostRef, nElem); // allocate device memory innerStruct *d_a, *d_c; checkCuda(hipMalloc((innerStruct**)&d_a, nBytes)); checkCuda(hipMalloc((innerStruct**)&d_c, nBytes)); // copy data from host to device checkCuda(hipMemcpy(d_a, h_a, nBytes, hipMemcpyHostToDevice)); // set up offset for summaryAU: It is blocksize not offset. int blocksize = 256; if (argc > 1) blocksize = atoi(argv[1]); // execution configuration dim3 block(blocksize, 1); dim3 grid((nElem + block.x - 1) / block.x, 1); // kernel 1: warmup warmup << <grid, block >> >(d_a, d_c, nElem); checkCuda(hipDeviceSynchronize()); printf_s("warmup <<< %3d, %3d >>>\n", grid.x, block.x); checkCuda(hipMemcpy(gpuRef, d_c, nBytes, hipMemcpyDeviceToHost)); checkInnerStruct(hostRef, gpuRef, nElem); // kernel 2: testInnerStruct x only testInnerStruct << <grid, block >> >(d_a, d_c, nElem); checkCuda(hipDeviceSynchronize()); printf_s("innerstruct <<< %3d, %3d >>>\n", grid.x, block.x); checkCuda(hipMemcpy(gpuRef, d_c, nBytes, hipMemcpyDeviceToHost)); checkInnerStruct(hostRef, gpuRef, nElem); // free memories both host and device checkCuda(hipFree(d_a)); checkCuda(hipFree(d_c)); free(h_a); free(hostRef); free(gpuRef); // reset device checkCuda(hipDeviceReset()); return EXIT_SUCCESS; }
ec383054b3b4d6ceb60c91ac3babdbe78bd573db.cu
#include <stdio.h> #include <stdlib.h> #include <cuda_runtime.h> #define LEN 1<<22 struct __align__(8) innerStruct { float x; float y; }; inline void checkCuda(cudaError_t result) { #if defined(DEBUG) || defined(_DEBUG) if (result != cudaSuccess) { printf_s("Error: %s : %d", __FILE__, __LINE__); printf_s("CUDA Runtime Error: %d: %s\n", result, cudaGetErrorString(result)); exit(1); } #endif } void initialInnerStruct(innerStruct *ip, int size) { for (int i = 0; i < size; i++) { ip[i].x = (float)(rand() & 0xFF) / 100.0f; } return; } void testInnerStructHost(innerStruct *a, innerStruct *c, const int N) { for (int idx = 0; idx < N; idx++) { c[idx].x = a[idx].x + 10.f; } return; } void checkInnerStruct(innerStruct *hostRef, innerStruct *gpuRef, const int N) { double epsilon = 1.0E-8; bool match = 1; for (int i = 0; i < N; i++) { if (abs(hostRef[i].x - gpuRef[i].x) > epsilon) { match = 0; printf_s("different on %dth element: host %f gpu %f\n", i, hostRef[i].x, gpuRef[i].x); break; } } if (!match) printf("Arrays do not match.\n\n"); } __global__ void testInnerStruct(innerStruct *data, innerStruct * result, const int N) { unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < N) { innerStruct tmp = data[i]; tmp.x += 10.f; result[i] = tmp; } } __global__ void warmup(innerStruct *data, innerStruct * result, const int N) { unsigned int i = blockIdx.x * blockDim.x + threadIdx.x; if (i < N) { innerStruct tmp = data[i]; tmp.x += 10.f; result[i] = tmp; } } int main(int argc, char **argv) { // set up device int dev = 0; cudaDeviceProp deviceProp; checkCuda(cudaGetDeviceProperties(&deviceProp, dev)); printf_s("%s test struct of array at ", argv[0]); printf_s("device %d: %s \n", dev, deviceProp.name); checkCuda(cudaSetDevice(dev)); // allocate host memory int nElem = LEN; size_t nBytes = nElem * sizeof(innerStruct); innerStruct *h_a = (innerStruct *)malloc(nBytes); innerStruct *hostRef = (innerStruct *)malloc(nBytes); innerStruct *gpuRef = (innerStruct *)malloc(nBytes); // initialize host array initialInnerStruct(h_a, nElem); testInnerStructHost(h_a, hostRef, nElem); // allocate device memory innerStruct *d_a, *d_c; checkCuda(cudaMalloc((innerStruct**)&d_a, nBytes)); checkCuda(cudaMalloc((innerStruct**)&d_c, nBytes)); // copy data from host to device checkCuda(cudaMemcpy(d_a, h_a, nBytes, cudaMemcpyHostToDevice)); // set up offset for summaryAU: It is blocksize not offset. int blocksize = 256; if (argc > 1) blocksize = atoi(argv[1]); // execution configuration dim3 block(blocksize, 1); dim3 grid((nElem + block.x - 1) / block.x, 1); // kernel 1: warmup warmup << <grid, block >> >(d_a, d_c, nElem); checkCuda(cudaDeviceSynchronize()); printf_s("warmup <<< %3d, %3d >>>\n", grid.x, block.x); checkCuda(cudaMemcpy(gpuRef, d_c, nBytes, cudaMemcpyDeviceToHost)); checkInnerStruct(hostRef, gpuRef, nElem); // kernel 2: testInnerStruct x only testInnerStruct << <grid, block >> >(d_a, d_c, nElem); checkCuda(cudaDeviceSynchronize()); printf_s("innerstruct <<< %3d, %3d >>>\n", grid.x, block.x); checkCuda(cudaMemcpy(gpuRef, d_c, nBytes, cudaMemcpyDeviceToHost)); checkInnerStruct(hostRef, gpuRef, nElem); // free memories both host and device checkCuda(cudaFree(d_a)); checkCuda(cudaFree(d_c)); free(h_a); free(hostRef); free(gpuRef); // reset device checkCuda(cudaDeviceReset()); return EXIT_SUCCESS; }
fcb9b816edc38376b9c088c8ff538f2b1107ad54.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* Copyright (c) 2016 PaddlePaddle Authors. 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 "paddle/fluid/operators/math/cross_entropy.h" #include "paddle/fluid/platform/cuda_device_function.h" #include "paddle/fluid/platform/cuda_primitives.h" namespace paddle { namespace operators { namespace math { namespace { __device__ __forceinline__ float real_log(float x) { return logf(x); } __device__ __forceinline__ double real_log(double x) { return log(x); } __device__ __forceinline__ platform::float16 real_log( const platform::float16& val) { return static_cast<platform::float16>(logf(static_cast<float>(val))); } template <typename T> __global__ void CrossEntropyKernel(T* Y, const T* X, const int64_t* label, const int N, const int D, const int ignore_index) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { PADDLE_ASSERT(label[i] >= 0 && label[i] < D || label[i] == ignore_index); Y[i] = ignore_index == label[i] ? static_cast<T>(0) : -math::TolerableValue<T>()(real_log(X[i * D + label[i]])); } } template <typename T> __global__ void SoftCrossEntropyKernel(T* Y, const T* X, const T* label, const int class_num) { int tid = threadIdx.x; T val(0); int idx = blockIdx.x * class_num + tid; int end = blockIdx.x * class_num + class_num; for (; idx < end; idx += blockDim.x) { val += math::TolerableValue<T>()(real_log(X[idx])) * label[idx]; } val = paddle::platform::reduceSum(val, tid, blockDim.x); if (threadIdx.x == 0) { Y[blockIdx.x] = -val; } } } // namespace template <typename T> class CrossEntropyFunctor<platform::CUDADeviceContext, T> { public: void operator()(const platform::CUDADeviceContext& ctx, framework::Tensor* out, const framework::Tensor* prob, const framework::Tensor* labels, bool softLabel, const int ignore_index) { const T* prob_data = prob->data<T>(); T* loss_data = out->mutable_data<T>(ctx.GetPlace()); int batch_size = prob->dims()[0]; int class_num = prob->dims()[1]; if (softLabel) { const T* label_data = labels->data<T>(); int block = class_num > 512 ? 512 : pow(2, static_cast<int>(std::log2(class_num))); hipLaunchKernelGGL(( SoftCrossEntropyKernel<T>), dim3(batch_size), dim3(block), 0, ctx.stream(), loss_data, prob_data, label_data, class_num); } else { const int64_t* label_data = labels->data<int64_t>(); int block = 512; int grid = (batch_size + block - 1) / block; hipLaunchKernelGGL(( CrossEntropyKernel<T>), dim3(grid), dim3(block), 0, ctx.stream(), loss_data, prob_data, label_data, batch_size, class_num, ignore_index); } } }; template class CrossEntropyFunctor<platform::CUDADeviceContext, float>; template class CrossEntropyFunctor<platform::CUDADeviceContext, double>; template class CrossEntropyFunctor<platform::CUDADeviceContext, platform::float16>; } // namespace math } // namespace operators } // namespace paddle
fcb9b816edc38376b9c088c8ff538f2b1107ad54.cu
/* Copyright (c) 2016 PaddlePaddle Authors. 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 "paddle/fluid/operators/math/cross_entropy.h" #include "paddle/fluid/platform/cuda_device_function.h" #include "paddle/fluid/platform/cuda_primitives.h" namespace paddle { namespace operators { namespace math { namespace { __device__ __forceinline__ float real_log(float x) { return logf(x); } __device__ __forceinline__ double real_log(double x) { return log(x); } __device__ __forceinline__ platform::float16 real_log( const platform::float16& val) { return static_cast<platform::float16>(logf(static_cast<float>(val))); } template <typename T> __global__ void CrossEntropyKernel(T* Y, const T* X, const int64_t* label, const int N, const int D, const int ignore_index) { for (int i = blockIdx.x * blockDim.x + threadIdx.x; i < N; i += blockDim.x * gridDim.x) { PADDLE_ASSERT(label[i] >= 0 && label[i] < D || label[i] == ignore_index); Y[i] = ignore_index == label[i] ? static_cast<T>(0) : -math::TolerableValue<T>()(real_log(X[i * D + label[i]])); } } template <typename T> __global__ void SoftCrossEntropyKernel(T* Y, const T* X, const T* label, const int class_num) { int tid = threadIdx.x; T val(0); int idx = blockIdx.x * class_num + tid; int end = blockIdx.x * class_num + class_num; for (; idx < end; idx += blockDim.x) { val += math::TolerableValue<T>()(real_log(X[idx])) * label[idx]; } val = paddle::platform::reduceSum(val, tid, blockDim.x); if (threadIdx.x == 0) { Y[blockIdx.x] = -val; } } } // namespace template <typename T> class CrossEntropyFunctor<platform::CUDADeviceContext, T> { public: void operator()(const platform::CUDADeviceContext& ctx, framework::Tensor* out, const framework::Tensor* prob, const framework::Tensor* labels, bool softLabel, const int ignore_index) { const T* prob_data = prob->data<T>(); T* loss_data = out->mutable_data<T>(ctx.GetPlace()); int batch_size = prob->dims()[0]; int class_num = prob->dims()[1]; if (softLabel) { const T* label_data = labels->data<T>(); int block = class_num > 512 ? 512 : pow(2, static_cast<int>(std::log2(class_num))); SoftCrossEntropyKernel<T><<<batch_size, block, 0, ctx.stream()>>>( loss_data, prob_data, label_data, class_num); } else { const int64_t* label_data = labels->data<int64_t>(); int block = 512; int grid = (batch_size + block - 1) / block; CrossEntropyKernel<T><<<grid, block, 0, ctx.stream()>>>( loss_data, prob_data, label_data, batch_size, class_num, ignore_index); } } }; template class CrossEntropyFunctor<platform::CUDADeviceContext, float>; template class CrossEntropyFunctor<platform::CUDADeviceContext, double>; template class CrossEntropyFunctor<platform::CUDADeviceContext, platform::float16>; } // namespace math } // namespace operators } // namespace paddle
3cb7b1619c772aa1d8b14a7955e232d35e61cb7c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* This is a automatically generated test. Do not modify */ #include <stdio.h> #include <stdlib.h> #include <math.h> __global__ void compute(float comp, int var_1,float var_2,float var_3,float var_4,float var_5,float var_6,float var_7,float var_8,float var_9,float var_10,float var_11,float var_12,float var_13,float var_14) { float tmp_1 = +1.9087E-37f; comp += tmp_1 * var_2 * atan2f(var_3 - +1.9122E-6f * var_4 * (-0.0f / var_5), ceilf((+0.0f - -1.0134E-37f - -1.1554E-42f * var_6))); comp = +0.0f - -1.6493E-42f + (+1.0428E-30f - var_7); for (int i=0; i < var_1; ++i) { comp += (var_8 - var_9); comp += logf(+1.5001E-35f - var_10 / var_11 * var_12 + var_13); comp = atan2f(expf(+0.0f - -1.5600E-22f), -1.0130E36f / +0.0f / (var_14 + -1.2549E-43f)); } printf("%.17g\n", comp); } float* initPointer(float v) { float *ret = (float*) malloc(sizeof(float)*10); for(int i=0; i < 10; ++i) ret[i] = v; return ret; } int main(int argc, char** argv) { /* Program variables */ float tmp_1 = atof(argv[1]); int tmp_2 = atoi(argv[2]); float tmp_3 = atof(argv[3]); float tmp_4 = atof(argv[4]); float tmp_5 = atof(argv[5]); float tmp_6 = atof(argv[6]); float tmp_7 = atof(argv[7]); float tmp_8 = atof(argv[8]); float tmp_9 = atof(argv[9]); float tmp_10 = atof(argv[10]); float tmp_11 = atof(argv[11]); float tmp_12 = atof(argv[12]); float tmp_13 = atof(argv[13]); float tmp_14 = atof(argv[14]); float tmp_15 = atof(argv[15]); hipLaunchKernelGGL(( compute), dim3(1),dim3(1), 0, 0, tmp_1,tmp_2,tmp_3,tmp_4,tmp_5,tmp_6,tmp_7,tmp_8,tmp_9,tmp_10,tmp_11,tmp_12,tmp_13,tmp_14,tmp_15); hipDeviceSynchronize(); return 0; }
3cb7b1619c772aa1d8b14a7955e232d35e61cb7c.cu
/* This is a automatically generated test. Do not modify */ #include <stdio.h> #include <stdlib.h> #include <math.h> __global__ void compute(float comp, int var_1,float var_2,float var_3,float var_4,float var_5,float var_6,float var_7,float var_8,float var_9,float var_10,float var_11,float var_12,float var_13,float var_14) { float tmp_1 = +1.9087E-37f; comp += tmp_1 * var_2 * atan2f(var_3 - +1.9122E-6f * var_4 * (-0.0f / var_5), ceilf((+0.0f - -1.0134E-37f - -1.1554E-42f * var_6))); comp = +0.0f - -1.6493E-42f + (+1.0428E-30f - var_7); for (int i=0; i < var_1; ++i) { comp += (var_8 - var_9); comp += logf(+1.5001E-35f - var_10 / var_11 * var_12 + var_13); comp = atan2f(expf(+0.0f - -1.5600E-22f), -1.0130E36f / +0.0f / (var_14 + -1.2549E-43f)); } printf("%.17g\n", comp); } float* initPointer(float v) { float *ret = (float*) malloc(sizeof(float)*10); for(int i=0; i < 10; ++i) ret[i] = v; return ret; } int main(int argc, char** argv) { /* Program variables */ float tmp_1 = atof(argv[1]); int tmp_2 = atoi(argv[2]); float tmp_3 = atof(argv[3]); float tmp_4 = atof(argv[4]); float tmp_5 = atof(argv[5]); float tmp_6 = atof(argv[6]); float tmp_7 = atof(argv[7]); float tmp_8 = atof(argv[8]); float tmp_9 = atof(argv[9]); float tmp_10 = atof(argv[10]); float tmp_11 = atof(argv[11]); float tmp_12 = atof(argv[12]); float tmp_13 = atof(argv[13]); float tmp_14 = atof(argv[14]); float tmp_15 = atof(argv[15]); compute<<<1,1>>>(tmp_1,tmp_2,tmp_3,tmp_4,tmp_5,tmp_6,tmp_7,tmp_8,tmp_9,tmp_10,tmp_11,tmp_12,tmp_13,tmp_14,tmp_15); cudaDeviceSynchronize(); return 0; }
8602ab93921750e2a467c69971014515144ac884.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* -- MAGMA (version 1.6.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2015 @generated from zhemv_mgpu.cu normal z -> s, Fri Jan 30 19:00:10 2015 @author Mark Gates */ #include "common_magma.h" #include "commonblas_s.h" #define PRECISION_s #define NB_X 64 #define NB_Y 4 #define bank_shift 33 #define quarter_NB_X 16 #define half_NB_X 32 /******************************************************************************* Lower case, compute block multiply, work = A*x, for any size n: [ (A11*x1) (A21^H*x2) (A31^H*x3) ] [ A11 A21^H A31^H ] [ x1 ] work = [ --- (A21*x1 + A22*x2) (A32^H*x3) ] = [ A21 A22 A32^H ] * [ x2 ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] [ A31 A32 A33 ] [ x3 ] Uses a 64x4 thread block. For diagonal tiles, covers a 64x64 tile using three 32x32 tiles (plus one gets transposed). For off-diagonal tiles, covers a 64x64 tile using four 64x16 tiles. In both cases, each thread multiplies 4 elements. For rows past the bottom of the matrix, the A pointer is adjusted to be the last valid row of A, which multiple threads will read. Extra rows are ignored when saving results to work. Columns past the right edge are explicitly ignored when loading. x values past the bottom are set to zero, thus, extra columns are zeroed when multiplying. Previously: [ (A11*x1) --- ] work = [ (A21^H*x2) (A21*x1 + A22*x2) --- ] [ (A31^H*x3) (A32^H*x3) (A31*x1 + A32*x2 + A33*x3) ] which doesn't work as well because that has dimension blocks*NB by blocks, where blocks*NB >= n, and it can be that blocks*NB > lda, so it won't fit in lda*blocks space. This is why it used to need lwork = lda*(blocks + 1). ********************************************************************/ __global__ void ssymv_kernel_L_mgpu( int n, float const * __restrict__ A, int lda, float const * __restrict__ x, int incx, float * __restrict__ work, int my_gpu_id, int ngpu, int block_offset ) { #if (__CUDA_ARCH__ >= 200) // treats sA as 16x64 block #define sA16(i_, j_) (sA[(i_)][(j_)]) // i.e., sA[ (i_)*(NB_X+3) + (j_) ] // treats sA as 32x32 block #define sA32(i_, j_) (sA[0][(i_) + bank_shift*(j_)]) // 64x4 thread block const int tx = threadIdx.x; const int ty = threadIdx.y; const int blk = blockIdx.x; const int blk_ind = NB_X * blk; const int td = NB_X * ty + tx; // GPUs are renumbered so that GPU 0 starts with block 0, GPU 1 starts with block 1, etc. if ( blk < my_gpu_id ) { return; } // 32x8 thread block const int tx2 = td % half_NB_X; const int ty2 = td / half_NB_X; // If this blk has fewer than NB_X rows, partial is the number of valid rows, // so tx = 0, ..., partial-1 are valid rows, and tx >= partial are invalid. // Else, partial == 0. const int partial = (blk == gridDim.x - 1 ? ((n + block_offset) % NB_X) : 0); float psum, psum_t; float total = MAGMA_S_ZERO; // sA is used as a 32x32 block, sA32(i,j), // and as a 16x64 block, sA16(i,j), in different parts of the code. // sA must be at least half_NB_X*bank_shift = 32x33 = 1056; // quarter_NB_X*(NB_X + 2) = 16*(64 + 2) = 1056 __shared__ float sA [quarter_NB_X][NB_X + 2]; // TODO +3 used in ssymv (single GPU); why? __shared__ float sx_blk[NB_X]; // for x[ blk ] __shared__ float sx_jj [NB_X]; // for x[ jj ], which cycles over all blocks left of diag float rA[4]; float psums_t[4]; // -------------------- // load 64x1 block x(blk_ind + 0:63) into sx_blk x += (blk_ind + tx)*incx; // x is x(blk_ind + tx) if ( ty == 0 ) { // GPUs are renumbered so that GPU 0 has block 0, which is partial of offset. if ( (partial && tx >= partial) || (blk == 0 /*&& my_gpu_id == 0*/ && tx < block_offset) ) { sx_blk[tx] = MAGMA_S_ZERO; } else { sx_blk[tx] = x[0]; } } // -------------------- // move to block row work += blk*lda; // work is work(0, blk) A += blk_ind; // A is A(blk_ind, 0) A += ty2*lda + tx2; // A is A(blk_ind + tx2, ty2) if ( blk % ngpu == my_gpu_id ) { // this GPU owns this diagonal block, so // move to 32x32 diag block A += (blk/ngpu)*NB_X*lda; // A is A(blk_ind + tx2, blk_ind + ty2) // load 32x32 diag block A(blk_ind + 0:31, blk_ind + 0:31) into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 >= partial ) { A = A - tx2 + (partial - 1); // A is A(blk_ind + partial-1, blk_ind + ty2), the bottom-most valid row } #pragma unroll for(int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } } if ( tx2 >= partial ) { A = A + tx2 - (partial - 1); // A is A(blk_ind + tx2, blk_ind + ty2) } } else { #pragma unroll for(int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle, // as four 32x8 sections in parallel: // columns 0,4,8,12,16,20,24,28; then 1,5,...,29; then 2,6,...,30, then 3,7,...,31 #pragma unroll for(int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = ( sA32(tx2, j) ); } } __syncthreads(); // multiply 32x32 diag block * x // each thread does partial row sA(tx2, ty2*4 : ty2*4 + 3) psum = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to next 32x32 diag block, then repeat steps from first diag block A += half_NB_X + half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + NB/2 + ty2) // load 32x32 diag block A[block + 0:31, block + 0:31] into sA if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for(int j=0; j < half_NB_X; j += 8) { if ( ty2+j + half_NB_X < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for(int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle #pragma unroll for(int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = ( sA32(tx2, j) ); } } __syncthreads(); // multiply 32x32 diag block * x psum = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to off-diag 32x32 block A -= half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + ty2) // load 32x32 block of A into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for(int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for(int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // multiply 32x32 block (below diag) psum = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum += sA32(tx2, ty2 + j*8) * sx_blk[j*8 + ty2]; } //__syncthreads(); // no sync needed here // multiply transposed 32x32 block (above diag) psum_t = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum_t += ( sA32(ty2*4 + j, tx2) ) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial sums for non-transposed 32x32 block sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // store partial sums for transposed 32x32 block sA32(ty2, tx2) = psum_t; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to leftmost 64x64 block in block row, and // switch thread offset from (tx2,ty2) 32x8 block to (tx,ty) 64x4 block A -= half_NB_X; // A is A(blk_ind + tx2, blk_ind + ty2) A -= (blk/ngpu)*NB_X*lda; // A is A(blk_ind + tx2, ty2) } // finish switching thread offset A -= ty2*lda + tx2; // A is A(blk_ind, 0) A += 4*ty*lda + tx; // A is A(blk_ind + tx, 4*ty) if ( partial && tx >= partial ) { A = A - tx + (partial - 1); // A is A(blk_ind + partial-1, 4*ty), the bottom-most valid row } x -= blk_ind*incx; // x is x(tx) // 16x16 thread block const int tx4 = td % quarter_NB_X; const int ty4 = td / quarter_NB_X; // cycle over blocks jj left of diagonal, in block row blk for(int jj=my_gpu_id; jj < blk; jj += ngpu) { // load 64x1 block x(jj_ind + 0:63) into sx_jj // since this block is left of diagonal, x must have all NB rows // only the first block column (jj=0, on GPU 0) deals with offset if ( ty == 0 ) { if ( jj == 0 && tx < block_offset ) { sx_jj[tx] = MAGMA_S_ZERO; } else { sx_jj[tx] = x[jj*NB_X*incx]; } } __syncthreads(); for( int k=0; k < 4; k++ ) { // load 64x16 block of A into rA, 4 elements per thread, // as four 64x4 sections in parallel: // columns 0,4,8,12; then 1,5,9,13; then 2,6,10,14; then 3,7,11,15 // since this block is left of diagonal, it has all NB columns, // and block of x must have all NB rows. #pragma unroll for(int j=0; j < 4; j++) { rA[j] = A[j*lda]; } // 1) multiply 64x16 block A_{blk,jj} * x_jj // each thread does partial row rA(tx + 16*k, ty*4 + 16*k : ty*4 + 3 + 16*k) // 2) multiply transposed 16x64 block A_{blk,jj}^H * x_blk, // storing each product Aji*xi to sA(j,i) #pragma unroll for(int j=0; j < 4; j++) { total += rA[j] * sx_jj[quarter_NB_X*k + ty*4 + j]; // y_blk = A_{blk,jj} * x_jj sA16(ty*4 + j, tx) = ( rA[j] ) * sx_blk[tx]; // y_jj = A_{blk,jj}^H * x_blk } __syncthreads(); // do partial row sums for transposed 16x64 result // use 16x16 thread grid (tx4, ty4) instead of 64x4 (tx, ty) // sum sixteen 16x4 sections in parallel: // columns 0,4,8,...,60; then 1,5,...,61; then 2,6,...,62; then 3,7,...,63 psum_t = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum_t += sA16(tx4, ty4*4 + j); } __syncthreads(); // store partial row sums of transposed result, y_jj (locally) psums_t[k] = psum_t; // move right to next 64x16 block A += lda * quarter_NB_X; // A is A(blk_ind + tx#, jj*NB_x + (k+1)*NB_X/4 + 4*ty), # tx or partial } // already at next 64x64 block // A is A(blk_ind + tx#, (jj+1)*NB_x + 4*ty), # tx or partial // store partial row sums of transposed result, y_jj #pragma unroll for(int k=0; k < 4; k++) { sA16(tx4, ty4 + quarter_NB_X*k) = psums_t[k]; } __syncthreads(); // sum up partial row sums of transposed result, y_jj, and store final total to workspace // thread (tx4,ty4) where ty4 < 4 sums row tx4 + ty4*16 // since this is the transposed block above the diagonal, it must have all NB rows if ( ty4 < 4 ) { int ty4_nb4 = ty4*quarter_NB_X; psum_t = sA16(tx4, 0 + ty4_nb4) + sA16(tx4, 1 + ty4_nb4) + sA16(tx4, 2 + ty4_nb4) + sA16(tx4, 3 + ty4_nb4) + sA16(tx4, 4 + ty4_nb4) + sA16(tx4, 5 + ty4_nb4) + sA16(tx4, 6 + ty4_nb4) + sA16(tx4, 7 + ty4_nb4) + sA16(tx4, 8 + ty4_nb4) + sA16(tx4, 9 + ty4_nb4) + sA16(tx4, 10 + ty4_nb4) + sA16(tx4, 11 + ty4_nb4) + sA16(tx4, 12 + ty4_nb4) + sA16(tx4, 13 + ty4_nb4) + sA16(tx4, 14 + ty4_nb4) + sA16(tx4, 15 + ty4_nb4); work[jj*NB_X + tx4 + ty4_nb4] = psum_t; // store at work( jj*NB_X + tx4 + ty4*16, blk ) } __syncthreads(); } // store row sums sA16(ty, tx) = total; __syncthreads(); // sum up final total, y_blk, for row tx if ( ty == 0 && (partial == 0 || tx < partial) ) { total = sA16(0, tx) + sA16(1, tx) + sA16(2, tx) + sA16(3, tx); work[blk*NB_X + tx] = total; // store at work( blk*NB_X + tx, blk ) } #endif /* (__CUDA_ARCH__ >= 200) */ } // end ssymv_kernel_L_mgpu /************************************************************** Lower case, sum up partial results per GPU. Each block sums one block row; each thread sums one row. On input (for 3 blocks): [ (A11*x1) (A21^H*x2) (A31^H*x3) ] work = [ --- (A21*x1 + A22*x2) (A32^H*x3) ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] On output: [ (A11*x1) + (A21^H*x2) + (A31^H*x3) ] y = alpha*[ (A21*x1 + A22*x2) + (A32^H*x3) ] [ (A21*x1 + A22*x2 + A33*x3) ] Note beta*y is not included here; see magmablas_ssymv_mgpu_sync. The above workspace is distributed over multiple GPUs as diagrammed for 5 blocks: [ * x x x x ] blk=0 * data for non-transposed row w_blk = A_{blk,1:blk} * x_{1:blk} work[gpu=0] = [ * ] blk=1 x data for transposed block w_jj = A_{blk,jj}^H * x_{blk} [ * x x ] blk=2 blanks are not set [ * ] blk=3 [ * ] blk=4 [ ] blk=0 (blank) work[gpu=1] = [ * x x x ] blk=1 [ * ] blk=2 [ * x ] blk=3 [ * ] blk=4 On output, rows across are summed up. Entries left of the diagonal blocks are not accessed. Blank rows, where a GPU has no data to contribute, are explicitly set to zero in y. [ * + x + x + x ] y[gpu=0] = [ * ] [ * + x ] [ * ] [ 0 ] (explicitly set to 0) y[gpu=1] = [ * + x + x ] [ * ] [ * ] ********************************************************************/ __global__ void ssymv_kernel_L_mgpu_sum( int n, float alpha, int lda, float * __restrict__ y, int incy, float const * __restrict__ work, int my_gpu_id, int ngpu, int block_offset) { int tx = threadIdx.x; int blk = blockIdx.x; int blk_ind = blk * NB_X; int ind = blk_ind + tx; int blocks = gridDim.x; // Don't write outside [block_offset, ..., n+block_offset) if ( ind >= block_offset && ind < n+block_offset ) { float Ax = MAGMA_S_ZERO; // GPUs are renumbered so that GPU 0 starts with block 0, // GPU 1 starts with block 1, etc., // therefore only blk >= my_gpu_id have non-zero data. if ( blk >= my_gpu_id ) { work += ind; // if this GPU owns block-column blk, all blocks j=[blk, ..., blocks) contain data; // else only block j=blk contains data. int last = blocks-1; if ( blk % ngpu != my_gpu_id ) { last = blk; } for(int j = blk; j <= last; ++j) { Ax += work[j*lda]; } } y[ind * incy] = alpha*Ax; // see magmablas_ssymv_sync for beta*y } } // end ssymv_kernel_L_mgpu_sum /** Purpose ------- magmablas_ssymv_mgpu performs the matrix-vector operation: y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n symmetric matrix. Arguments ---------- @param[in] uplo magma_uplo_t. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: - = MagmaUpper: Only the upper triangular part of A is to be referenced. **Not currently supported.** - = MagmaLower: Only the lower triangular part of A is to be referenced. @param[in] n INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. @param[in] alpha REAL. On entry, ALPHA specifies the scalar alpha. @param[in] d_lA Array of pointers, dimension (ngpu), to block-column distributed matrix A, with block size nb. d_lA[dev] is a REAL array on GPU dev, of dimension (LDDA, nlocal), where \n { floor(n/nb/ngpu)*nb + nb if dev < floor(n/nb) % ngpu, nlocal = { floor(n/nb/ngpu)*nb + n%nb if dev == floor(n/nb) % ngpu, { floor(n/nb/ngpu)*nb otherwise. \n Before entry with UPLO = MagmaUpper, the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = MagmaLower, the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. @param[in] ldda INTEGER. On entry, LDDA specifies the first dimension of A as declared in the calling (sub) program. LDDA must be at least max( 1, n ). It is recommended that ldda is multiple of 16. Otherwise performance would be deteriorated as the memory accesses would not be fully coalescent. @param[in] x REAL array **on the CPU** (not the GPU), of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. @param[in] incx INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. @param[in] beta REAL. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. @param[in,out] y REAL array **on the CPU** (not the GPU), of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. @param[in] incy INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. @param hwork (workspace) REAL array on the CPU, of dimension (lhwork). @param[in] lhwork INTEGER. The dimension of the array hwork. lhwork >= ngpu*nb. @param dwork (workspaces) Array of pointers, dimension (ngpu), to workspace on each GPU. dwork[dev] is a REAL array on GPU dev, of dimension (ldwork). @param[in] ldwork INTEGER. The dimension of each array dwork[dev]. ldwork >= ldda*( ceil((n + offset % nb) / nb) + 1 ). @param[in] ngpu INTEGER. The number of GPUs to use. @param[in] nb INTEGER. The block size used for distributing d_lA. Must be 64. @param[in] queues magma_queue_t array of dimension (ngpu). queues[dev] is an execution queue on GPU dev. @ingroup magma_sblas2 ********************************************************************/ extern "C" magma_int_t magmablas_ssymv_mgpu( magma_uplo_t uplo, magma_int_t n, float alpha, magmaFloat_const_ptr const d_lA[], magma_int_t ldda, magma_int_t offset, float const *x, magma_int_t incx, float beta, // unused, see magmablas_ssymv_mgpu_sync float *y, magma_int_t incy, // unused float *hwork, magma_int_t lhwork, magmaFloat_ptr dwork[], magma_int_t ldwork, magma_int_t ngpu, magma_int_t nb, magma_queue_t queues[] ) { magma_int_t arch = magma_getdevice_arch(); if ( arch < 200 ) { // -------------------- // no CUDA ARCH 1.x version fprintf( stderr, "%s not supported on CUDA arch 1.x\n", __func__ ); return MAGMA_ERR_NOT_SUPPORTED; } // -------------------- // CUDA ARCH 2.x (Fermi) version int upper = (uplo == MagmaUpper); magma_int_t offset_block_id = offset / NB_X; magma_int_t offset_gpu_id = offset_block_id % ngpu; magma_int_t block_offset = offset % NB_X; magma_int_t blocks = ceildiv( n + block_offset, NB_X ); magma_int_t ldwmin = ldda*(blocks + 1); magma_int_t lhwmin = n*ngpu; /* * Test the input parameters. */ magma_int_t info = 0; if ( (! upper) && (uplo != MagmaLower) ) { info = -1; } else if ( n < 0 ) { info = -2; } else if ( ldda < max(1,n+offset) ) { info = -5; } else if ( offset < 0 ) { info = -6; } else if ( incx == 0 ) { info = -8; } else if ( incy == 0 ) { info = -11; } else if ( lhwork < lhwmin ) { info = -13; } else if ( ldwork < ldwmin ) { info = -15; } else if ( ngpu < 1 ) { info = -16; } else if ( nb != NB_X ) { info = -17; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( n == 0 ) return info; magma_device_t orig_dev; magma_getdevice( &orig_dev ); magma_int_t dev; for(dev=0; dev < ngpu; dev++) { magma_setdevice( dev ); // blocks before the offset block magma_int_t num_blocks_skipped = offset_block_id / ngpu; if ( dev < offset_gpu_id ) { num_blocks_skipped += 1; } // shift dA to first block >= offset block that is owned by this GPU float const *dA_dev = d_lA[dev] + offset_block_id*NB_X + num_blocks_skipped*NB_X*ldda; // first column of dwork is to broadcast x to all GPUs. // remaining blocks number of columns is for partial sums from // each block, as in single GPU version. float *dx_dev = dwork[dev]; float *dwork_dev = dwork[dev] + ldda; // renumber GPUs starting from the offset block magma_int_t new_gpu_id = (dev + ngpu - offset_gpu_id) % ngpu; dim3 grid( blocks, 1 ); // copy x to each GPU magma_ssetvector_async( n, x, incx, dx_dev + block_offset, 1, queues[dev] ); // perform work = A*x, partial row sums dim3 threads( NB_X, NB_Y ); // perform w = sum( work ), larger partial row sums dim3 threads_sum( NB_X, 1 ); if ( upper ) { hipLaunchKernelGGL(( ssymv_kernel_U_mgpu), dim3(grid), dim3(threads), 0, queues[dev] , n, dA_dev, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); hipLaunchKernelGGL(( ssymv_kernel_U_mgpu_sum), dim3(grid), dim3(threads_sum), 0, queues[dev] , n, alpha, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); } else { hipLaunchKernelGGL(( ssymv_kernel_L_mgpu), dim3(grid), dim3(threads), 0, queues[dev] , n, dA_dev, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); hipLaunchKernelGGL(( ssymv_kernel_L_mgpu_sum), dim3(grid), dim3(threads_sum), 0, queues[dev] , n, alpha, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); } } // 2nd loop in case hwork is not pinned, causing this to be sync instead of async. for(dev=0; dev < ngpu; dev++) { // copy w to CPU magma_setdevice( dev ); float *dx_dev = dwork[dev]; magma_sgetvector_async( n, dx_dev + block_offset, 1, &hwork[dev*n], 1, queues[dev] ); } // see magmablas_ssymv_mgpu_sync for final row sums magma_setdevice( orig_dev ); return info; } /** Synchronizes and acculumates final ssymv result. For convenience, the parameters are identical to magmablas_ssymv_mgpu (though some are unused here). @see magmablas_ssymv_mgpu @ingroup magma_sblas2 ********************************************************************/ extern "C" magma_int_t magmablas_ssymv_mgpu_sync( magma_uplo_t uplo, // unused, see magmablas_ssymv_mgpu magma_int_t n, float alpha, // unused magmaFloat_const_ptr const d_lA[], magma_int_t ldda, magma_int_t offset, // unused float const *x, magma_int_t incx, // unused float beta, float *y, magma_int_t incy, // unused float *hwork, magma_int_t lhwork, magmaFloat_ptr dwork[], magma_int_t ldwork, // unused magma_int_t ngpu, magma_int_t nb, // unused magma_queue_t queues[] ) { const float c_one = MAGMA_S_ONE; const magma_int_t ione = 1; magma_device_t dev; magma_int_t lhwmin = n*ngpu; /* * Test the input parameters. */ magma_int_t info = 0; //if ( (! upper) && (uplo != MagmaLower) ) { // unused // info = -1; //} else if ( n < 0 ) { info = -2; } else if ( ldda < max(1,n+offset) ) { info = -5; } else if ( offset < 0 ) { info = -6; } else if ( incx == 0 ) { info = -8; } else if ( incy == 0 ) { info = -11; } else if ( lhwork < lhwmin ) { info = -13; //} else if ( ldwork < ldwmin ) { // unused // info = -15; } else if ( ngpu < 1 ) { info = -16; } else if ( nb != NB_X ) { info = -17; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( n == 0 ) return info; magma_device_t orig_dev; magma_getdevice( &orig_dev ); // scale y = beta*y blasf77_sscal( &n, &beta, y, &incy ); // sum reduce, y += sum( hwork ) for( dev=0; dev < ngpu; ++dev ) { magma_setdevice( dev ); magma_queue_sync( queues[dev] ); blasf77_saxpy( &n, &c_one, &hwork[dev*n], &ione, y, &ione ); } magma_setdevice( orig_dev ); return info; }
8602ab93921750e2a467c69971014515144ac884.cu
/* -- MAGMA (version 1.6.1) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date January 2015 @generated from zhemv_mgpu.cu normal z -> s, Fri Jan 30 19:00:10 2015 @author Mark Gates */ #include "common_magma.h" #include "commonblas_s.h" #define PRECISION_s #define NB_X 64 #define NB_Y 4 #define bank_shift 33 #define quarter_NB_X 16 #define half_NB_X 32 /******************************************************************************* Lower case, compute block multiply, work = A*x, for any size n: [ (A11*x1) (A21^H*x2) (A31^H*x3) ] [ A11 A21^H A31^H ] [ x1 ] work = [ --- (A21*x1 + A22*x2) (A32^H*x3) ] = [ A21 A22 A32^H ] * [ x2 ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] [ A31 A32 A33 ] [ x3 ] Uses a 64x4 thread block. For diagonal tiles, covers a 64x64 tile using three 32x32 tiles (plus one gets transposed). For off-diagonal tiles, covers a 64x64 tile using four 64x16 tiles. In both cases, each thread multiplies 4 elements. For rows past the bottom of the matrix, the A pointer is adjusted to be the last valid row of A, which multiple threads will read. Extra rows are ignored when saving results to work. Columns past the right edge are explicitly ignored when loading. x values past the bottom are set to zero, thus, extra columns are zeroed when multiplying. Previously: [ (A11*x1) --- ] work = [ (A21^H*x2) (A21*x1 + A22*x2) --- ] [ (A31^H*x3) (A32^H*x3) (A31*x1 + A32*x2 + A33*x3) ] which doesn't work as well because that has dimension blocks*NB by blocks, where blocks*NB >= n, and it can be that blocks*NB > lda, so it won't fit in lda*blocks space. This is why it used to need lwork = lda*(blocks + 1). ********************************************************************/ __global__ void ssymv_kernel_L_mgpu( int n, float const * __restrict__ A, int lda, float const * __restrict__ x, int incx, float * __restrict__ work, int my_gpu_id, int ngpu, int block_offset ) { #if (__CUDA_ARCH__ >= 200) // treats sA as 16x64 block #define sA16(i_, j_) (sA[(i_)][(j_)]) // i.e., sA[ (i_)*(NB_X+3) + (j_) ] // treats sA as 32x32 block #define sA32(i_, j_) (sA[0][(i_) + bank_shift*(j_)]) // 64x4 thread block const int tx = threadIdx.x; const int ty = threadIdx.y; const int blk = blockIdx.x; const int blk_ind = NB_X * blk; const int td = NB_X * ty + tx; // GPUs are renumbered so that GPU 0 starts with block 0, GPU 1 starts with block 1, etc. if ( blk < my_gpu_id ) { return; } // 32x8 thread block const int tx2 = td % half_NB_X; const int ty2 = td / half_NB_X; // If this blk has fewer than NB_X rows, partial is the number of valid rows, // so tx = 0, ..., partial-1 are valid rows, and tx >= partial are invalid. // Else, partial == 0. const int partial = (blk == gridDim.x - 1 ? ((n + block_offset) % NB_X) : 0); float psum, psum_t; float total = MAGMA_S_ZERO; // sA is used as a 32x32 block, sA32(i,j), // and as a 16x64 block, sA16(i,j), in different parts of the code. // sA must be at least half_NB_X*bank_shift = 32x33 = 1056; // quarter_NB_X*(NB_X + 2) = 16*(64 + 2) = 1056 __shared__ float sA [quarter_NB_X][NB_X + 2]; // TODO +3 used in ssymv (single GPU); why? __shared__ float sx_blk[NB_X]; // for x[ blk ] __shared__ float sx_jj [NB_X]; // for x[ jj ], which cycles over all blocks left of diag float rA[4]; float psums_t[4]; // -------------------- // load 64x1 block x(blk_ind + 0:63) into sx_blk x += (blk_ind + tx)*incx; // x is x(blk_ind + tx) if ( ty == 0 ) { // GPUs are renumbered so that GPU 0 has block 0, which is partial of offset. if ( (partial && tx >= partial) || (blk == 0 /*&& my_gpu_id == 0*/ && tx < block_offset) ) { sx_blk[tx] = MAGMA_S_ZERO; } else { sx_blk[tx] = x[0]; } } // -------------------- // move to block row work += blk*lda; // work is work(0, blk) A += blk_ind; // A is A(blk_ind, 0) A += ty2*lda + tx2; // A is A(blk_ind + tx2, ty2) if ( blk % ngpu == my_gpu_id ) { // this GPU owns this diagonal block, so // move to 32x32 diag block A += (blk/ngpu)*NB_X*lda; // A is A(blk_ind + tx2, blk_ind + ty2) // load 32x32 diag block A(blk_ind + 0:31, blk_ind + 0:31) into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 >= partial ) { A = A - tx2 + (partial - 1); // A is A(blk_ind + partial-1, blk_ind + ty2), the bottom-most valid row } #pragma unroll for(int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } } if ( tx2 >= partial ) { A = A + tx2 - (partial - 1); // A is A(blk_ind + tx2, blk_ind + ty2) } } else { #pragma unroll for(int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle, // as four 32x8 sections in parallel: // columns 0,4,8,12,16,20,24,28; then 1,5,...,29; then 2,6,...,30, then 3,7,...,31 #pragma unroll for(int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = ( sA32(tx2, j) ); } } __syncthreads(); // multiply 32x32 diag block * x // each thread does partial row sA(tx2, ty2*4 : ty2*4 + 3) psum = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to next 32x32 diag block, then repeat steps from first diag block A += half_NB_X + half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + NB/2 + ty2) // load 32x32 diag block A[block + 0:31, block + 0:31] into sA if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for(int j=0; j < half_NB_X; j += 8) { if ( ty2+j + half_NB_X < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for(int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle #pragma unroll for(int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = ( sA32(tx2, j) ); } } __syncthreads(); // multiply 32x32 diag block * x psum = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to off-diag 32x32 block A -= half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + ty2) // load 32x32 block of A into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for(int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for(int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // multiply 32x32 block (below diag) psum = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum += sA32(tx2, ty2 + j*8) * sx_blk[j*8 + ty2]; } //__syncthreads(); // no sync needed here // multiply transposed 32x32 block (above diag) psum_t = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum_t += ( sA32(ty2*4 + j, tx2) ) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial sums for non-transposed 32x32 block sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // store partial sums for transposed 32x32 block sA32(ty2, tx2) = psum_t; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to leftmost 64x64 block in block row, and // switch thread offset from (tx2,ty2) 32x8 block to (tx,ty) 64x4 block A -= half_NB_X; // A is A(blk_ind + tx2, blk_ind + ty2) A -= (blk/ngpu)*NB_X*lda; // A is A(blk_ind + tx2, ty2) } // finish switching thread offset A -= ty2*lda + tx2; // A is A(blk_ind, 0) A += 4*ty*lda + tx; // A is A(blk_ind + tx, 4*ty) if ( partial && tx >= partial ) { A = A - tx + (partial - 1); // A is A(blk_ind + partial-1, 4*ty), the bottom-most valid row } x -= blk_ind*incx; // x is x(tx) // 16x16 thread block const int tx4 = td % quarter_NB_X; const int ty4 = td / quarter_NB_X; // cycle over blocks jj left of diagonal, in block row blk for(int jj=my_gpu_id; jj < blk; jj += ngpu) { // load 64x1 block x(jj_ind + 0:63) into sx_jj // since this block is left of diagonal, x must have all NB rows // only the first block column (jj=0, on GPU 0) deals with offset if ( ty == 0 ) { if ( jj == 0 && tx < block_offset ) { sx_jj[tx] = MAGMA_S_ZERO; } else { sx_jj[tx] = x[jj*NB_X*incx]; } } __syncthreads(); for( int k=0; k < 4; k++ ) { // load 64x16 block of A into rA, 4 elements per thread, // as four 64x4 sections in parallel: // columns 0,4,8,12; then 1,5,9,13; then 2,6,10,14; then 3,7,11,15 // since this block is left of diagonal, it has all NB columns, // and block of x must have all NB rows. #pragma unroll for(int j=0; j < 4; j++) { rA[j] = A[j*lda]; } // 1) multiply 64x16 block A_{blk,jj} * x_jj // each thread does partial row rA(tx + 16*k, ty*4 + 16*k : ty*4 + 3 + 16*k) // 2) multiply transposed 16x64 block A_{blk,jj}^H * x_blk, // storing each product Aji*xi to sA(j,i) #pragma unroll for(int j=0; j < 4; j++) { total += rA[j] * sx_jj[quarter_NB_X*k + ty*4 + j]; // y_blk = A_{blk,jj} * x_jj sA16(ty*4 + j, tx) = ( rA[j] ) * sx_blk[tx]; // y_jj = A_{blk,jj}^H * x_blk } __syncthreads(); // do partial row sums for transposed 16x64 result // use 16x16 thread grid (tx4, ty4) instead of 64x4 (tx, ty) // sum sixteen 16x4 sections in parallel: // columns 0,4,8,...,60; then 1,5,...,61; then 2,6,...,62; then 3,7,...,63 psum_t = MAGMA_S_ZERO; #pragma unroll for(int j=0; j < 4; j++) { psum_t += sA16(tx4, ty4*4 + j); } __syncthreads(); // store partial row sums of transposed result, y_jj (locally) psums_t[k] = psum_t; // move right to next 64x16 block A += lda * quarter_NB_X; // A is A(blk_ind + tx#, jj*NB_x + (k+1)*NB_X/4 + 4*ty), # tx or partial } // already at next 64x64 block // A is A(blk_ind + tx#, (jj+1)*NB_x + 4*ty), # tx or partial // store partial row sums of transposed result, y_jj #pragma unroll for(int k=0; k < 4; k++) { sA16(tx4, ty4 + quarter_NB_X*k) = psums_t[k]; } __syncthreads(); // sum up partial row sums of transposed result, y_jj, and store final total to workspace // thread (tx4,ty4) where ty4 < 4 sums row tx4 + ty4*16 // since this is the transposed block above the diagonal, it must have all NB rows if ( ty4 < 4 ) { int ty4_nb4 = ty4*quarter_NB_X; psum_t = sA16(tx4, 0 + ty4_nb4) + sA16(tx4, 1 + ty4_nb4) + sA16(tx4, 2 + ty4_nb4) + sA16(tx4, 3 + ty4_nb4) + sA16(tx4, 4 + ty4_nb4) + sA16(tx4, 5 + ty4_nb4) + sA16(tx4, 6 + ty4_nb4) + sA16(tx4, 7 + ty4_nb4) + sA16(tx4, 8 + ty4_nb4) + sA16(tx4, 9 + ty4_nb4) + sA16(tx4, 10 + ty4_nb4) + sA16(tx4, 11 + ty4_nb4) + sA16(tx4, 12 + ty4_nb4) + sA16(tx4, 13 + ty4_nb4) + sA16(tx4, 14 + ty4_nb4) + sA16(tx4, 15 + ty4_nb4); work[jj*NB_X + tx4 + ty4_nb4] = psum_t; // store at work( jj*NB_X + tx4 + ty4*16, blk ) } __syncthreads(); } // store row sums sA16(ty, tx) = total; __syncthreads(); // sum up final total, y_blk, for row tx if ( ty == 0 && (partial == 0 || tx < partial) ) { total = sA16(0, tx) + sA16(1, tx) + sA16(2, tx) + sA16(3, tx); work[blk*NB_X + tx] = total; // store at work( blk*NB_X + tx, blk ) } #endif /* (__CUDA_ARCH__ >= 200) */ } // end ssymv_kernel_L_mgpu /************************************************************** Lower case, sum up partial results per GPU. Each block sums one block row; each thread sums one row. On input (for 3 blocks): [ (A11*x1) (A21^H*x2) (A31^H*x3) ] work = [ --- (A21*x1 + A22*x2) (A32^H*x3) ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] On output: [ (A11*x1) + (A21^H*x2) + (A31^H*x3) ] y = alpha*[ (A21*x1 + A22*x2) + (A32^H*x3) ] [ (A21*x1 + A22*x2 + A33*x3) ] Note beta*y is not included here; see magmablas_ssymv_mgpu_sync. The above workspace is distributed over multiple GPUs as diagrammed for 5 blocks: [ * x x x x ] blk=0 * data for non-transposed row w_blk = A_{blk,1:blk} * x_{1:blk} work[gpu=0] = [ * ] blk=1 x data for transposed block w_jj = A_{blk,jj}^H * x_{blk} [ * x x ] blk=2 blanks are not set [ * ] blk=3 [ * ] blk=4 [ ] blk=0 (blank) work[gpu=1] = [ * x x x ] blk=1 [ * ] blk=2 [ * x ] blk=3 [ * ] blk=4 On output, rows across are summed up. Entries left of the diagonal blocks are not accessed. Blank rows, where a GPU has no data to contribute, are explicitly set to zero in y. [ * + x + x + x ] y[gpu=0] = [ * ] [ * + x ] [ * ] [ 0 ] (explicitly set to 0) y[gpu=1] = [ * + x + x ] [ * ] [ * ] ********************************************************************/ __global__ void ssymv_kernel_L_mgpu_sum( int n, float alpha, int lda, float * __restrict__ y, int incy, float const * __restrict__ work, int my_gpu_id, int ngpu, int block_offset) { int tx = threadIdx.x; int blk = blockIdx.x; int blk_ind = blk * NB_X; int ind = blk_ind + tx; int blocks = gridDim.x; // Don't write outside [block_offset, ..., n+block_offset) if ( ind >= block_offset && ind < n+block_offset ) { float Ax = MAGMA_S_ZERO; // GPUs are renumbered so that GPU 0 starts with block 0, // GPU 1 starts with block 1, etc., // therefore only blk >= my_gpu_id have non-zero data. if ( blk >= my_gpu_id ) { work += ind; // if this GPU owns block-column blk, all blocks j=[blk, ..., blocks) contain data; // else only block j=blk contains data. int last = blocks-1; if ( blk % ngpu != my_gpu_id ) { last = blk; } for(int j = blk; j <= last; ++j) { Ax += work[j*lda]; } } y[ind * incy] = alpha*Ax; // see magmablas_ssymv_sync for beta*y } } // end ssymv_kernel_L_mgpu_sum /** Purpose ------- magmablas_ssymv_mgpu performs the matrix-vector operation: y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n symmetric matrix. Arguments ---------- @param[in] uplo magma_uplo_t. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: - = MagmaUpper: Only the upper triangular part of A is to be referenced. **Not currently supported.** - = MagmaLower: Only the lower triangular part of A is to be referenced. @param[in] n INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. @param[in] alpha REAL. On entry, ALPHA specifies the scalar alpha. @param[in] d_lA Array of pointers, dimension (ngpu), to block-column distributed matrix A, with block size nb. d_lA[dev] is a REAL array on GPU dev, of dimension (LDDA, nlocal), where \n { floor(n/nb/ngpu)*nb + nb if dev < floor(n/nb) % ngpu, nlocal = { floor(n/nb/ngpu)*nb + n%nb if dev == floor(n/nb) % ngpu, { floor(n/nb/ngpu)*nb otherwise. \n Before entry with UPLO = MagmaUpper, the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = MagmaLower, the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. @param[in] ldda INTEGER. On entry, LDDA specifies the first dimension of A as declared in the calling (sub) program. LDDA must be at least max( 1, n ). It is recommended that ldda is multiple of 16. Otherwise performance would be deteriorated as the memory accesses would not be fully coalescent. @param[in] x REAL array **on the CPU** (not the GPU), of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. @param[in] incx INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. @param[in] beta REAL. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. @param[in,out] y REAL array **on the CPU** (not the GPU), of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. @param[in] incy INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. @param hwork (workspace) REAL array on the CPU, of dimension (lhwork). @param[in] lhwork INTEGER. The dimension of the array hwork. lhwork >= ngpu*nb. @param dwork (workspaces) Array of pointers, dimension (ngpu), to workspace on each GPU. dwork[dev] is a REAL array on GPU dev, of dimension (ldwork). @param[in] ldwork INTEGER. The dimension of each array dwork[dev]. ldwork >= ldda*( ceil((n + offset % nb) / nb) + 1 ). @param[in] ngpu INTEGER. The number of GPUs to use. @param[in] nb INTEGER. The block size used for distributing d_lA. Must be 64. @param[in] queues magma_queue_t array of dimension (ngpu). queues[dev] is an execution queue on GPU dev. @ingroup magma_sblas2 ********************************************************************/ extern "C" magma_int_t magmablas_ssymv_mgpu( magma_uplo_t uplo, magma_int_t n, float alpha, magmaFloat_const_ptr const d_lA[], magma_int_t ldda, magma_int_t offset, float const *x, magma_int_t incx, float beta, // unused, see magmablas_ssymv_mgpu_sync float *y, magma_int_t incy, // unused float *hwork, magma_int_t lhwork, magmaFloat_ptr dwork[], magma_int_t ldwork, magma_int_t ngpu, magma_int_t nb, magma_queue_t queues[] ) { magma_int_t arch = magma_getdevice_arch(); if ( arch < 200 ) { // -------------------- // no CUDA ARCH 1.x version fprintf( stderr, "%s not supported on CUDA arch 1.x\n", __func__ ); return MAGMA_ERR_NOT_SUPPORTED; } // -------------------- // CUDA ARCH 2.x (Fermi) version int upper = (uplo == MagmaUpper); magma_int_t offset_block_id = offset / NB_X; magma_int_t offset_gpu_id = offset_block_id % ngpu; magma_int_t block_offset = offset % NB_X; magma_int_t blocks = ceildiv( n + block_offset, NB_X ); magma_int_t ldwmin = ldda*(blocks + 1); magma_int_t lhwmin = n*ngpu; /* * Test the input parameters. */ magma_int_t info = 0; if ( (! upper) && (uplo != MagmaLower) ) { info = -1; } else if ( n < 0 ) { info = -2; } else if ( ldda < max(1,n+offset) ) { info = -5; } else if ( offset < 0 ) { info = -6; } else if ( incx == 0 ) { info = -8; } else if ( incy == 0 ) { info = -11; } else if ( lhwork < lhwmin ) { info = -13; } else if ( ldwork < ldwmin ) { info = -15; } else if ( ngpu < 1 ) { info = -16; } else if ( nb != NB_X ) { info = -17; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( n == 0 ) return info; magma_device_t orig_dev; magma_getdevice( &orig_dev ); magma_int_t dev; for(dev=0; dev < ngpu; dev++) { magma_setdevice( dev ); // blocks before the offset block magma_int_t num_blocks_skipped = offset_block_id / ngpu; if ( dev < offset_gpu_id ) { num_blocks_skipped += 1; } // shift dA to first block >= offset block that is owned by this GPU float const *dA_dev = d_lA[dev] + offset_block_id*NB_X + num_blocks_skipped*NB_X*ldda; // first column of dwork is to broadcast x to all GPUs. // remaining blocks number of columns is for partial sums from // each block, as in single GPU version. float *dx_dev = dwork[dev]; float *dwork_dev = dwork[dev] + ldda; // renumber GPUs starting from the offset block magma_int_t new_gpu_id = (dev + ngpu - offset_gpu_id) % ngpu; dim3 grid( blocks, 1 ); // copy x to each GPU magma_ssetvector_async( n, x, incx, dx_dev + block_offset, 1, queues[dev] ); // perform work = A*x, partial row sums dim3 threads( NB_X, NB_Y ); // perform w = sum( work ), larger partial row sums dim3 threads_sum( NB_X, 1 ); if ( upper ) { ssymv_kernel_U_mgpu<<< grid, threads, 0, queues[dev] >>>( n, dA_dev, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); ssymv_kernel_U_mgpu_sum<<< grid, threads_sum, 0, queues[dev] >>>( n, alpha, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); } else { ssymv_kernel_L_mgpu<<< grid, threads, 0, queues[dev] >>>( n, dA_dev, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); ssymv_kernel_L_mgpu_sum<<< grid, threads_sum, 0, queues[dev] >>>( n, alpha, ldda, dx_dev, 1, dwork_dev, new_gpu_id, ngpu, block_offset ); } } // 2nd loop in case hwork is not pinned, causing this to be sync instead of async. for(dev=0; dev < ngpu; dev++) { // copy w to CPU magma_setdevice( dev ); float *dx_dev = dwork[dev]; magma_sgetvector_async( n, dx_dev + block_offset, 1, &hwork[dev*n], 1, queues[dev] ); } // see magmablas_ssymv_mgpu_sync for final row sums magma_setdevice( orig_dev ); return info; } /** Synchronizes and acculumates final ssymv result. For convenience, the parameters are identical to magmablas_ssymv_mgpu (though some are unused here). @see magmablas_ssymv_mgpu @ingroup magma_sblas2 ********************************************************************/ extern "C" magma_int_t magmablas_ssymv_mgpu_sync( magma_uplo_t uplo, // unused, see magmablas_ssymv_mgpu magma_int_t n, float alpha, // unused magmaFloat_const_ptr const d_lA[], magma_int_t ldda, magma_int_t offset, // unused float const *x, magma_int_t incx, // unused float beta, float *y, magma_int_t incy, // unused float *hwork, magma_int_t lhwork, magmaFloat_ptr dwork[], magma_int_t ldwork, // unused magma_int_t ngpu, magma_int_t nb, // unused magma_queue_t queues[] ) { const float c_one = MAGMA_S_ONE; const magma_int_t ione = 1; magma_device_t dev; magma_int_t lhwmin = n*ngpu; /* * Test the input parameters. */ magma_int_t info = 0; //if ( (! upper) && (uplo != MagmaLower) ) { // unused // info = -1; //} else if ( n < 0 ) { info = -2; } else if ( ldda < max(1,n+offset) ) { info = -5; } else if ( offset < 0 ) { info = -6; } else if ( incx == 0 ) { info = -8; } else if ( incy == 0 ) { info = -11; } else if ( lhwork < lhwmin ) { info = -13; //} else if ( ldwork < ldwmin ) { // unused // info = -15; } else if ( ngpu < 1 ) { info = -16; } else if ( nb != NB_X ) { info = -17; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( n == 0 ) return info; magma_device_t orig_dev; magma_getdevice( &orig_dev ); // scale y = beta*y blasf77_sscal( &n, &beta, y, &incy ); // sum reduce, y += sum( hwork ) for( dev=0; dev < ngpu; ++dev ) { magma_setdevice( dev ); magma_queue_sync( queues[dev] ); blasf77_saxpy( &n, &c_one, &hwork[dev*n], &ione, y, &ione ); } magma_setdevice( orig_dev ); return info; }
LegacyThrustHelpers.hip
// !!! This is a file automatically generated by hipify!!! #include <ATen/ATen.h> #include <THH/THHTensorSort.cuh> #include <THH/THHThrustAllocator.cuh> #include <thrust/execution_policy.h> #include <thrust/sort.h> namespace at { namespace native { void index_put_accum_kernel_thrust_helper(Tensor &linearIndex, Tensor &orig_indices, Tensor &sorted_indices, int64_t num_indices) { sorted_indices.copy_(linearIndex); const hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA(); auto allocator = THCThrustAllocator(globalContext().lazyInitCUDA()); auto policy = thrust::hip::par(allocator).on(stream); using device_ptr = thrust::device_ptr<int64_t>; // Fill sortedOrigIndices with sequential indices const auto count_iter = thrust::counting_iterator<int64_t>(0); auto orig_data = device_ptr(orig_indices.data_ptr<int64_t>()); thrust::copy(policy, count_iter, count_iter + num_indices, orig_data); // Sort the inputs into sorted with the corresponding indices; we // don't need a stable or multidimensional sort, so just use Thrust // directly // Sort; a stable sort is not required // NB - not passing comparator causes thrust to use radix sort, and it hurts perf A LOT, at least for medium (few K) sized indices auto sorted_data = device_ptr(sorted_indices.data_ptr<int64_t>()); thrust::sort_by_key(policy, sorted_data, sorted_data + num_indices, orig_data, ThrustLTOp<int64_t>()); } }}
LegacyThrustHelpers.cu
#include <ATen/ATen.h> #include <THC/THCTensorSort.cuh> #include <THC/THCThrustAllocator.cuh> #include <thrust/execution_policy.h> #include <thrust/sort.h> namespace at { namespace native { void index_put_accum_kernel_thrust_helper(Tensor &linearIndex, Tensor &orig_indices, Tensor &sorted_indices, int64_t num_indices) { sorted_indices.copy_(linearIndex); const cudaStream_t stream = at::cuda::getCurrentCUDAStream(); auto allocator = THCThrustAllocator(globalContext().lazyInitCUDA()); auto policy = thrust::cuda::par(allocator).on(stream); using device_ptr = thrust::device_ptr<int64_t>; // Fill sortedOrigIndices with sequential indices const auto count_iter = thrust::counting_iterator<int64_t>(0); auto orig_data = device_ptr(orig_indices.data_ptr<int64_t>()); thrust::copy(policy, count_iter, count_iter + num_indices, orig_data); // Sort the inputs into sorted with the corresponding indices; we // don't need a stable or multidimensional sort, so just use Thrust // directly // Sort; a stable sort is not required // NB - not passing comparator causes thrust to use radix sort, and it hurts perf A LOT, at least for medium (few K) sized indices auto sorted_data = device_ptr(sorted_indices.data_ptr<int64_t>()); thrust::sort_by_key(policy, sorted_data, sorted_data + num_indices, orig_data, ThrustLTOp<int64_t>()); } }}
c3008afc9a7e0e332c3399f0603812698aa55a07.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright 2020 Naval Postgraduate School * * 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 <nps_uw_multibeam_sonar/sonar_calculation_cuda.cuh> // #include <math.h> #include <assert.h> // For complex numbers #include <thrust/complex.h> #include <hip/hip_complex.h> // For rand() function #include <unistd.h> #include <hiprand/hiprand.h> #include <hiprand/hiprand_kernel.h> // For FFT #include <hipfft.h> #include <cufftw.h> #include <thrust/device_vector.h> #include <list> #include <chrono> #define BLOCK_SIZE 32 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__) /////////////////////////////////////////////////////////////////////////// // Incident Angle Calculation Function // incidence angle is target's normal angle accounting for the ray's azimuth // and elevation __device__ float compute_incidence(float azimuth, float elevation, float *normal) { // ray normal from camera azimuth and elevation float camera_x = cosf(-azimuth) * cosf(elevation); float camera_y = sinf(-azimuth) * cosf(elevation); float camera_z = sinf(elevation); float ray_normal[3] = {camera_x, camera_y, camera_z}; // target normal with axes compensated to camera axes float target_normal[3] = {normal[2], -normal[0], -normal[1]}; // dot product float dot_product = ray_normal[0] * target_normal[0] + ray_normal[1] * target_normal[1] + ray_normal[2] * target_normal[2]; return M_PI - acosf(dot_product); } /////////////////////////////////////////////////////////////////////////// __device__ __host__ float unnormalized_sinc(float t) { if (abs(t) < 1E-8) return 1.0; else return sin(t) / t; } /////////////////////////////////////////////////////////////////////////// template <typename T> __global__ void column_sums_reduce(const T *__restrict__ in, T *__restrict__ out, size_t width, size_t height) { __shared__ T sdata[BLOCK_SIZE][BLOCK_SIZE + 1]; size_t idx = threadIdx.x + blockDim.x * blockIdx.x; size_t width_stride = gridDim.x * blockDim.x; size_t full_width = (width & (~((unsigned long long)(BLOCK_SIZE - 1)))) + ((width & (BLOCK_SIZE - 1)) ? BLOCK_SIZE : 0); // round up to next block for (size_t w = idx; w < full_width; w += width_stride) { // grid-stride loop across matrix width sdata[threadIdx.y][threadIdx.x] = 0; size_t in_ptr = w + threadIdx.y * width; for (size_t h = threadIdx.y; h < height; h += BLOCK_SIZE) { // block-stride loop across matrix height sdata[threadIdx.y][threadIdx.x] += (w < width) ? in[in_ptr] : 0; in_ptr += width * BLOCK_SIZE; } __syncthreads(); T my_val = sdata[threadIdx.x][threadIdx.y]; for (int i = warpSize >> 1; i > 0; i >>= 1) // warp-wise parallel sum reduction my_val += __shfl_xor_sync(0xFFFFFFFFU, my_val, i); __syncthreads(); if (threadIdx.x == 0) sdata[0][threadIdx.y] = my_val; __syncthreads(); if ((threadIdx.y == 0) && ((w) < width)) out[w] = sdata[0][threadIdx.x]; } } __global__ void gpu_matrix_mult(float *a, float *b, float *c, int m, int n, int k) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; float sum = 0; if (col < k && row < m) { for (int i = 0; i < n; i++) { sum += a[row * n + i] * b[i * k + col]; } c[row * k + col] = sum; } } __global__ void gpu_diag_matrix_mult(float *Val, int *RowPtr, float *diagVals, int total_rows) { const int row = threadIdx.x + blockIdx.x * blockDim.x; if (row < total_rows) { for (int i = RowPtr[row]; i < RowPtr[row + 1]; i++) { Val[i] = diagVals[row] * Val[i]; } } } /////////////////////////////////////////////////////////////////////////// // Sonar Claculation Function __global__ void sonar_calculation(thrust::complex<float> *P_Beams, float *depth_image, float *normal_image, int width, int height, int depth_image_step, int normal_image_step, float *rand_image, int rand_image_step, float *reflectivity_image, int reflectivity_image_step, float hPixelSize, float vPixelSize, float hFOV, float vFOV, float beam_azimuthAngleWidth, float beam_elevationAngleWidth, float ray_azimuthAngleWidth, float ray_elevationAngleWidth, float soundSpeed, float sourceTerm, int nBeams, int nRays, int raySkips, float sonarFreq, float delta_f, int nFreq, float bandwidth, float attenuation, float area_scaler) { // 2D Index of current thread const int beam = blockIdx.x * blockDim.x + threadIdx.x; const int ray = blockIdx.y * blockDim.y + threadIdx.y; //Only valid threads perform memory I/O if ((beam < width) && (ray < height) && (ray % raySkips == 0)) { // Location of the image pixel const int depth_index = ray * depth_image_step / sizeof(float) + beam; const int normal_index = ray * normal_image_step / sizeof(float) + (3 * beam); const int rand_index = ray * rand_image_step / sizeof(float) + (2 * beam); const int reflectivity_index = ray * reflectivity_image_step / sizeof(float) + beam; // Input parameters for ray processing float distance = depth_image[depth_index] * 1.0f; float normal[3] = {normal_image[normal_index], normal_image[normal_index + 1], normal_image[normal_index + 2]}; // Calculate ray angles double fl = static_cast<double>(width) / (2.0 * tan(hFOV/2.0)); float ray_azimuthAngle = atan2(static_cast<double>(beam) - 0.5 * static_cast<double>(width-1), fl); float ray_elevationAngle = atan2(static_cast<double>(ray) - 0.5 * static_cast<double>(height-1), fl); // Beam pattern // float azimuthBeamPattern = abs(unnormalized_sinc(M_PI * 0.884 // / ray_azimuthAngleWidth * sin(ray_azimuthAngle))); // only one column of rays for each beam at beam center, interference calculated later float azimuthBeamPattern = 1.0; float elevationBeamPattern = abs(unnormalized_sinc(M_PI * 0.884 / (beam_elevationAngleWidth) * sin(ray_elevationAngle))); // incidence angle float incidence = acos(normal[2]); // compute_incidence(ray_azimuthAngle, ray_elevationAngle, normal); // ----- Point scattering model ------ // // Gaussian noise generated using opencv RNG float xi_z = rand_image[rand_index]; float xi_y = rand_image[rand_index + 1]; // Calculate amplitude thrust::complex<float> randomAmps = thrust::complex<float>(xi_z / sqrt(2.0), xi_y / sqrt(2.0)); thrust::complex<float> lambert_sqrt = thrust::complex<float>(sqrt(reflectivity_image[reflectivity_index]) * cos(incidence), 0.0); thrust::complex<float> beamPattern = thrust::complex<float>(azimuthBeamPattern * elevationBeamPattern, 0.0); thrust::complex<float> targetArea_sqrt = thrust::complex<float>(sqrt(distance * area_scaler), 0.0); thrust::complex<float> propagationTerm = thrust::complex<float>(1.0 / pow(distance, 2.0) * exp(-2.0 * attenuation * distance), 0.0); thrust::complex<float> amplitude = randomAmps * thrust::complex<float>(sourceTerm, 0.0) * propagationTerm * beamPattern * lambert_sqrt * targetArea_sqrt; // Summation of Echo returned from a signal (frequency domain) for (size_t f = 0; f < nFreq; f++) { float freq; if (nFreq % 2 == 0) freq = delta_f * (-nFreq / 2.0 + f*1.0f + 1.0); else freq = delta_f * (-(nFreq - 1) / 2.0 + f*1.0f + 1.0); float kw = 2.0 * M_PI * freq / soundSpeed; // wave vector // Transmit spectrum, frequency domain thrust::complex<float> kernel = exp(thrust::complex<float>(0.0f, 2.0f * distance * kw)) * amplitude; P_Beams[beam * nFreq * (int)(nRays / raySkips) + (int)(ray / raySkips) * nFreq + f] = thrust::complex<float>(kernel.real() , kernel.imag()); } } } /////////////////////////////////////////////////////////////////////////// namespace NpsGazeboSonar { // CUDA Device Checker Wrapper void check_cuda_init_wrapper(void) { // Check CUDA device hipDeviceSynchronize(); hipError_t error = hipGetLastError(); if (error != hipSuccess) { fprintf(stderr, "ERROR: %s\n", hipGetErrorString(error)); exit(-1); } } // Sonar Claculation Function Wrapper CArray2D sonar_calculation_wrapper(const cv::Mat &depth_image, const cv::Mat &normal_image, const cv::Mat &rand_image, double _hPixelSize, double _vPixelSize, double _hFOV, double _vFOV, double _beam_azimuthAngleWidth, double _beam_elevationAngleWidth, double _ray_azimuthAngleWidth, double _ray_elevationAngleWidth, double _soundSpeed, double _maxDistance, double _sourceLevel, int _nBeams, int _nRays, int _raySkips, double _sonarFreq, double _bandwidth, int _nFreq, const cv::Mat &reflectivity_image, double _attenuation, float *window, float **beamCorrector, float beamCorrectorSum, bool debugFlag) { auto start = std::chrono::high_resolution_clock::now(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); if (debugFlag) start = std::chrono::high_resolution_clock::now(); // ---- Allocation of properties parameters ---- // const float hPixelSize = (float)_hPixelSize; const float vPixelSize = (float)_vPixelSize; const float hFOV = (float)_hFOV; const float vFOV = (float)_vFOV; const float beam_elevationAngleWidth = (float)_beam_elevationAngleWidth; const float beam_azimuthAngleWidth = (float)_beam_azimuthAngleWidth; const float ray_elevationAngleWidth = (float)_ray_elevationAngleWidth; const float ray_azimuthAngleWidth = (float)_ray_azimuthAngleWidth; const float soundSpeed = (float)_soundSpeed; const float maxDistance = (float)_maxDistance; const float sonarFreq = (float)_sonarFreq; const float bandwidth = (float)_bandwidth; const float attenuation = (float)_attenuation; const int nBeams = _nBeams; const int nRays = _nRays; const int nFreq = _nFreq; const int raySkips = _raySkips; //#######################################################// //############### Sonar Calculation ################// //#######################################################// // --------- Calculation parameters --------- // const float max_distance = maxDistance; // Signal const float max_T = max_distance * 2.0 / soundSpeed; const float delta_f = 1.0 / max_T; // Precalculation const float area_scaler = ray_azimuthAngleWidth * ray_elevationAngleWidth; const float sourceLevel = (float)_sourceLevel; // db re 1 muPa; const float pref = 1e-6; // 1 micro pascal (muPa); const float sourceTerm = sqrt(pow(10, (sourceLevel / 10))) * pref; // source term // --------- Allocate GPU memory for image --------- // //Calculate total number of bytes of input and output image const int depth_image_Bytes = depth_image.step * depth_image.rows; const int normal_image_Bytes = normal_image.step * normal_image.rows; const int rand_image_Bytes = rand_image.step * rand_image.rows; const int reflectivity_image_Bytes = reflectivity_image.step * reflectivity_image.rows; //Allocate device memory float *d_depth_image, *d_normal_image, *d_rand_image, *d_reflectivity_image; SAFE_CALL(hipMalloc((void **)&d_depth_image, depth_image_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_normal_image, normal_image_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_rand_image, rand_image_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_reflectivity_image, reflectivity_image_Bytes), "CUDA Malloc Failed"); //Copy data from OpenCV input image to device memory SAFE_CALL(hipMemcpy(d_depth_image, depth_image.ptr(), depth_image_Bytes, hipMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(d_normal_image, normal_image.ptr(), normal_image_Bytes, hipMemcpyHostToDevice),"CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(d_rand_image, rand_image.ptr(), rand_image_Bytes, hipMemcpyHostToDevice),"CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(d_reflectivity_image, reflectivity_image.ptr(), reflectivity_image_Bytes, hipMemcpyHostToDevice), "CUDA Memcpy Failed"); //Specify a reasonable block size const dim3 block(BLOCK_SIZE, BLOCK_SIZE); //Calculate grid size to cover the whole image const dim3 grid((depth_image.cols + block.x - 1) / block.x, (depth_image.rows + block.y - 1) / block.y); // Beam data array thrust::complex<float> *P_Beams; thrust::complex<float> *d_P_Beams; const int P_Beams_N = nBeams * (int)(nRays / raySkips) * (nFreq + 1); const int P_Beams_Bytes = sizeof(thrust::complex<float>) * P_Beams_N; SAFE_CALL(hipHostMalloc((void **)&P_Beams, P_Beams_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_P_Beams, P_Beams_Bytes), "CUDA Malloc Failed"); //Launch the beamor conversion kernel hipLaunchKernelGGL(( sonar_calculation), dim3(grid), dim3(block), 0, 0, d_P_Beams, d_depth_image, d_normal_image, normal_image.cols, normal_image.rows, depth_image.step, normal_image.step, d_rand_image, rand_image.step, d_reflectivity_image, reflectivity_image.step, hPixelSize, vPixelSize, hFOV, vFOV, beam_azimuthAngleWidth, beam_elevationAngleWidth, ray_azimuthAngleWidth, ray_elevationAngleWidth, soundSpeed, sourceTerm, nBeams, nRays, raySkips, sonarFreq, delta_f, nFreq, bandwidth, attenuation, area_scaler); //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(P_Beams, d_P_Beams, P_Beams_Bytes, hipMemcpyDeviceToHost), "CUDA Memcpy Failed"); // Free GPU memory hipFree(d_depth_image); hipFree(d_normal_image); hipFree(d_rand_image); hipFree(d_reflectivity_image); hipFree(d_P_Beams); // For calc time measure if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("GPU Sonar Computation Time %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); start = std::chrono::high_resolution_clock::now(); } //########################################################// //######### Summation, Culling and windowing #########// //########################################################// // Preallocate an array for return CArray2D P_Beams_F(CArray(nFreq), nBeams); // GPU grids and rows unsigned int grid_rows, grid_cols; dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE); // GPU Ray summation using column sum float *P_Ray_real, *P_Ray_imag; float *d_P_Ray_real, *d_P_Ray_imag; const int P_Ray_N = (int)(nRays / raySkips) * (nFreq); const int P_Ray_Bytes = sizeof(float) * P_Ray_N; float *P_Ray_F_real, *P_Ray_F_imag; float *d_P_Ray_F_real, *d_P_Ray_F_imag; const int P_Ray_F_N = (nFreq)*1; const int P_Ray_F_Bytes = sizeof(float) * P_Ray_F_N; hipHostMalloc((void **)&P_Ray_real, P_Ray_Bytes); hipHostMalloc((void **)&P_Ray_imag, P_Ray_Bytes); hipHostMalloc((void **)&P_Ray_F_real, P_Ray_F_Bytes); hipHostMalloc((void **)&P_Ray_F_imag, P_Ray_F_Bytes); SAFE_CALL(hipMalloc((void **)&d_P_Ray_real, P_Ray_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_P_Ray_imag, P_Ray_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_P_Ray_F_real, P_Ray_F_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_P_Ray_F_imag, P_Ray_F_Bytes), "CUDA Malloc Failed"); dim3 dimGrid_Ray((nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE); for (size_t beam = 0; beam < nBeams; beam ++) { for (size_t ray = 0; ray < (int)(nRays / raySkips); ray++) { for (size_t f = 0; f < nFreq; f++) { P_Ray_real[ray * nFreq + f] = P_Beams[beam * nFreq * (int)(nRays / raySkips) + ray * nFreq + f].real(); P_Ray_imag[ray * nFreq + f] = P_Beams[beam * nFreq * (int)(nRays / raySkips) + ray * nFreq + f].imag(); } } SAFE_CALL(hipMemcpy(d_P_Ray_real, P_Ray_real, P_Ray_Bytes, hipMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(d_P_Ray_imag, P_Ray_imag, P_Ray_Bytes, hipMemcpyHostToDevice), "CUDA Memcpy Failed"); hipLaunchKernelGGL(( column_sums_reduce), dim3(dimGrid_Ray), dim3(dimBlock), 0, 0, d_P_Ray_real, d_P_Ray_F_real, nFreq, (int)(nRays / raySkips)); hipLaunchKernelGGL(( column_sums_reduce), dim3(dimGrid_Ray), dim3(dimBlock), 0, 0, d_P_Ray_imag, d_P_Ray_F_imag, nFreq, (int)(nRays / raySkips)); SAFE_CALL(hipMemcpy(P_Ray_F_real, d_P_Ray_F_real, P_Ray_F_Bytes, hipMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(P_Ray_F_imag, d_P_Ray_F_imag, P_Ray_F_Bytes, hipMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); for (size_t f = 0; f < nFreq; f++) P_Beams_F[beam][f] = Complex(P_Ray_F_real[f], P_Ray_F_imag[f]); } // free memory hipHostFree(P_Beams); hipHostFree(P_Ray_real); hipHostFree(P_Ray_imag); hipHostFree(P_Ray_F_real); hipHostFree(P_Ray_F_imag); hipFree(d_P_Ray_real); hipFree(d_P_Ray_imag); hipFree(d_P_Ray_F_real); hipFree(d_P_Ray_F_imag); if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("Sonar Ray Summation %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); start = std::chrono::high_resolution_clock::now(); } // -------------- Beam culling correction -----------------// // beamCorrector and beamCorrectorSum is precalculated at parent cpp float *P_Beams_Cor_real, *P_Beams_Cor_imag; // float *P_Beams_Cor_F_real, *P_Beams_Cor_F_imag; float *P_Beams_Cor_real_tmp, *P_Beams_Cor_imag_tmp; float *d_P_Beams_Cor_real, *d_P_Beams_Cor_imag; float *d_P_Beams_Cor_F_real, *d_P_Beams_Cor_F_imag; const int P_Beams_Cor_N = nBeams * nFreq; const int P_Beams_Cor_Bytes = sizeof(float) * P_Beams_Cor_N; hipHostMalloc((void **)&P_Beams_Cor_real, P_Beams_Cor_Bytes); hipHostMalloc((void **)&P_Beams_Cor_imag, P_Beams_Cor_Bytes); hipHostMalloc((void **)&P_Beams_Cor_real_tmp, P_Beams_Cor_Bytes); hipHostMalloc((void **)&P_Beams_Cor_imag_tmp, P_Beams_Cor_Bytes); // hipHostMalloc((void **)&P_Beams_Cor_F_real, P_Beams_Cor_Bytes); // hipHostMalloc((void **)&P_Beams_Cor_F_imag, P_Beams_Cor_Bytes); SAFE_CALL(hipMalloc((void **)&d_P_Beams_Cor_real, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_P_Beams_Cor_imag, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_P_Beams_Cor_F_real, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); SAFE_CALL(hipMalloc((void **)&d_P_Beams_Cor_F_imag, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); float *beamCorrector_lin, *d_beamCorrector_lin; const int beamCorrector_lin_N = nBeams * nBeams; const int beamCorrector_lin_Bytes = sizeof(float) * beamCorrector_lin_N; hipHostMalloc((void **)&beamCorrector_lin, beamCorrector_lin_Bytes); SAFE_CALL(hipMalloc((void **)&d_beamCorrector_lin, beamCorrector_lin_Bytes), "CUDA Malloc Failed"); // (nfreq x nBeams) * (nBeams x nBeams) = (nfreq x nBeams) for (size_t beam = 0; beam < nBeams; beam ++) { for (size_t f = 0; f < nFreq; f++) { P_Beams_Cor_real[f * nBeams + beam] = P_Beams_F[beam][f].real() * 1.0f; P_Beams_Cor_imag[f * nBeams + beam] = P_Beams_F[beam][f].imag() * 1.0f; } for (size_t beam_other = 0; beam_other < nBeams; beam_other ++) beamCorrector_lin[beam_other * nBeams + beam] = beamCorrector[beam][beam_other]; } SAFE_CALL(hipMemcpy(d_P_Beams_Cor_real, P_Beams_Cor_real, P_Beams_Cor_Bytes, hipMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(d_P_Beams_Cor_imag, P_Beams_Cor_imag, P_Beams_Cor_Bytes, hipMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(d_beamCorrector_lin, beamCorrector_lin, beamCorrector_lin_Bytes, hipMemcpyHostToDevice), "CUDA Memcpy Failed"); grid_rows = (nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE; grid_cols = (nBeams + BLOCK_SIZE - 1) / BLOCK_SIZE; dim3 dimGrid_Beam(grid_cols, grid_rows); hipLaunchKernelGGL(( gpu_matrix_mult), dim3(dimGrid_Beam), dim3(dimBlock), 0, 0, d_P_Beams_Cor_real, d_beamCorrector_lin, d_P_Beams_Cor_F_real, nFreq, nBeams, nBeams); SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); hipLaunchKernelGGL(( gpu_matrix_mult), dim3(dimGrid_Beam), dim3(dimBlock), 0, 0, d_P_Beams_Cor_imag, d_beamCorrector_lin, d_P_Beams_Cor_F_imag, nFreq, nBeams, nBeams); SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); //Copy back data from destination device meory SAFE_CALL(hipMemcpy(P_Beams_Cor_real_tmp, d_P_Beams_Cor_F_real, P_Beams_Cor_Bytes, hipMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(hipMemcpy(P_Beams_Cor_imag_tmp, d_P_Beams_Cor_F_imag, P_Beams_Cor_Bytes, hipMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); // --------------- Windowing ----------------- // // float *window_diag, *d_window; // const int window_N = nFreq * 1; // const int window_Bytes = sizeof(float) * window_N; // window_diag = (float *)malloc(window_Bytes); // SAFE_CALL(hipMalloc((void **)&d_window, window_Bytes), "CUDA Malloc Failed"); // int *diag_ptr, *d_diag_ptr; // const int diag_ptr_N = nBeams * 1; // const int diag_ptr_Bytes = sizeof(int) * diag_ptr_N; // diag_ptr = (int *)malloc(diag_ptr_Bytes); // SAFE_CALL(hipMalloc((void **)&d_diag_ptr, diag_ptr_Bytes), "CUDA Malloc Failed"); // // (nBeams x nfreq) * (1 x nFreq) = (nBeams x nFreq) // for (size_t beam = 0; beam < nBeams; beam ++) // { // for (size_t f = 0; f < nFreq; f++) // { // Transpose // P_Beams_Cor_real[beam * nFreq + f] = P_Beams_Cor_real_tmp[f * nBeams + beam]; // P_Beams_Cor_imag[beam * nFreq + f] = P_Beams_Cor_imag_tmp[f * nBeams + beam]; // window_diag[f] = window[f]; // } // diag_ptr[beam] = (int)beam; // } // SAFE_CALL(hipMemcpy(d_P_Beams_Cor_real, P_Beams_Cor_real, P_Beams_Cor_Bytes, // hipMemcpyHostToDevice), // "CUDA Memcpy Failed"); // SAFE_CALL(hipMemcpy(d_P_Beams_Cor_imag, P_Beams_Cor_imag, P_Beams_Cor_Bytes, // hipMemcpyHostToDevice), // "CUDA Memcpy Failed"); // SAFE_CALL(hipMemcpy(d_window, window_diag, window_Bytes, // hipMemcpyHostToDevice), // "CUDA Memcpy Failed"); // SAFE_CALL(hipMemcpy(d_diag_ptr, diag_ptr, diag_ptr_Bytes, // hipMemcpyHostToDevice), // "CUDA Memcpy Failed"); // grid_rows = (nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE; // grid_cols = (nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE; // dim3 dimGrid_window(grid_cols, grid_rows); // gpu_diag_matrix_mult<<<dimGrid_window, dimBlock>>>(d_P_Beams_Cor_real, d_diag_ptr, d_window, nFreq); // SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); // gpu_diag_matrix_mult<<<dimGrid_window, dimBlock>>>(d_P_Beams_Cor_imag, d_diag_ptr, d_window, nFreq); // SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); // //Copy back data from destination device meory // SAFE_CALL(hipMemcpy(P_Beams_Cor_F_real, d_P_Beams_Cor_real, P_Beams_Cor_Bytes, // hipMemcpyDeviceToHost), // "CUDA Memcpy Failed"); // SAFE_CALL(hipMemcpy(P_Beams_Cor_F_imag, d_P_Beams_Cor_imag, P_Beams_Cor_Bytes, // hipMemcpyDeviceToHost), // "CUDA Memcpy Failed"); // SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); // Return for (size_t beam = 0; beam < nBeams; beam ++) for (size_t f = 0; f < nFreq; f++) P_Beams_F[beam][f] = Complex(P_Beams_Cor_real_tmp[f * nBeams + beam] / beamCorrectorSum, P_Beams_Cor_imag_tmp[f * nBeams + beam] / beamCorrectorSum); // Free memory hipFree(d_P_Beams_Cor_imag); hipFree(d_P_Beams_Cor_real); hipFree(d_P_Beams_Cor_F_imag); hipFree(d_P_Beams_Cor_F_real); hipFree(d_beamCorrector_lin); // hipFree(d_window); // hipFree(d_diag_ptr); hipHostFree(P_Beams_Cor_real); hipHostFree(P_Beams_Cor_imag); // hipHostFree(P_Beams_Cor_F_real); // hipHostFree(P_Beams_Cor_F_imag); hipHostFree(P_Beams_Cor_real_tmp); hipHostFree(P_Beams_Cor_imag_tmp); hipHostFree(beamCorrector_lin); // hipHostFree(window_diag); // hipHostFree(diag_ptr); // For calc time measure if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("GPU Window & Correction %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); start = std::chrono::high_resolution_clock::now(); } //#################################################// //################### FFT #####################// //#################################################// SAFE_CALL(hipDeviceSynchronize(), "Kernel Launch Failed"); const int DATASIZE = nFreq; const int BATCH = nBeams; // --- Host side input data allocation and initialization hipfftComplex *hostInputData = (hipfftComplex *)malloc( DATASIZE * BATCH * sizeof(hipfftComplex)); for (int beam = 0; beam < BATCH; beam++) { for (int f = 0; f < DATASIZE; f++) { if (f < nFreq) hostInputData[beam * DATASIZE + f] = make_cuComplex(P_Beams_F[beam][f].real() * 1.0f, P_Beams_F[beam][f].imag() * 1.0f); else hostInputData[beam * DATASIZE + f] = (make_cuComplex(0.f, 0.f)); // zero padding } } // --- Device side input data allocation and initialization hipfftComplex *deviceInputData; SAFE_CALL(hipMalloc((void **)&deviceInputData, DATASIZE * BATCH * sizeof(hipfftComplex)), "FFT CUDA Malloc Failed"); SAFE_CALL(hipMemcpy(deviceInputData, hostInputData, DATASIZE * BATCH * sizeof(hipfftComplex), hipMemcpyHostToDevice), "FFT CUDA Memcopy Failed"); // --- Host side output data allocation hipfftComplex *hostOutputData = (hipfftComplex *)malloc(DATASIZE * BATCH * sizeof(hipfftComplex)); // --- Device side output data allocation hipfftComplex *deviceOutputData; hipMalloc((void **)&deviceOutputData, DATASIZE * BATCH * sizeof(hipfftComplex)); // --- Batched 1D FFTs hipfftHandle handle; int rank = 1; // --- 1D FFTs int n[] = {DATASIZE}; // --- Size of the Fourier transform // --- Distance between two successive input/output elements int istride = 1, ostride = 1; int idist = DATASIZE, odist = DATASIZE; // --- Distance between batches // --- Input/Output size with pitch (ignored for 1D transforms) int inembed[] = {0}; int onembed[] = {0}; int batch = BATCH; // --- Number of batched executions hipfftPlanMany(&handle, rank, n, inembed, istride, idist, onembed, ostride, odist, HIPFFT_C2C, batch); hipfftExecC2C(handle, deviceInputData, deviceOutputData, HIPFFT_FORWARD); // --- Device->Host copy of the results SAFE_CALL(hipMemcpy(hostOutputData, deviceOutputData, DATASIZE * BATCH * sizeof(hipfftComplex), hipMemcpyDeviceToHost), "FFT CUDA Memcopy Failed"); hipfftDestroy(handle); hipFree(deviceOutputData); hipFree(deviceInputData); free(hostInputData); free(hostOutputData); for (int beam = 0; beam < BATCH; beam++) { for (int f = 0; f < nFreq; f++) { P_Beams_F[beam][f] = Complex(hostOutputData[beam * DATASIZE + f].x * delta_f, hostOutputData[beam * DATASIZE + f].y * delta_f); } } // For calc time measure if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("GPU FFT Calc Time %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); } return P_Beams_F; } } // namespace NpsGazeboSonar
c3008afc9a7e0e332c3399f0603812698aa55a07.cu
/* * Copyright 2020 Naval Postgraduate School * * 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 <nps_uw_multibeam_sonar/sonar_calculation_cuda.cuh> // #include <math.h> #include <assert.h> // For complex numbers #include <thrust/complex.h> #include <cuComplex.h> // For rand() function #include <unistd.h> #include <curand.h> #include <curand_kernel.h> // For FFT #include <cufft.h> #include <cufftw.h> #include <thrust/device_vector.h> #include <list> #include <chrono> #define BLOCK_SIZE 32 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__) /////////////////////////////////////////////////////////////////////////// // Incident Angle Calculation Function // incidence angle is target's normal angle accounting for the ray's azimuth // and elevation __device__ float compute_incidence(float azimuth, float elevation, float *normal) { // ray normal from camera azimuth and elevation float camera_x = cosf(-azimuth) * cosf(elevation); float camera_y = sinf(-azimuth) * cosf(elevation); float camera_z = sinf(elevation); float ray_normal[3] = {camera_x, camera_y, camera_z}; // target normal with axes compensated to camera axes float target_normal[3] = {normal[2], -normal[0], -normal[1]}; // dot product float dot_product = ray_normal[0] * target_normal[0] + ray_normal[1] * target_normal[1] + ray_normal[2] * target_normal[2]; return M_PI - acosf(dot_product); } /////////////////////////////////////////////////////////////////////////// __device__ __host__ float unnormalized_sinc(float t) { if (abs(t) < 1E-8) return 1.0; else return sin(t) / t; } /////////////////////////////////////////////////////////////////////////// template <typename T> __global__ void column_sums_reduce(const T *__restrict__ in, T *__restrict__ out, size_t width, size_t height) { __shared__ T sdata[BLOCK_SIZE][BLOCK_SIZE + 1]; size_t idx = threadIdx.x + blockDim.x * blockIdx.x; size_t width_stride = gridDim.x * blockDim.x; size_t full_width = (width & (~((unsigned long long)(BLOCK_SIZE - 1)))) + ((width & (BLOCK_SIZE - 1)) ? BLOCK_SIZE : 0); // round up to next block for (size_t w = idx; w < full_width; w += width_stride) { // grid-stride loop across matrix width sdata[threadIdx.y][threadIdx.x] = 0; size_t in_ptr = w + threadIdx.y * width; for (size_t h = threadIdx.y; h < height; h += BLOCK_SIZE) { // block-stride loop across matrix height sdata[threadIdx.y][threadIdx.x] += (w < width) ? in[in_ptr] : 0; in_ptr += width * BLOCK_SIZE; } __syncthreads(); T my_val = sdata[threadIdx.x][threadIdx.y]; for (int i = warpSize >> 1; i > 0; i >>= 1) // warp-wise parallel sum reduction my_val += __shfl_xor_sync(0xFFFFFFFFU, my_val, i); __syncthreads(); if (threadIdx.x == 0) sdata[0][threadIdx.y] = my_val; __syncthreads(); if ((threadIdx.y == 0) && ((w) < width)) out[w] = sdata[0][threadIdx.x]; } } __global__ void gpu_matrix_mult(float *a, float *b, float *c, int m, int n, int k) { int row = blockIdx.y * blockDim.y + threadIdx.y; int col = blockIdx.x * blockDim.x + threadIdx.x; float sum = 0; if (col < k && row < m) { for (int i = 0; i < n; i++) { sum += a[row * n + i] * b[i * k + col]; } c[row * k + col] = sum; } } __global__ void gpu_diag_matrix_mult(float *Val, int *RowPtr, float *diagVals, int total_rows) { const int row = threadIdx.x + blockIdx.x * blockDim.x; if (row < total_rows) { for (int i = RowPtr[row]; i < RowPtr[row + 1]; i++) { Val[i] = diagVals[row] * Val[i]; } } } /////////////////////////////////////////////////////////////////////////// // Sonar Claculation Function __global__ void sonar_calculation(thrust::complex<float> *P_Beams, float *depth_image, float *normal_image, int width, int height, int depth_image_step, int normal_image_step, float *rand_image, int rand_image_step, float *reflectivity_image, int reflectivity_image_step, float hPixelSize, float vPixelSize, float hFOV, float vFOV, float beam_azimuthAngleWidth, float beam_elevationAngleWidth, float ray_azimuthAngleWidth, float ray_elevationAngleWidth, float soundSpeed, float sourceTerm, int nBeams, int nRays, int raySkips, float sonarFreq, float delta_f, int nFreq, float bandwidth, float attenuation, float area_scaler) { // 2D Index of current thread const int beam = blockIdx.x * blockDim.x + threadIdx.x; const int ray = blockIdx.y * blockDim.y + threadIdx.y; //Only valid threads perform memory I/O if ((beam < width) && (ray < height) && (ray % raySkips == 0)) { // Location of the image pixel const int depth_index = ray * depth_image_step / sizeof(float) + beam; const int normal_index = ray * normal_image_step / sizeof(float) + (3 * beam); const int rand_index = ray * rand_image_step / sizeof(float) + (2 * beam); const int reflectivity_index = ray * reflectivity_image_step / sizeof(float) + beam; // Input parameters for ray processing float distance = depth_image[depth_index] * 1.0f; float normal[3] = {normal_image[normal_index], normal_image[normal_index + 1], normal_image[normal_index + 2]}; // Calculate ray angles double fl = static_cast<double>(width) / (2.0 * tan(hFOV/2.0)); float ray_azimuthAngle = atan2(static_cast<double>(beam) - 0.5 * static_cast<double>(width-1), fl); float ray_elevationAngle = atan2(static_cast<double>(ray) - 0.5 * static_cast<double>(height-1), fl); // Beam pattern // float azimuthBeamPattern = abs(unnormalized_sinc(M_PI * 0.884 // / ray_azimuthAngleWidth * sin(ray_azimuthAngle))); // only one column of rays for each beam at beam center, interference calculated later float azimuthBeamPattern = 1.0; float elevationBeamPattern = abs(unnormalized_sinc(M_PI * 0.884 / (beam_elevationAngleWidth) * sin(ray_elevationAngle))); // incidence angle float incidence = acos(normal[2]); // compute_incidence(ray_azimuthAngle, ray_elevationAngle, normal); // ----- Point scattering model ------ // // Gaussian noise generated using opencv RNG float xi_z = rand_image[rand_index]; float xi_y = rand_image[rand_index + 1]; // Calculate amplitude thrust::complex<float> randomAmps = thrust::complex<float>(xi_z / sqrt(2.0), xi_y / sqrt(2.0)); thrust::complex<float> lambert_sqrt = thrust::complex<float>(sqrt(reflectivity_image[reflectivity_index]) * cos(incidence), 0.0); thrust::complex<float> beamPattern = thrust::complex<float>(azimuthBeamPattern * elevationBeamPattern, 0.0); thrust::complex<float> targetArea_sqrt = thrust::complex<float>(sqrt(distance * area_scaler), 0.0); thrust::complex<float> propagationTerm = thrust::complex<float>(1.0 / pow(distance, 2.0) * exp(-2.0 * attenuation * distance), 0.0); thrust::complex<float> amplitude = randomAmps * thrust::complex<float>(sourceTerm, 0.0) * propagationTerm * beamPattern * lambert_sqrt * targetArea_sqrt; // Summation of Echo returned from a signal (frequency domain) for (size_t f = 0; f < nFreq; f++) { float freq; if (nFreq % 2 == 0) freq = delta_f * (-nFreq / 2.0 + f*1.0f + 1.0); else freq = delta_f * (-(nFreq - 1) / 2.0 + f*1.0f + 1.0); float kw = 2.0 * M_PI * freq / soundSpeed; // wave vector // Transmit spectrum, frequency domain thrust::complex<float> kernel = exp(thrust::complex<float>(0.0f, 2.0f * distance * kw)) * amplitude; P_Beams[beam * nFreq * (int)(nRays / raySkips) + (int)(ray / raySkips) * nFreq + f] = thrust::complex<float>(kernel.real() , kernel.imag()); } } } /////////////////////////////////////////////////////////////////////////// namespace NpsGazeboSonar { // CUDA Device Checker Wrapper void check_cuda_init_wrapper(void) { // Check CUDA device cudaDeviceSynchronize(); cudaError_t error = cudaGetLastError(); if (error != cudaSuccess) { fprintf(stderr, "ERROR: %s\n", cudaGetErrorString(error)); exit(-1); } } // Sonar Claculation Function Wrapper CArray2D sonar_calculation_wrapper(const cv::Mat &depth_image, const cv::Mat &normal_image, const cv::Mat &rand_image, double _hPixelSize, double _vPixelSize, double _hFOV, double _vFOV, double _beam_azimuthAngleWidth, double _beam_elevationAngleWidth, double _ray_azimuthAngleWidth, double _ray_elevationAngleWidth, double _soundSpeed, double _maxDistance, double _sourceLevel, int _nBeams, int _nRays, int _raySkips, double _sonarFreq, double _bandwidth, int _nFreq, const cv::Mat &reflectivity_image, double _attenuation, float *window, float **beamCorrector, float beamCorrectorSum, bool debugFlag) { auto start = std::chrono::high_resolution_clock::now(); auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); if (debugFlag) start = std::chrono::high_resolution_clock::now(); // ---- Allocation of properties parameters ---- // const float hPixelSize = (float)_hPixelSize; const float vPixelSize = (float)_vPixelSize; const float hFOV = (float)_hFOV; const float vFOV = (float)_vFOV; const float beam_elevationAngleWidth = (float)_beam_elevationAngleWidth; const float beam_azimuthAngleWidth = (float)_beam_azimuthAngleWidth; const float ray_elevationAngleWidth = (float)_ray_elevationAngleWidth; const float ray_azimuthAngleWidth = (float)_ray_azimuthAngleWidth; const float soundSpeed = (float)_soundSpeed; const float maxDistance = (float)_maxDistance; const float sonarFreq = (float)_sonarFreq; const float bandwidth = (float)_bandwidth; const float attenuation = (float)_attenuation; const int nBeams = _nBeams; const int nRays = _nRays; const int nFreq = _nFreq; const int raySkips = _raySkips; //#######################################################// //############### Sonar Calculation ################// //#######################################################// // --------- Calculation parameters --------- // const float max_distance = maxDistance; // Signal const float max_T = max_distance * 2.0 / soundSpeed; const float delta_f = 1.0 / max_T; // Precalculation const float area_scaler = ray_azimuthAngleWidth * ray_elevationAngleWidth; const float sourceLevel = (float)_sourceLevel; // db re 1 muPa; const float pref = 1e-6; // 1 micro pascal (muPa); const float sourceTerm = sqrt(pow(10, (sourceLevel / 10))) * pref; // source term // --------- Allocate GPU memory for image --------- // //Calculate total number of bytes of input and output image const int depth_image_Bytes = depth_image.step * depth_image.rows; const int normal_image_Bytes = normal_image.step * normal_image.rows; const int rand_image_Bytes = rand_image.step * rand_image.rows; const int reflectivity_image_Bytes = reflectivity_image.step * reflectivity_image.rows; //Allocate device memory float *d_depth_image, *d_normal_image, *d_rand_image, *d_reflectivity_image; SAFE_CALL(cudaMalloc((void **)&d_depth_image, depth_image_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_normal_image, normal_image_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_rand_image, rand_image_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_reflectivity_image, reflectivity_image_Bytes), "CUDA Malloc Failed"); //Copy data from OpenCV input image to device memory SAFE_CALL(cudaMemcpy(d_depth_image, depth_image.ptr(), depth_image_Bytes, cudaMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(d_normal_image, normal_image.ptr(), normal_image_Bytes, cudaMemcpyHostToDevice),"CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(d_rand_image, rand_image.ptr(), rand_image_Bytes, cudaMemcpyHostToDevice),"CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(d_reflectivity_image, reflectivity_image.ptr(), reflectivity_image_Bytes, cudaMemcpyHostToDevice), "CUDA Memcpy Failed"); //Specify a reasonable block size const dim3 block(BLOCK_SIZE, BLOCK_SIZE); //Calculate grid size to cover the whole image const dim3 grid((depth_image.cols + block.x - 1) / block.x, (depth_image.rows + block.y - 1) / block.y); // Beam data array thrust::complex<float> *P_Beams; thrust::complex<float> *d_P_Beams; const int P_Beams_N = nBeams * (int)(nRays / raySkips) * (nFreq + 1); const int P_Beams_Bytes = sizeof(thrust::complex<float>) * P_Beams_N; SAFE_CALL(cudaMallocHost((void **)&P_Beams, P_Beams_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_P_Beams, P_Beams_Bytes), "CUDA Malloc Failed"); //Launch the beamor conversion kernel sonar_calculation<<<grid, block>>>(d_P_Beams, d_depth_image, d_normal_image, normal_image.cols, normal_image.rows, depth_image.step, normal_image.step, d_rand_image, rand_image.step, d_reflectivity_image, reflectivity_image.step, hPixelSize, vPixelSize, hFOV, vFOV, beam_azimuthAngleWidth, beam_elevationAngleWidth, ray_azimuthAngleWidth, ray_elevationAngleWidth, soundSpeed, sourceTerm, nBeams, nRays, raySkips, sonarFreq, delta_f, nFreq, bandwidth, attenuation, area_scaler); //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(P_Beams, d_P_Beams, P_Beams_Bytes, cudaMemcpyDeviceToHost), "CUDA Memcpy Failed"); // Free GPU memory cudaFree(d_depth_image); cudaFree(d_normal_image); cudaFree(d_rand_image); cudaFree(d_reflectivity_image); cudaFree(d_P_Beams); // For calc time measure if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("GPU Sonar Computation Time %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); start = std::chrono::high_resolution_clock::now(); } //########################################################// //######### Summation, Culling and windowing #########// //########################################################// // Preallocate an array for return CArray2D P_Beams_F(CArray(nFreq), nBeams); // GPU grids and rows unsigned int grid_rows, grid_cols; dim3 dimBlock(BLOCK_SIZE, BLOCK_SIZE); // GPU Ray summation using column sum float *P_Ray_real, *P_Ray_imag; float *d_P_Ray_real, *d_P_Ray_imag; const int P_Ray_N = (int)(nRays / raySkips) * (nFreq); const int P_Ray_Bytes = sizeof(float) * P_Ray_N; float *P_Ray_F_real, *P_Ray_F_imag; float *d_P_Ray_F_real, *d_P_Ray_F_imag; const int P_Ray_F_N = (nFreq)*1; const int P_Ray_F_Bytes = sizeof(float) * P_Ray_F_N; cudaMallocHost((void **)&P_Ray_real, P_Ray_Bytes); cudaMallocHost((void **)&P_Ray_imag, P_Ray_Bytes); cudaMallocHost((void **)&P_Ray_F_real, P_Ray_F_Bytes); cudaMallocHost((void **)&P_Ray_F_imag, P_Ray_F_Bytes); SAFE_CALL(cudaMalloc((void **)&d_P_Ray_real, P_Ray_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_P_Ray_imag, P_Ray_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_P_Ray_F_real, P_Ray_F_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_P_Ray_F_imag, P_Ray_F_Bytes), "CUDA Malloc Failed"); dim3 dimGrid_Ray((nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE); for (size_t beam = 0; beam < nBeams; beam ++) { for (size_t ray = 0; ray < (int)(nRays / raySkips); ray++) { for (size_t f = 0; f < nFreq; f++) { P_Ray_real[ray * nFreq + f] = P_Beams[beam * nFreq * (int)(nRays / raySkips) + ray * nFreq + f].real(); P_Ray_imag[ray * nFreq + f] = P_Beams[beam * nFreq * (int)(nRays / raySkips) + ray * nFreq + f].imag(); } } SAFE_CALL(cudaMemcpy(d_P_Ray_real, P_Ray_real, P_Ray_Bytes, cudaMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(d_P_Ray_imag, P_Ray_imag, P_Ray_Bytes, cudaMemcpyHostToDevice), "CUDA Memcpy Failed"); column_sums_reduce<<<dimGrid_Ray, dimBlock>>>(d_P_Ray_real, d_P_Ray_F_real, nFreq, (int)(nRays / raySkips)); column_sums_reduce<<<dimGrid_Ray, dimBlock>>>(d_P_Ray_imag, d_P_Ray_F_imag, nFreq, (int)(nRays / raySkips)); SAFE_CALL(cudaMemcpy(P_Ray_F_real, d_P_Ray_F_real, P_Ray_F_Bytes, cudaMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(P_Ray_F_imag, d_P_Ray_F_imag, P_Ray_F_Bytes, cudaMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); for (size_t f = 0; f < nFreq; f++) P_Beams_F[beam][f] = Complex(P_Ray_F_real[f], P_Ray_F_imag[f]); } // free memory cudaFreeHost(P_Beams); cudaFreeHost(P_Ray_real); cudaFreeHost(P_Ray_imag); cudaFreeHost(P_Ray_F_real); cudaFreeHost(P_Ray_F_imag); cudaFree(d_P_Ray_real); cudaFree(d_P_Ray_imag); cudaFree(d_P_Ray_F_real); cudaFree(d_P_Ray_F_imag); if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("Sonar Ray Summation %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); start = std::chrono::high_resolution_clock::now(); } // -------------- Beam culling correction -----------------// // beamCorrector and beamCorrectorSum is precalculated at parent cpp float *P_Beams_Cor_real, *P_Beams_Cor_imag; // float *P_Beams_Cor_F_real, *P_Beams_Cor_F_imag; float *P_Beams_Cor_real_tmp, *P_Beams_Cor_imag_tmp; float *d_P_Beams_Cor_real, *d_P_Beams_Cor_imag; float *d_P_Beams_Cor_F_real, *d_P_Beams_Cor_F_imag; const int P_Beams_Cor_N = nBeams * nFreq; const int P_Beams_Cor_Bytes = sizeof(float) * P_Beams_Cor_N; cudaMallocHost((void **)&P_Beams_Cor_real, P_Beams_Cor_Bytes); cudaMallocHost((void **)&P_Beams_Cor_imag, P_Beams_Cor_Bytes); cudaMallocHost((void **)&P_Beams_Cor_real_tmp, P_Beams_Cor_Bytes); cudaMallocHost((void **)&P_Beams_Cor_imag_tmp, P_Beams_Cor_Bytes); // cudaMallocHost((void **)&P_Beams_Cor_F_real, P_Beams_Cor_Bytes); // cudaMallocHost((void **)&P_Beams_Cor_F_imag, P_Beams_Cor_Bytes); SAFE_CALL(cudaMalloc((void **)&d_P_Beams_Cor_real, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_P_Beams_Cor_imag, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_P_Beams_Cor_F_real, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); SAFE_CALL(cudaMalloc((void **)&d_P_Beams_Cor_F_imag, P_Beams_Cor_Bytes), "CUDA Malloc Failed"); float *beamCorrector_lin, *d_beamCorrector_lin; const int beamCorrector_lin_N = nBeams * nBeams; const int beamCorrector_lin_Bytes = sizeof(float) * beamCorrector_lin_N; cudaMallocHost((void **)&beamCorrector_lin, beamCorrector_lin_Bytes); SAFE_CALL(cudaMalloc((void **)&d_beamCorrector_lin, beamCorrector_lin_Bytes), "CUDA Malloc Failed"); // (nfreq x nBeams) * (nBeams x nBeams) = (nfreq x nBeams) for (size_t beam = 0; beam < nBeams; beam ++) { for (size_t f = 0; f < nFreq; f++) { P_Beams_Cor_real[f * nBeams + beam] = P_Beams_F[beam][f].real() * 1.0f; P_Beams_Cor_imag[f * nBeams + beam] = P_Beams_F[beam][f].imag() * 1.0f; } for (size_t beam_other = 0; beam_other < nBeams; beam_other ++) beamCorrector_lin[beam_other * nBeams + beam] = beamCorrector[beam][beam_other]; } SAFE_CALL(cudaMemcpy(d_P_Beams_Cor_real, P_Beams_Cor_real, P_Beams_Cor_Bytes, cudaMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(d_P_Beams_Cor_imag, P_Beams_Cor_imag, P_Beams_Cor_Bytes, cudaMemcpyHostToDevice), "CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(d_beamCorrector_lin, beamCorrector_lin, beamCorrector_lin_Bytes, cudaMemcpyHostToDevice), "CUDA Memcpy Failed"); grid_rows = (nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE; grid_cols = (nBeams + BLOCK_SIZE - 1) / BLOCK_SIZE; dim3 dimGrid_Beam(grid_cols, grid_rows); gpu_matrix_mult<<<dimGrid_Beam, dimBlock>>>(d_P_Beams_Cor_real, d_beamCorrector_lin, d_P_Beams_Cor_F_real, nFreq, nBeams, nBeams); SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); gpu_matrix_mult<<<dimGrid_Beam, dimBlock>>>(d_P_Beams_Cor_imag, d_beamCorrector_lin, d_P_Beams_Cor_F_imag, nFreq, nBeams, nBeams); SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); //Copy back data from destination device meory SAFE_CALL(cudaMemcpy(P_Beams_Cor_real_tmp, d_P_Beams_Cor_F_real, P_Beams_Cor_Bytes, cudaMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(cudaMemcpy(P_Beams_Cor_imag_tmp, d_P_Beams_Cor_F_imag, P_Beams_Cor_Bytes, cudaMemcpyDeviceToHost), "CUDA Memcpy Failed"); SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); // --------------- Windowing ----------------- // // float *window_diag, *d_window; // const int window_N = nFreq * 1; // const int window_Bytes = sizeof(float) * window_N; // window_diag = (float *)malloc(window_Bytes); // SAFE_CALL(cudaMalloc((void **)&d_window, window_Bytes), "CUDA Malloc Failed"); // int *diag_ptr, *d_diag_ptr; // const int diag_ptr_N = nBeams * 1; // const int diag_ptr_Bytes = sizeof(int) * diag_ptr_N; // diag_ptr = (int *)malloc(diag_ptr_Bytes); // SAFE_CALL(cudaMalloc((void **)&d_diag_ptr, diag_ptr_Bytes), "CUDA Malloc Failed"); // // (nBeams x nfreq) * (1 x nFreq) = (nBeams x nFreq) // for (size_t beam = 0; beam < nBeams; beam ++) // { // for (size_t f = 0; f < nFreq; f++) // { // Transpose // P_Beams_Cor_real[beam * nFreq + f] = P_Beams_Cor_real_tmp[f * nBeams + beam]; // P_Beams_Cor_imag[beam * nFreq + f] = P_Beams_Cor_imag_tmp[f * nBeams + beam]; // window_diag[f] = window[f]; // } // diag_ptr[beam] = (int)beam; // } // SAFE_CALL(cudaMemcpy(d_P_Beams_Cor_real, P_Beams_Cor_real, P_Beams_Cor_Bytes, // cudaMemcpyHostToDevice), // "CUDA Memcpy Failed"); // SAFE_CALL(cudaMemcpy(d_P_Beams_Cor_imag, P_Beams_Cor_imag, P_Beams_Cor_Bytes, // cudaMemcpyHostToDevice), // "CUDA Memcpy Failed"); // SAFE_CALL(cudaMemcpy(d_window, window_diag, window_Bytes, // cudaMemcpyHostToDevice), // "CUDA Memcpy Failed"); // SAFE_CALL(cudaMemcpy(d_diag_ptr, diag_ptr, diag_ptr_Bytes, // cudaMemcpyHostToDevice), // "CUDA Memcpy Failed"); // grid_rows = (nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE; // grid_cols = (nFreq + BLOCK_SIZE - 1) / BLOCK_SIZE; // dim3 dimGrid_window(grid_cols, grid_rows); // gpu_diag_matrix_mult<<<dimGrid_window, dimBlock>>>(d_P_Beams_Cor_real, d_diag_ptr, d_window, nFreq); // SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); // gpu_diag_matrix_mult<<<dimGrid_window, dimBlock>>>(d_P_Beams_Cor_imag, d_diag_ptr, d_window, nFreq); // SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); // //Copy back data from destination device meory // SAFE_CALL(cudaMemcpy(P_Beams_Cor_F_real, d_P_Beams_Cor_real, P_Beams_Cor_Bytes, // cudaMemcpyDeviceToHost), // "CUDA Memcpy Failed"); // SAFE_CALL(cudaMemcpy(P_Beams_Cor_F_imag, d_P_Beams_Cor_imag, P_Beams_Cor_Bytes, // cudaMemcpyDeviceToHost), // "CUDA Memcpy Failed"); // SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); // Return for (size_t beam = 0; beam < nBeams; beam ++) for (size_t f = 0; f < nFreq; f++) P_Beams_F[beam][f] = Complex(P_Beams_Cor_real_tmp[f * nBeams + beam] / beamCorrectorSum, P_Beams_Cor_imag_tmp[f * nBeams + beam] / beamCorrectorSum); // Free memory cudaFree(d_P_Beams_Cor_imag); cudaFree(d_P_Beams_Cor_real); cudaFree(d_P_Beams_Cor_F_imag); cudaFree(d_P_Beams_Cor_F_real); cudaFree(d_beamCorrector_lin); // cudaFree(d_window); // cudaFree(d_diag_ptr); cudaFreeHost(P_Beams_Cor_real); cudaFreeHost(P_Beams_Cor_imag); // cudaFreeHost(P_Beams_Cor_F_real); // cudaFreeHost(P_Beams_Cor_F_imag); cudaFreeHost(P_Beams_Cor_real_tmp); cudaFreeHost(P_Beams_Cor_imag_tmp); cudaFreeHost(beamCorrector_lin); // cudaFreeHost(window_diag); // cudaFreeHost(diag_ptr); // For calc time measure if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("GPU Window & Correction %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); start = std::chrono::high_resolution_clock::now(); } //#################################################// //################### FFT #####################// //#################################################// SAFE_CALL(cudaDeviceSynchronize(), "Kernel Launch Failed"); const int DATASIZE = nFreq; const int BATCH = nBeams; // --- Host side input data allocation and initialization cufftComplex *hostInputData = (cufftComplex *)malloc( DATASIZE * BATCH * sizeof(cufftComplex)); for (int beam = 0; beam < BATCH; beam++) { for (int f = 0; f < DATASIZE; f++) { if (f < nFreq) hostInputData[beam * DATASIZE + f] = make_cuComplex(P_Beams_F[beam][f].real() * 1.0f, P_Beams_F[beam][f].imag() * 1.0f); else hostInputData[beam * DATASIZE + f] = (make_cuComplex(0.f, 0.f)); // zero padding } } // --- Device side input data allocation and initialization cufftComplex *deviceInputData; SAFE_CALL(cudaMalloc((void **)&deviceInputData, DATASIZE * BATCH * sizeof(cufftComplex)), "FFT CUDA Malloc Failed"); SAFE_CALL(cudaMemcpy(deviceInputData, hostInputData, DATASIZE * BATCH * sizeof(cufftComplex), cudaMemcpyHostToDevice), "FFT CUDA Memcopy Failed"); // --- Host side output data allocation cufftComplex *hostOutputData = (cufftComplex *)malloc(DATASIZE * BATCH * sizeof(cufftComplex)); // --- Device side output data allocation cufftComplex *deviceOutputData; cudaMalloc((void **)&deviceOutputData, DATASIZE * BATCH * sizeof(cufftComplex)); // --- Batched 1D FFTs cufftHandle handle; int rank = 1; // --- 1D FFTs int n[] = {DATASIZE}; // --- Size of the Fourier transform // --- Distance between two successive input/output elements int istride = 1, ostride = 1; int idist = DATASIZE, odist = DATASIZE; // --- Distance between batches // --- Input/Output size with pitch (ignored for 1D transforms) int inembed[] = {0}; int onembed[] = {0}; int batch = BATCH; // --- Number of batched executions cufftPlanMany(&handle, rank, n, inembed, istride, idist, onembed, ostride, odist, CUFFT_C2C, batch); cufftExecC2C(handle, deviceInputData, deviceOutputData, CUFFT_FORWARD); // --- Device->Host copy of the results SAFE_CALL(cudaMemcpy(hostOutputData, deviceOutputData, DATASIZE * BATCH * sizeof(cufftComplex), cudaMemcpyDeviceToHost), "FFT CUDA Memcopy Failed"); cufftDestroy(handle); cudaFree(deviceOutputData); cudaFree(deviceInputData); free(hostInputData); free(hostOutputData); for (int beam = 0; beam < BATCH; beam++) { for (int f = 0; f < nFreq; f++) { P_Beams_F[beam][f] = Complex(hostOutputData[beam * DATASIZE + f].x * delta_f, hostOutputData[beam * DATASIZE + f].y * delta_f); } } // For calc time measure if (debugFlag) { stop = std::chrono::high_resolution_clock::now(); duration = std::chrono::duration_cast<std::chrono::microseconds>(stop - start); printf("GPU FFT Calc Time %lld/100 [s]\n", static_cast<long long int>(duration.count() / 10000)); } return P_Beams_F; } } // namespace NpsGazeboSonar
bf26e4430c45bd545028f030297e88f059b109cf.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* * Copyright 1993-2007 NVIDIA Corporation. All rights reserved. * * NOTICE TO USER: * * This source code is subject to NVIDIA ownership rights under U.S. and * international Copyright laws. Users and possessors of this source code * are hereby granted a nonexclusive, royalty-free license to use this code * in individual and commercial software. * * NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE * CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR * IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. * IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOURCE CODE. * * U.S. Government End Users. This source code is a "commercial item" as * that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of * "commercial computer software" and "commercial computer software * documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995) * and is provided to the U.S. Government only as a commercial end item. * Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through * 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the * source code with only those rights set forth herein. * * Any use of this source code in individual and commercial software must * include, in the user documentation and internal comments to the code, * the above Disclaimer and U.S. Government End Users Notice. */ /* matrix project which demonstrates the basics on how to setup a project * example application. * Device code. */ #ifndef _matrix_KERNEL_H_ #define _matrix_KERNEL_H_ #include <stdio.h> #include <matrix.h> #define SDATA( index) CUT_BANK_CHECKER(sdata, index) //////////////////////////////////////////////////////////////////////////////// //! Simple test kernel for device functionality //! @param g_idata input data in global memory //! @param g_odata output data in global memory //////////////////////////////////////////////////////////////////////////////// __global__ void testKernel( float* d_matrixA, float* d_matrixB, float* d_matrixC, const unsigned int ah, const unsigned int aw, const unsigned int bh, const unsigned int bw) { // shared memory - Matrix B #ifdef CHANGE4 __shared__ float shm_matrixB[KERNEL_SIZE+(2*KERNEL_LENGTH)]; #elif defined(CHANGE1) __shared__ float shm_matrixB[KERNEL_SIZE]; #endif // shared memory - SubMatrix A #ifdef CHANGE4 __shared__ float shm_subMatrixA[BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH+WARP_SIZE]; #elif defined(CHANGE3) __shared__ float shm_subMatrixA0[BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH]; __shared__ float shm_subMatrixA1[BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH]; #elif defined(CHANGE2) __shared__ float shm_subMatrixA[2*BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH]; #endif // the size is determined by the host application const unsigned int bx = blockIdx.x; const unsigned int by = blockIdx.y; // access thread id const int tx = threadIdx.x; const int ty = threadIdx.y; #ifdef CHANGE3 int xstep = bx; int ystep = 2 * by; #elif defined(CHANGE2) int xstep = bx; int ystep = by; #else int xstep = BLOCK_SIZE * bx; int ystep = BLOCK_SIZE * by; #endif #ifdef CHANGE3 float sum0 = 0; float sum1 = 0; #else float sum = 0; #endif int y = ystep + ty; int x = xstep + tx; #ifdef CHANGE4 if(tx<(KERNEL_LENGTH)) {// Padding zeros to get rid of dependence on divergence shm_matrixB[ tx ] = 0; shm_matrixB[ KERNEL_SIZE + tx ] = 0; } // Padding zeros to get rid of dependence on divergence if(tx<(KERNEL_SIZE)) shm_matrixB[ tx + KERNEL_LENGTH ] = d_matrixB[ tx ]; if(tx<(WARP_SIZE)) shm_subMatrixA[ tx ] = 0; __syncthreads(); #elif defined(CHANGE1) if((tx<(KERNEL_SIZE))) shm_matrixB[ tx ] = d_matrixB[ tx ]; // __syncthreads(); #endif /* -------------------------------- Computation -------------------------------------*/ #ifdef CHANGE4 //modified code for (int j=0; j<bh+1; j++) { shm_subMatrixA[tx+WARP_SIZE] = 0; if ((y-j+1)>-1) { shm_subMatrixA[tx+WARP_SIZE] = d_matrixA[(y-j+1)*aw+(x)]; } __syncthreads(); for(int k = 0; k < bw; ++k) { float b0 = shm_matrixB[j*bw+k]; float b1 = shm_matrixB[(j+1)*bw+k]; float a = 0; a = shm_subMatrixA[tx-k+WARP_SIZE]; sum0 += a*b0; sum1 += a*b1; }//k loop __syncthreads(); }//j loop #elif defined(CHANGE3) //modified code for (int j=0; j<bh; j++) { if ((((y-j)>-1) &&(y-j)<ah)) { shm_subMatrixA0[tx] = d_matrixA[(y-j)*aw+(x)]; } if ((((y+1-j)>-1) &&(y+1-j)<ah)) { shm_subMatrixA1[tx] = d_matrixA[(y+1-j)*aw+(x)]; } __syncthreads(); for(int k = 0; k < bw; ++k) { float b = shm_matrixB[j*bw+k]; float a0 = 0; float a1 = 0; // check the out-of-bound if ((((y-j)>-1) &&(y-j)<ah)&&(x-k)>-1&&(x-k)<aw) { a0 = shm_subMatrixA0[tx-k]; sum0 += a0*b; } if ((((y+1-j)>-1) &&(y+1-j)<ah)&&(x-k)>-1&&(x-k)<aw) { a1 = shm_subMatrixA1[tx-k]; sum1 += a1*b; } }//k loop __syncthreads(); }//j loop #elif defined(CHANGE2) //modified code for (int j=0; j<bh; j++) { #if 0 if(tx<WARP_SIZE) if (((y-j)>-1) &&((y-j)<ah)&&((x-DATA_TO_PULL_SIZE)>-1)&&((x - DATA_TO_PULL_SIZE)<aw)) shm_subMatrixA[tx] = d_matrixA[(y-j)*aw+(x-DATA_TO_PULL_SIZE)]; #endif if ((((y-j)>-1) &&(y-j)<ah)) shm_subMatrixA[tx] = d_matrixA[(y-j)*aw+(x)]; __syncthreads(); for(int k = 0; k < bw; ++k) { float b = shm_matrixB[j*bw+k]; float a = 0; // check the out-of-bound if ((y-j)>-1 &&(y-j)<ah&&((x)-k)>-1&&((x)-k)<aw) { a = shm_subMatrixA[tx-k]; sum += a*b; } }//k loop __syncthreads(); }//j loop #elif defined(CHANGE1) //modified code for (int j=0; j<bh; j++) { for(int k = 0; k < bw; ++k) { float b = shm_matrixB[j*bw+k]; float a = 0; // check the out-of-bound if ((y-j)>-1&&(y-j)<ah&&(x-k)>-1&&(x-k)<aw) { a = d_matrixA[(y-j)*aw+(x-k)]; sum += a*b; } } } //j loop __syncthreads(); #else //Original Code for (int j=0; j<bh; j++) { for(int k = 0; k < bw; ++k) { float b = d_matrixB[j*bw+k]; float a = 0; // check the out-of-bound if ((y-j)>-1&&(y-j)<ah&&(x-k)>-1&&(x-k)<aw) { a = d_matrixA[(y-j)*aw+(x-k)]; sum += a*b; } } }//j loop #endif //CHANGES #ifdef CHANGE4 // write data to global memory d_matrixC[(1*y*aw)+x] = sum0; d_matrixC[(((1*y)+1)*aw)+x] = sum1; #elif defined(CHANGE3) // write data to global memory d_matrixC[(1*y*aw)+x] = sum0; d_matrixC[(((1*y)+1)*aw)+x] = sum1; #else // write data to global memory d_matrixC[y*aw+x] = sum; #endif }// end of func #endif // #ifndef _matrix_KERNEL_H_
bf26e4430c45bd545028f030297e88f059b109cf.cu
/* * Copyright 1993-2007 NVIDIA Corporation. All rights reserved. * * NOTICE TO USER: * * This source code is subject to NVIDIA ownership rights under U.S. and * international Copyright laws. Users and possessors of this source code * are hereby granted a nonexclusive, royalty-free license to use this code * in individual and commercial software. * * NVIDIA MAKES NO REPRESENTATION ABOUT THE SUITABILITY OF THIS SOURCE * CODE FOR ANY PURPOSE. IT IS PROVIDED "AS IS" WITHOUT EXPRESS OR * IMPLIED WARRANTY OF ANY KIND. NVIDIA DISCLAIMS ALL WARRANTIES WITH * REGARD TO THIS SOURCE CODE, INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY, NONINFRINGEMENT, AND FITNESS FOR A PARTICULAR PURPOSE. * IN NO EVENT SHALL NVIDIA BE LIABLE FOR ANY SPECIAL, INDIRECT, INCIDENTAL, * OR CONSEQUENTIAL DAMAGES, OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS * OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE * OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE * OR PERFORMANCE OF THIS SOURCE CODE. * * U.S. Government End Users. This source code is a "commercial item" as * that term is defined at 48 C.F.R. 2.101 (OCT 1995), consisting of * "commercial computer software" and "commercial computer software * documentation" as such terms are used in 48 C.F.R. 12.212 (SEPT 1995) * and is provided to the U.S. Government only as a commercial end item. * Consistent with 48 C.F.R.12.212 and 48 C.F.R. 227.7202-1 through * 227.7202-4 (JUNE 1995), all U.S. Government End Users acquire the * source code with only those rights set forth herein. * * Any use of this source code in individual and commercial software must * include, in the user documentation and internal comments to the code, * the above Disclaimer and U.S. Government End Users Notice. */ /* matrix project which demonstrates the basics on how to setup a project * example application. * Device code. */ #ifndef _matrix_KERNEL_H_ #define _matrix_KERNEL_H_ #include <stdio.h> #include <matrix.h> #define SDATA( index) CUT_BANK_CHECKER(sdata, index) //////////////////////////////////////////////////////////////////////////////// //! Simple test kernel for device functionality //! @param g_idata input data in global memory //! @param g_odata output data in global memory //////////////////////////////////////////////////////////////////////////////// __global__ void testKernel( float* d_matrixA, float* d_matrixB, float* d_matrixC, const unsigned int ah, const unsigned int aw, const unsigned int bh, const unsigned int bw) { // shared memory - Matrix B #ifdef CHANGE4 __shared__ float shm_matrixB[KERNEL_SIZE+(2*KERNEL_LENGTH)]; #elif defined(CHANGE1) __shared__ float shm_matrixB[KERNEL_SIZE]; #endif // shared memory - SubMatrix A #ifdef CHANGE4 __shared__ float shm_subMatrixA[BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH+WARP_SIZE]; #elif defined(CHANGE3) __shared__ float shm_subMatrixA0[BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH]; __shared__ float shm_subMatrixA1[BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH]; #elif defined(CHANGE2) __shared__ float shm_subMatrixA[2*BLOCK_SIZE_HEIGHT*BLOCK_SIZE_WIDTH]; #endif // the size is determined by the host application const unsigned int bx = blockIdx.x; const unsigned int by = blockIdx.y; // access thread id const int tx = threadIdx.x; const int ty = threadIdx.y; #ifdef CHANGE3 int xstep = bx; int ystep = 2 * by; #elif defined(CHANGE2) int xstep = bx; int ystep = by; #else int xstep = BLOCK_SIZE * bx; int ystep = BLOCK_SIZE * by; #endif #ifdef CHANGE3 float sum0 = 0; float sum1 = 0; #else float sum = 0; #endif int y = ystep + ty; int x = xstep + tx; #ifdef CHANGE4 if(tx<(KERNEL_LENGTH)) {// Padding zeros to get rid of dependence on divergence shm_matrixB[ tx ] = 0; shm_matrixB[ KERNEL_SIZE + tx ] = 0; } // Padding zeros to get rid of dependence on divergence if(tx<(KERNEL_SIZE)) shm_matrixB[ tx + KERNEL_LENGTH ] = d_matrixB[ tx ]; if(tx<(WARP_SIZE)) shm_subMatrixA[ tx ] = 0; __syncthreads(); #elif defined(CHANGE1) if((tx<(KERNEL_SIZE))) shm_matrixB[ tx ] = d_matrixB[ tx ]; // __syncthreads(); #endif /* -------------------------------- Computation -------------------------------------*/ #ifdef CHANGE4 //modified code for (int j=0; j<bh+1; j++) { shm_subMatrixA[tx+WARP_SIZE] = 0; if ((y-j+1)>-1) { shm_subMatrixA[tx+WARP_SIZE] = d_matrixA[(y-j+1)*aw+(x)]; } __syncthreads(); for(int k = 0; k < bw; ++k) { float b0 = shm_matrixB[j*bw+k]; float b1 = shm_matrixB[(j+1)*bw+k]; float a = 0; a = shm_subMatrixA[tx-k+WARP_SIZE]; sum0 += a*b0; sum1 += a*b1; }//k loop __syncthreads(); }//j loop #elif defined(CHANGE3) //modified code for (int j=0; j<bh; j++) { if ((((y-j)>-1) &&(y-j)<ah)) { shm_subMatrixA0[tx] = d_matrixA[(y-j)*aw+(x)]; } if ((((y+1-j)>-1) &&(y+1-j)<ah)) { shm_subMatrixA1[tx] = d_matrixA[(y+1-j)*aw+(x)]; } __syncthreads(); for(int k = 0; k < bw; ++k) { float b = shm_matrixB[j*bw+k]; float a0 = 0; float a1 = 0; // check the out-of-bound if ((((y-j)>-1) &&(y-j)<ah)&&(x-k)>-1&&(x-k)<aw) { a0 = shm_subMatrixA0[tx-k]; sum0 += a0*b; } if ((((y+1-j)>-1) &&(y+1-j)<ah)&&(x-k)>-1&&(x-k)<aw) { a1 = shm_subMatrixA1[tx-k]; sum1 += a1*b; } }//k loop __syncthreads(); }//j loop #elif defined(CHANGE2) //modified code for (int j=0; j<bh; j++) { #if 0 if(tx<WARP_SIZE) if (((y-j)>-1) &&((y-j)<ah)&&((x-DATA_TO_PULL_SIZE)>-1)&&((x - DATA_TO_PULL_SIZE)<aw)) shm_subMatrixA[tx] = d_matrixA[(y-j)*aw+(x-DATA_TO_PULL_SIZE)]; #endif if ((((y-j)>-1) &&(y-j)<ah)) shm_subMatrixA[tx] = d_matrixA[(y-j)*aw+(x)]; __syncthreads(); for(int k = 0; k < bw; ++k) { float b = shm_matrixB[j*bw+k]; float a = 0; // check the out-of-bound if ((y-j)>-1 &&(y-j)<ah&&((x)-k)>-1&&((x)-k)<aw) { a = shm_subMatrixA[tx-k]; sum += a*b; } }//k loop __syncthreads(); }//j loop #elif defined(CHANGE1) //modified code for (int j=0; j<bh; j++) { for(int k = 0; k < bw; ++k) { float b = shm_matrixB[j*bw+k]; float a = 0; // check the out-of-bound if ((y-j)>-1&&(y-j)<ah&&(x-k)>-1&&(x-k)<aw) { a = d_matrixA[(y-j)*aw+(x-k)]; sum += a*b; } } } //j loop __syncthreads(); #else //Original Code for (int j=0; j<bh; j++) { for(int k = 0; k < bw; ++k) { float b = d_matrixB[j*bw+k]; float a = 0; // check the out-of-bound if ((y-j)>-1&&(y-j)<ah&&(x-k)>-1&&(x-k)<aw) { a = d_matrixA[(y-j)*aw+(x-k)]; sum += a*b; } } }//j loop #endif //CHANGES #ifdef CHANGE4 // write data to global memory d_matrixC[(1*y*aw)+x] = sum0; d_matrixC[(((1*y)+1)*aw)+x] = sum1; #elif defined(CHANGE3) // write data to global memory d_matrixC[(1*y*aw)+x] = sum0; d_matrixC[(((1*y)+1)*aw)+x] = sum1; #else // write data to global memory d_matrixC[y*aw+x] = sum; #endif }// end of func #endif // #ifndef _matrix_KERNEL_H_
0f53aa2d79ea96eade52db2c9c5c9affe0c20785.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /* -- MAGMA (version 2.5.4) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date October 2020 csymv.cu is nearly identical to chemv.cu, just change names and drop MAGMA_C_CONJ. csymv_kernel_U (upper) in csymv_upper.cu is very similar to csymv_kernel_L (lower) in csymv.cu; diff the two files to compare. Note: [ds] precisions generated from chemv.cu @generated from magmablas/zsymv.cu, normal z -> c, Thu Oct 8 23:05:36 2020 @author Mark Gates */ #include "magma_internal.h" #include "commonblas_c.h" #define PRECISION_c #define NB_X 64 #define NB_Y 4 #define bank_shift 33 #define quarter_NB_X 16 #define half_NB_X 32 /***************************************************************************//** Lower case, compute block multiply, work = A*x, for any size n: [ A11*x1 A12*x2 A13*x3 ] [ A11 A12 A13 ] [ x1 ] work = [ --- (A21*x1 + A22*x2) A23*x3 ] = [ A21 A22 A23 ] * [ x2 ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] [ A31 A32 A33 ] [ x3 ] Uses a 64x4 thread block. For diagonal tiles, covers a 64x64 tile using three 32x32 tiles (plus one gets transposed). For off-diagonal tiles, covers a 64x64 tile using four 64x16 tiles. In both cases, each thread multiplies 4 elements. For rows past the bottom of the matrix, the A pointer is adjusted to be the last valid row of A, which multiple threads will read. Extra rows are ignored when saving results to work. Columns past the right edge are explicitly ignored when loading. x values past the bottom are set to zero, thus, extra columns are zeroed when multiplying. Previously: [ A11*x1 --- ] work = [ A12*x2 (A21*x1 + A22*x2) --- ] [ A13*x3 A23*x3 (A31*x1 + A32*x2 + A33*x3) ] which doesn't work as well because that has dimension blocks*NB by blocks, where blocks*NB >= n, and it can be that blocks*NB > lda, so it won't fit in lda*blocks space. This is why it used to need lwork = lda*(blocks + 1). *******************************************************************************/ __global__ void csymv_kernel_L( int n, magmaFloatComplex const * __restrict__ A, int lda, magmaFloatComplex const * __restrict__ x, int incx, magmaFloatComplex * __restrict__ work) { #if defined(PRECISION_s) || defined(PRECISION_d) || defined(PRECISION_c) || (__CUDA_ARCH__ >= 200) // treats sA as 16x64 block #define sA16(i_, j_) (sA[(i_)][(j_)]) // i.e., sA[ (i_)*(NB_X+3) + (j_) ] // treats sA as 32x32 block #define sA32(i_, j_) (sA[0][(i_) + bank_shift*(j_)]) // 64x4 thread block const int tx = threadIdx.x; const int ty = threadIdx.y; const int blk = blockIdx.x; const int blk_ind = NB_X * blk; const int td = NB_X * ty + tx; // 32x8 thread block const int tx2 = td % half_NB_X; const int ty2 = td / half_NB_X; // If this blk has fewer than NB_X rows, partial is the number of valid rows, // so tx = 0, ..., partial-1 are valid rows, and tx >= partial are invalid. // Else, partial == 0. const int partial = (blk == gridDim.x - 1 ? (n % NB_X) : 0); magmaFloatComplex psum, psum_t; magmaFloatComplex total = MAGMA_C_ZERO; // sA is used as a 32x32 block, sA32(i,j), // and as a 16x64 block, sA16(i,j), in different parts of the code. // sA must be at least half_NB_X*bank_shift = 32x33 = 1056; // quarter_NB_X*(NB_X + 2) = 16*(64 + 2) = 1056 __shared__ magmaFloatComplex sA [quarter_NB_X][NB_X + 3]; /* Why +3? seems it only needs +2. Does +3 reduce bank conflicts? */ __shared__ magmaFloatComplex sx_blk[NB_X]; // for x[ blk ] __shared__ magmaFloatComplex sx_jj [NB_X]; // for x[ jj ], which cycles over all blocks left of diag magmaFloatComplex rA[4]; magmaFloatComplex psums_t[4]; // -------------------- // load 64x1 block x(blk_ind + 0:63) into sx_blk x += (blk_ind + tx)*incx; // x is x(blk_ind + tx) if ( ty == 0 ) { if ( partial == 0 || tx < partial ) { sx_blk[tx] = x[0]; } else { sx_blk[tx] = MAGMA_C_ZERO; } } // -------------------- // move to block row work += blk*lda; // work is work(0, blk) A += blk_ind; // A is A(blk_ind, 0) A += ty2*lda + tx2; // A is A(blk_ind + tx2, ty2) // move to 32x32 diag block A += blk_ind*lda; // A is A(blk_ind + tx2, blk_ind + ty2) // load 32x32 diag block A(blk_ind + 0:31, blk_ind + 0:31) into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 >= partial ) { A = A - tx2 + (partial - 1); // A is A(blk_ind + partial-1, blk_ind + ty2), the bottom-most valid row } #pragma unroll for (int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } else { sA32(tx2, ty2 + j) = MAGMA_C_ZERO; } } if ( tx2 >= partial ) { A = A + tx2 - (partial - 1); // A is A(blk_ind + tx2, blk_ind + ty2) } } else { #pragma unroll for (int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle, // as four 32x8 sections in parallel: // columns 0,4,8,12,16,20,24,28; then 1,5,...,29; then 2,6,...,30, then 3,7,...,31 #pragma unroll for (int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = sA32(tx2, j); } } __syncthreads(); // multiply 32x32 diag block * x // each thread does partial row sA(tx2, ty2*4 : ty2*4 + 3) psum = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to next 32x32 diag block, then repeat steps from first diag block A += half_NB_X + half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + NB/2 + ty2) // load 32x32 diag block A[block + 0:31, block + 0:31] into sA if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for (int j=0; j < half_NB_X; j += 8) { if ( ty2+j + half_NB_X < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } else { sA32(tx2, ty2 + j) = MAGMA_C_ZERO; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for (int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle #pragma unroll for (int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = sA32(tx2, j); } } __syncthreads(); // multiply 32x32 diag block * x psum = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to off-diag 32x32 block A -= half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + ty2) // load 32x32 block of A into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for (int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } else { sA32(tx2, ty2 + j) = MAGMA_C_ZERO; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for (int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // multiply 32x32 block (below diag) psum = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum += sA32(tx2, ty2 + j*8) * sx_blk[j*8 + ty2]; } //__syncthreads(); // no sync needed here // multiply transposed 32x32 block (above diag) psum_t = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum_t += sA32(ty2*4 + j, tx2) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial sums for non-transposed 32x32 block sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // store partial sums for transposed 32x32 block sA32(ty2, tx2) = psum_t; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to leftmost 64x64 block in block row, and // switch thread offset from (tx2,ty2) 32x8 block to (tx,ty) 64x4 block A -= half_NB_X; // A is A(blk_ind + tx2, blk_ind + ty2) A -= blk_ind*lda; // A is A(blk_ind + tx2, ty2) A -= ty2*lda + tx2; // A is A(blk_ind, 0) A += 4*ty*lda + tx; // A is A(blk_ind + tx, 4*ty) if ( partial && tx >= partial ) { A = A - tx + (partial - 1); // A is A(blk_ind + partial-1, 4*ty), the bottom-most valid row } x -= blk_ind*incx; // x is x(tx) // 16x16 thread block const int tx4 = td % quarter_NB_X; const int ty4 = td / quarter_NB_X; // cycle over blocks jj left of diagonal, in block row blk for (int jj=0; jj < blk; ++jj) { // load 64x1 block x(jj_ind + 0:63) into sx_jj // since this block is left of diagonal, x must have all NB rows if ( ty == 0 ) { sx_jj[tx] = x[jj*NB_X*incx]; } __syncthreads(); for (int k=0; k < 4; k++) { // load 64x16 block of A into rA, 4 elements per thread, // as four 64x4 sections in parallel: // columns 0,4,8,12; then 1,5,9,13; then 2,6,10,14; then 3,7,11,15 // since this block is left of diagonal, it has all NB columns, // and block of x must have all NB rows. #pragma unroll for (int j=0; j < 4; j++) { rA[j] = A[j*lda]; } // 1) multiply 64x16 block A_{blk,jj} * x_jj // each thread does partial row rA(tx + 16*k, ty*4 + 16*k : ty*4 + 3 + 16*k) // 2) multiply transposed 16x64 block A_{blk,jj}^H * x_blk, // storing each product Aji*xi to sA(j,i) #pragma unroll for (int j=0; j < 4; j++) { total += rA[j] * sx_jj[quarter_NB_X*k + ty*4 + j]; // y_blk = A_{blk,jj} * x_jj sA16(ty*4 + j, tx) = rA[j] * sx_blk[tx]; // y_jj = A_{blk,jj}^H * x_blk } __syncthreads(); // do partial row sums for transposed 16x64 result // use 16x16 thread grid (tx4, ty4) instead of 64x4 (tx, ty) // sum sixteen 16x4 sections in parallel: // columns 0,4,8,...,60; then 1,5,...,61; then 2,6,...,62; then 3,7,...,63 psum_t = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum_t += sA16(tx4, ty4*4 + j); } __syncthreads(); // store partial row sums of transposed result, y_jj (locally) psums_t[k] = psum_t; // move right to next 64x16 block A += lda * quarter_NB_X; // A is A(blk_ind + tx#, jj*NB_x + (k+1)*NB_X/4 + 4*ty), # tx or partial } // already at next 64x64 block // A is A(blk_ind + tx#, (jj+1)*NB_x + 4*ty), # tx or partial // store partial row sums of transposed result, y_jj #pragma unroll for (int k=0; k < 4; k++) { sA16(tx4, ty4 + quarter_NB_X*k) = psums_t[k]; } __syncthreads(); // sum up partial row sums of transposed result, y_jj, and store final total to workspace // thread (tx4,ty4) where ty4 < 4 sums row tx4 + ty4*16 // since this is the transposed block above the diagonal, it must have all NB rows if ( ty4 < 4 ) { int ty4_nb4 = ty4*quarter_NB_X; psum_t = sA16(tx4, 0 + ty4_nb4) + sA16(tx4, 1 + ty4_nb4) + sA16(tx4, 2 + ty4_nb4) + sA16(tx4, 3 + ty4_nb4) + sA16(tx4, 4 + ty4_nb4) + sA16(tx4, 5 + ty4_nb4) + sA16(tx4, 6 + ty4_nb4) + sA16(tx4, 7 + ty4_nb4) + sA16(tx4, 8 + ty4_nb4) + sA16(tx4, 9 + ty4_nb4) + sA16(tx4, 10 + ty4_nb4) + sA16(tx4, 11 + ty4_nb4) + sA16(tx4, 12 + ty4_nb4) + sA16(tx4, 13 + ty4_nb4) + sA16(tx4, 14 + ty4_nb4) + sA16(tx4, 15 + ty4_nb4); work[jj*NB_X + tx4 + ty4_nb4] = psum_t; // store at work( jj*NB_X + tx4 + ty4*16, blk ) } __syncthreads(); } // store row sums sA16(ty, tx) = total; __syncthreads(); // sum up final total, y_blk, for row tx if ( ty == 0 && (partial == 0 || tx < partial) ) { total = sA16(0, tx) + sA16(1, tx) + sA16(2, tx) + sA16(3, tx); work[blk*NB_X + tx] = total; // store at work( blk*NB_X + tx, blk ) } #endif /* PRECISION_[sdc] || (__CUDA_ARCH__ >= 200) */ } // end csymv_kernel_L /***************************************************************************//** Lower case, sum up final results Each block sums one block row; each thread sums one row. On input (for 3 blocks): [ (A11*x1) (A21^H*x2) (A31^H*x3) ] work = [ --- (A21*x1 + A22*x2) (A32^H*x3) ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] On output: [ (A11*x1) + (A21^H*x2) + (A31^H*x3) ] y = alpha*[ (A21*x1 + A22*x2) + (A32^H*x3) ] + beta*y [ (A21*x1 + A22*x2 + A33*x3) ] *******************************************************************************/ __global__ void csymv_kernel_L_sum( int n, magmaFloatComplex alpha, int lda, magmaFloatComplex beta, magmaFloatComplex * __restrict__ y, int incy, magmaFloatComplex const * __restrict__ work ) { int tx = threadIdx.x; int blk = blockIdx.x; int blk_ind = blk * NB_X; int ind = blk_ind + tx; int blocks = gridDim.x; // Don't write outside [0, ..., n) if ( ind < n ) { work += ind + blk*lda; magmaFloatComplex Ax = MAGMA_C_ZERO; for (int j = blk; j < blocks; ++j) { Ax += work[0]; work += lda; } y[ind * incy] = beta*y[ind * incy] + alpha*Ax; } } /***************************************************************************//** Purpose ------- magmablas_csymv_work performs the matrix-vector operation: y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n complex symmetric matrix. Arguments ---------- @param[in] uplo magma_uplo_t. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: - = MagmaUpper: Only the upper triangular part of A is to be referenced. - = MagmaLower: Only the lower triangular part of A is to be referenced. @param[in] n INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. @param[in] alpha COMPLEX. On entry, ALPHA specifies the scalar alpha. @param[in] dA COMPLEX array of DIMENSION ( LDDA, n ). Before entry with UPLO = MagmaUpper, the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = MagmaLower, the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. @param[in] ldda INTEGER. On entry, LDDA specifies the first dimension of A as declared in the calling (sub) program. LDDA must be at least max( 1, n ). It is recommended that ldda is multiple of 16. Otherwise performance would be deteriorated as the memory accesses would not be fully coalescent. @param[in] dx COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. @param[in] incx INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. @param[in] beta COMPLEX. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. @param[in,out] dy COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. @param[in] incy INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. @param[in] dwork (workspace) COMPLEX array on the GPU, dimension (MAX(1, LWORK)), @param[in] lwork INTEGER. The dimension of the array DWORK. LWORK >= LDDA * ceil( N / NB_X ), where NB_X = 64. @param[in] queue magma_queue_t. Queue to execute in. MAGMA implements csymv through two steps: 1) perform the multiplication in each thread block and put the intermediate value in dwork. 2) sum the intermediate values and store the final result in y. magamblas_csymv_work requires users to provide a workspace, while magmablas_csymv is a wrapper routine allocating the workspace inside the routine and provides the same interface as cublas. If users need to call csymv frequently, we suggest using magmablas_csymv_work instead of magmablas_csymv. As the overhead to allocate and free in device memory in magmablas_csymv would hurt performance. Our tests show that this penalty is about 10 Gflop/s when the matrix size is around 10000. @ingroup magma_symv *******************************************************************************/ extern "C" magma_int_t magmablas_csymv_work( magma_uplo_t uplo, magma_int_t n, magmaFloatComplex alpha, magmaFloatComplex_const_ptr dA, magma_int_t ldda, magmaFloatComplex_const_ptr dx, magma_int_t incx, magmaFloatComplex beta, magmaFloatComplex_ptr dy, magma_int_t incy, magmaFloatComplex_ptr dwork, magma_int_t lwork, magma_queue_t queue ) { #if defined(PRECISION_z) // z precision requires CUDA ARCH 2.x; call CUBLAS version instead. magma_int_t arch = magma_getdevice_arch(); if ( arch < 200 ) { //magma_csymv( uplo, n, alpha, dA, ldda, dx, incx, beta, dy, incy ); //return MAGMA_SUCCESS; fprintf(stderr, "%s: %s\n", __func__, "not supported on CUDA ARCH 1.x"); return MAGMA_ERR_NOT_SUPPORTED; } #endif // -------------------- // [sdc] precisions, or z precision with CUDA ARCH 2.x bool upper = (uplo == MagmaUpper); magma_int_t blocks = magma_ceildiv( n, NB_X ); magma_int_t lwmin = ldda*blocks; /* * Test the input parameters. */ magma_int_t info = 0; if ((! upper) && (uplo != MagmaLower)) { info = -1; } else if ( n < 0 ) { info = -2; } else if ( ldda < max(1, n) ) { info = -5; } else if ( incx == 0 ) { info = -7; } else if ( incy == 0 ) { info = -10; } else if ( lwork < lwmin ) { info = -12; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( (n == 0) || ( MAGMA_C_EQUAL(alpha, MAGMA_C_ZERO) && MAGMA_C_EQUAL(beta, MAGMA_C_ONE) ) ) return info; dim3 grid( blocks, 1, 1 ); dim3 threads( NB_X, NB_Y, 1 ); dim3 threads_sum( NB_X, 1, 1 ); if ( upper ) { hipLaunchKernelGGL(( csymv_kernel_U), dim3(grid), dim3(threads), 0, queue->cuda_stream() , n, dA, ldda, dx, incx, dwork); hipLaunchKernelGGL(( csymv_kernel_U_sum), dim3(grid), dim3(threads_sum), 0, queue->cuda_stream() , n, alpha, ldda, beta, dy, incy, dwork); } else { hipLaunchKernelGGL(( csymv_kernel_L), dim3(grid), dim3(threads), 0, queue->cuda_stream() , n, dA, ldda, dx, incx, dwork); hipLaunchKernelGGL(( csymv_kernel_L_sum), dim3(grid), dim3(threads_sum), 0, queue->cuda_stream() , n, alpha, ldda, beta, dy, incy, dwork); } return info; } // end magmablas_csymv_work /***************************************************************************//** Purpose ------- magmablas_csymv performs the matrix-vector operation: y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n complex symmetric matrix. Arguments ---------- @param[in] uplo magma_uplo_t. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: - = MagmaUpper: Only the upper triangular part of A is to be referenced. - = MagmaLower: Only the lower triangular part of A is to be referenced. @param[in] n INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. @param[in] alpha COMPLEX. On entry, ALPHA specifies the scalar alpha. @param[in] dA COMPLEX array of DIMENSION ( LDDA, n ). Before entry with UPLO = MagmaUpper, the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = MagmaLower, the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. @param[in] ldda INTEGER. On entry, LDDA specifies the first dimension of A as declared in the calling (sub) program. LDDA must be at least max( 1, n ). It is recommended that ldda is multiple of 16. Otherwise performance would be deteriorated as the memory accesses would not be fully coalescent. @param[in] dx COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. @param[in] incx INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. @param[in] beta COMPLEX. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. @param[in,out] dy COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. @param[in] incy INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. @param[in] queue magma_queue_t Queue to execute in. @ingroup magma_symv *******************************************************************************/ extern "C" magma_int_t magmablas_csymv( magma_uplo_t uplo, magma_int_t n, magmaFloatComplex alpha, magmaFloatComplex_const_ptr dA, magma_int_t ldda, magmaFloatComplex_const_ptr dx, magma_int_t incx, magmaFloatComplex beta, magmaFloatComplex_ptr dy, magma_int_t incy, magma_queue_t queue ) { #if defined(PRECISION_z) // z precision requires CUDA ARCH 2.x; no CUBLAS version of csymv. magma_int_t arch = magma_getdevice_arch(); if ( arch < 200 ) { //magma_csymv( uplo, n, alpha, dA, ldda, dx, incx, beta, dy, incy ); //return MAGMA_SUCCESS; fprintf(stderr, "%s: %s\n", __func__, "not supported on CUDA ARCH 1.x"); return MAGMA_ERR_NOT_SUPPORTED; } #endif // -------------------- // [sdc] precisions, or z precision with CUDA ARCH 2.x bool upper = (uplo == MagmaUpper); /* * Test the input parameters. */ magma_int_t info = 0; if ((! upper) && (uplo != MagmaLower)) { info = -1; } else if ( n < 0 ) { info = -2; } else if ( ldda < max(1, n) ) { info = -5; } else if ( incx == 0 ) { info = -7; } else if ( incy == 0 ) { info = -10; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( (n == 0) || ( MAGMA_C_EQUAL(alpha, MAGMA_C_ZERO) && MAGMA_C_EQUAL(beta, MAGMA_C_ONE) ) ) return info; magmaFloatComplex_ptr dwork; magma_int_t blocks = magma_ceildiv( n, NB_X ); magma_int_t lwork = ldda*blocks; magma_cmalloc( &dwork, lwork ); if ( dwork == NULL ) { info = MAGMA_ERR_DEVICE_ALLOC; magma_xerbla( __func__, -(info) ); return info; } magmablas_csymv_work( uplo, n, alpha, dA, ldda, dx, incx, beta, dy, incy, dwork, lwork, queue ); magma_free( dwork ); return info; } // end magmablas_csymv
0f53aa2d79ea96eade52db2c9c5c9affe0c20785.cu
/* -- MAGMA (version 2.5.4) -- Univ. of Tennessee, Knoxville Univ. of California, Berkeley Univ. of Colorado, Denver @date October 2020 csymv.cu is nearly identical to chemv.cu, just change names and drop MAGMA_C_CONJ. csymv_kernel_U (upper) in csymv_upper.cu is very similar to csymv_kernel_L (lower) in csymv.cu; diff the two files to compare. Note: [ds] precisions generated from chemv.cu @generated from magmablas/zsymv.cu, normal z -> c, Thu Oct 8 23:05:36 2020 @author Mark Gates */ #include "magma_internal.h" #include "commonblas_c.h" #define PRECISION_c #define NB_X 64 #define NB_Y 4 #define bank_shift 33 #define quarter_NB_X 16 #define half_NB_X 32 /***************************************************************************//** Lower case, compute block multiply, work = A*x, for any size n: [ A11*x1 A12*x2 A13*x3 ] [ A11 A12 A13 ] [ x1 ] work = [ --- (A21*x1 + A22*x2) A23*x3 ] = [ A21 A22 A23 ] * [ x2 ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] [ A31 A32 A33 ] [ x3 ] Uses a 64x4 thread block. For diagonal tiles, covers a 64x64 tile using three 32x32 tiles (plus one gets transposed). For off-diagonal tiles, covers a 64x64 tile using four 64x16 tiles. In both cases, each thread multiplies 4 elements. For rows past the bottom of the matrix, the A pointer is adjusted to be the last valid row of A, which multiple threads will read. Extra rows are ignored when saving results to work. Columns past the right edge are explicitly ignored when loading. x values past the bottom are set to zero, thus, extra columns are zeroed when multiplying. Previously: [ A11*x1 --- ] work = [ A12*x2 (A21*x1 + A22*x2) --- ] [ A13*x3 A23*x3 (A31*x1 + A32*x2 + A33*x3) ] which doesn't work as well because that has dimension blocks*NB by blocks, where blocks*NB >= n, and it can be that blocks*NB > lda, so it won't fit in lda*blocks space. This is why it used to need lwork = lda*(blocks + 1). *******************************************************************************/ __global__ void csymv_kernel_L( int n, magmaFloatComplex const * __restrict__ A, int lda, magmaFloatComplex const * __restrict__ x, int incx, magmaFloatComplex * __restrict__ work) { #if defined(PRECISION_s) || defined(PRECISION_d) || defined(PRECISION_c) || (__CUDA_ARCH__ >= 200) // treats sA as 16x64 block #define sA16(i_, j_) (sA[(i_)][(j_)]) // i.e., sA[ (i_)*(NB_X+3) + (j_) ] // treats sA as 32x32 block #define sA32(i_, j_) (sA[0][(i_) + bank_shift*(j_)]) // 64x4 thread block const int tx = threadIdx.x; const int ty = threadIdx.y; const int blk = blockIdx.x; const int blk_ind = NB_X * blk; const int td = NB_X * ty + tx; // 32x8 thread block const int tx2 = td % half_NB_X; const int ty2 = td / half_NB_X; // If this blk has fewer than NB_X rows, partial is the number of valid rows, // so tx = 0, ..., partial-1 are valid rows, and tx >= partial are invalid. // Else, partial == 0. const int partial = (blk == gridDim.x - 1 ? (n % NB_X) : 0); magmaFloatComplex psum, psum_t; magmaFloatComplex total = MAGMA_C_ZERO; // sA is used as a 32x32 block, sA32(i,j), // and as a 16x64 block, sA16(i,j), in different parts of the code. // sA must be at least half_NB_X*bank_shift = 32x33 = 1056; // quarter_NB_X*(NB_X + 2) = 16*(64 + 2) = 1056 __shared__ magmaFloatComplex sA [quarter_NB_X][NB_X + 3]; /* Why +3? seems it only needs +2. Does +3 reduce bank conflicts? */ __shared__ magmaFloatComplex sx_blk[NB_X]; // for x[ blk ] __shared__ magmaFloatComplex sx_jj [NB_X]; // for x[ jj ], which cycles over all blocks left of diag magmaFloatComplex rA[4]; magmaFloatComplex psums_t[4]; // -------------------- // load 64x1 block x(blk_ind + 0:63) into sx_blk x += (blk_ind + tx)*incx; // x is x(blk_ind + tx) if ( ty == 0 ) { if ( partial == 0 || tx < partial ) { sx_blk[tx] = x[0]; } else { sx_blk[tx] = MAGMA_C_ZERO; } } // -------------------- // move to block row work += blk*lda; // work is work(0, blk) A += blk_ind; // A is A(blk_ind, 0) A += ty2*lda + tx2; // A is A(blk_ind + tx2, ty2) // move to 32x32 diag block A += blk_ind*lda; // A is A(blk_ind + tx2, blk_ind + ty2) // load 32x32 diag block A(blk_ind + 0:31, blk_ind + 0:31) into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 >= partial ) { A = A - tx2 + (partial - 1); // A is A(blk_ind + partial-1, blk_ind + ty2), the bottom-most valid row } #pragma unroll for (int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } else { sA32(tx2, ty2 + j) = MAGMA_C_ZERO; } } if ( tx2 >= partial ) { A = A + tx2 - (partial - 1); // A is A(blk_ind + tx2, blk_ind + ty2) } } else { #pragma unroll for (int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle, // as four 32x8 sections in parallel: // columns 0,4,8,12,16,20,24,28; then 1,5,...,29; then 2,6,...,30, then 3,7,...,31 #pragma unroll for (int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = sA32(tx2, j); } } __syncthreads(); // multiply 32x32 diag block * x // each thread does partial row sA(tx2, ty2*4 : ty2*4 + 3) psum = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to next 32x32 diag block, then repeat steps from first diag block A += half_NB_X + half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + NB/2 + ty2) // load 32x32 diag block A[block + 0:31, block + 0:31] into sA if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for (int j=0; j < half_NB_X; j += 8) { if ( ty2+j + half_NB_X < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } else { sA32(tx2, ty2 + j) = MAGMA_C_ZERO; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for (int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // symmetrize 32x32 diag block, copying lower to upper triangle #pragma unroll for (int j=ty2*4; j < ty2*4 + 4; j++) { if ( j < tx2 ) { sA32(j, tx2) = sA32(tx2, j); } } __syncthreads(); // multiply 32x32 diag block * x psum = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum += sA32(tx2, ty2*4 + j) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial row sums sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to off-diag 32x32 block A -= half_NB_X*lda; // A is A(blk_ind + NB/2 + tx2, blk_ind + ty2) // load 32x32 block of A into sA, // as four 32x8 sections one after another: // columns 0:7, then 8:15, then 16:23, then 24:31 if ( partial ) { if ( tx2 + half_NB_X >= partial ) { A = A - (tx2 + half_NB_X) + (partial - 1); } #pragma unroll for (int j=0; j < half_NB_X; j += 8) { if ( ty2+j < partial ) { sA32(tx2, ty2 + j) = A[j*lda]; } else { sA32(tx2, ty2 + j) = MAGMA_C_ZERO; } } if ( tx2 + half_NB_X >= partial ) { A = A + (tx2 + half_NB_X) - (partial - 1); } } else { #pragma unroll for (int j=0; j < half_NB_X; j += 8) { sA32(tx2, ty2 + j) = A[j*lda]; } } __syncthreads(); // multiply 32x32 block (below diag) psum = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum += sA32(tx2, ty2 + j*8) * sx_blk[j*8 + ty2]; } //__syncthreads(); // no sync needed here // multiply transposed 32x32 block (above diag) psum_t = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum_t += sA32(ty2*4 + j, tx2) * sx_blk[half_NB_X + ty2*4 + j]; } __syncthreads(); // store partial sums for non-transposed 32x32 block sA32(ty2, tx2) = psum; __syncthreads(); // sum up partial row sums, so thread (tx2,1) has total for row (blk_ind + NB/2 + tx2) if ( ty2 == 1 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // store partial sums for transposed 32x32 block sA32(ty2, tx2) = psum_t; __syncthreads(); // sum up partial row sums, so thread (tx2,0) has total for row (blk_ind + tx2) if ( ty2 == 0 ) { total = total + sA32(0, tx2) + sA32(1, tx2) + sA32(2, tx2) + sA32(3, tx2) + sA32(4, tx2) + sA32(5, tx2) + sA32(6, tx2) + sA32(7, tx2); } __syncthreads(); // -------------------- // move to leftmost 64x64 block in block row, and // switch thread offset from (tx2,ty2) 32x8 block to (tx,ty) 64x4 block A -= half_NB_X; // A is A(blk_ind + tx2, blk_ind + ty2) A -= blk_ind*lda; // A is A(blk_ind + tx2, ty2) A -= ty2*lda + tx2; // A is A(blk_ind, 0) A += 4*ty*lda + tx; // A is A(blk_ind + tx, 4*ty) if ( partial && tx >= partial ) { A = A - tx + (partial - 1); // A is A(blk_ind + partial-1, 4*ty), the bottom-most valid row } x -= blk_ind*incx; // x is x(tx) // 16x16 thread block const int tx4 = td % quarter_NB_X; const int ty4 = td / quarter_NB_X; // cycle over blocks jj left of diagonal, in block row blk for (int jj=0; jj < blk; ++jj) { // load 64x1 block x(jj_ind + 0:63) into sx_jj // since this block is left of diagonal, x must have all NB rows if ( ty == 0 ) { sx_jj[tx] = x[jj*NB_X*incx]; } __syncthreads(); for (int k=0; k < 4; k++) { // load 64x16 block of A into rA, 4 elements per thread, // as four 64x4 sections in parallel: // columns 0,4,8,12; then 1,5,9,13; then 2,6,10,14; then 3,7,11,15 // since this block is left of diagonal, it has all NB columns, // and block of x must have all NB rows. #pragma unroll for (int j=0; j < 4; j++) { rA[j] = A[j*lda]; } // 1) multiply 64x16 block A_{blk,jj} * x_jj // each thread does partial row rA(tx + 16*k, ty*4 + 16*k : ty*4 + 3 + 16*k) // 2) multiply transposed 16x64 block A_{blk,jj}^H * x_blk, // storing each product Aji*xi to sA(j,i) #pragma unroll for (int j=0; j < 4; j++) { total += rA[j] * sx_jj[quarter_NB_X*k + ty*4 + j]; // y_blk = A_{blk,jj} * x_jj sA16(ty*4 + j, tx) = rA[j] * sx_blk[tx]; // y_jj = A_{blk,jj}^H * x_blk } __syncthreads(); // do partial row sums for transposed 16x64 result // use 16x16 thread grid (tx4, ty4) instead of 64x4 (tx, ty) // sum sixteen 16x4 sections in parallel: // columns 0,4,8,...,60; then 1,5,...,61; then 2,6,...,62; then 3,7,...,63 psum_t = MAGMA_C_ZERO; #pragma unroll for (int j=0; j < 4; j++) { psum_t += sA16(tx4, ty4*4 + j); } __syncthreads(); // store partial row sums of transposed result, y_jj (locally) psums_t[k] = psum_t; // move right to next 64x16 block A += lda * quarter_NB_X; // A is A(blk_ind + tx#, jj*NB_x + (k+1)*NB_X/4 + 4*ty), # tx or partial } // already at next 64x64 block // A is A(blk_ind + tx#, (jj+1)*NB_x + 4*ty), # tx or partial // store partial row sums of transposed result, y_jj #pragma unroll for (int k=0; k < 4; k++) { sA16(tx4, ty4 + quarter_NB_X*k) = psums_t[k]; } __syncthreads(); // sum up partial row sums of transposed result, y_jj, and store final total to workspace // thread (tx4,ty4) where ty4 < 4 sums row tx4 + ty4*16 // since this is the transposed block above the diagonal, it must have all NB rows if ( ty4 < 4 ) { int ty4_nb4 = ty4*quarter_NB_X; psum_t = sA16(tx4, 0 + ty4_nb4) + sA16(tx4, 1 + ty4_nb4) + sA16(tx4, 2 + ty4_nb4) + sA16(tx4, 3 + ty4_nb4) + sA16(tx4, 4 + ty4_nb4) + sA16(tx4, 5 + ty4_nb4) + sA16(tx4, 6 + ty4_nb4) + sA16(tx4, 7 + ty4_nb4) + sA16(tx4, 8 + ty4_nb4) + sA16(tx4, 9 + ty4_nb4) + sA16(tx4, 10 + ty4_nb4) + sA16(tx4, 11 + ty4_nb4) + sA16(tx4, 12 + ty4_nb4) + sA16(tx4, 13 + ty4_nb4) + sA16(tx4, 14 + ty4_nb4) + sA16(tx4, 15 + ty4_nb4); work[jj*NB_X + tx4 + ty4_nb4] = psum_t; // store at work( jj*NB_X + tx4 + ty4*16, blk ) } __syncthreads(); } // store row sums sA16(ty, tx) = total; __syncthreads(); // sum up final total, y_blk, for row tx if ( ty == 0 && (partial == 0 || tx < partial) ) { total = sA16(0, tx) + sA16(1, tx) + sA16(2, tx) + sA16(3, tx); work[blk*NB_X + tx] = total; // store at work( blk*NB_X + tx, blk ) } #endif /* PRECISION_[sdc] || (__CUDA_ARCH__ >= 200) */ } // end csymv_kernel_L /***************************************************************************//** Lower case, sum up final results Each block sums one block row; each thread sums one row. On input (for 3 blocks): [ (A11*x1) (A21^H*x2) (A31^H*x3) ] work = [ --- (A21*x1 + A22*x2) (A32^H*x3) ] [ --- --- (A31*x1 + A32*x2 + A33*x3) ] On output: [ (A11*x1) + (A21^H*x2) + (A31^H*x3) ] y = alpha*[ (A21*x1 + A22*x2) + (A32^H*x3) ] + beta*y [ (A21*x1 + A22*x2 + A33*x3) ] *******************************************************************************/ __global__ void csymv_kernel_L_sum( int n, magmaFloatComplex alpha, int lda, magmaFloatComplex beta, magmaFloatComplex * __restrict__ y, int incy, magmaFloatComplex const * __restrict__ work ) { int tx = threadIdx.x; int blk = blockIdx.x; int blk_ind = blk * NB_X; int ind = blk_ind + tx; int blocks = gridDim.x; // Don't write outside [0, ..., n) if ( ind < n ) { work += ind + blk*lda; magmaFloatComplex Ax = MAGMA_C_ZERO; for (int j = blk; j < blocks; ++j) { Ax += work[0]; work += lda; } y[ind * incy] = beta*y[ind * incy] + alpha*Ax; } } /***************************************************************************//** Purpose ------- magmablas_csymv_work performs the matrix-vector operation: y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n complex symmetric matrix. Arguments ---------- @param[in] uplo magma_uplo_t. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: - = MagmaUpper: Only the upper triangular part of A is to be referenced. - = MagmaLower: Only the lower triangular part of A is to be referenced. @param[in] n INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. @param[in] alpha COMPLEX. On entry, ALPHA specifies the scalar alpha. @param[in] dA COMPLEX array of DIMENSION ( LDDA, n ). Before entry with UPLO = MagmaUpper, the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = MagmaLower, the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. @param[in] ldda INTEGER. On entry, LDDA specifies the first dimension of A as declared in the calling (sub) program. LDDA must be at least max( 1, n ). It is recommended that ldda is multiple of 16. Otherwise performance would be deteriorated as the memory accesses would not be fully coalescent. @param[in] dx COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. @param[in] incx INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. @param[in] beta COMPLEX. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. @param[in,out] dy COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. @param[in] incy INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. @param[in] dwork (workspace) COMPLEX array on the GPU, dimension (MAX(1, LWORK)), @param[in] lwork INTEGER. The dimension of the array DWORK. LWORK >= LDDA * ceil( N / NB_X ), where NB_X = 64. @param[in] queue magma_queue_t. Queue to execute in. MAGMA implements csymv through two steps: 1) perform the multiplication in each thread block and put the intermediate value in dwork. 2) sum the intermediate values and store the final result in y. magamblas_csymv_work requires users to provide a workspace, while magmablas_csymv is a wrapper routine allocating the workspace inside the routine and provides the same interface as cublas. If users need to call csymv frequently, we suggest using magmablas_csymv_work instead of magmablas_csymv. As the overhead to allocate and free in device memory in magmablas_csymv would hurt performance. Our tests show that this penalty is about 10 Gflop/s when the matrix size is around 10000. @ingroup magma_symv *******************************************************************************/ extern "C" magma_int_t magmablas_csymv_work( magma_uplo_t uplo, magma_int_t n, magmaFloatComplex alpha, magmaFloatComplex_const_ptr dA, magma_int_t ldda, magmaFloatComplex_const_ptr dx, magma_int_t incx, magmaFloatComplex beta, magmaFloatComplex_ptr dy, magma_int_t incy, magmaFloatComplex_ptr dwork, magma_int_t lwork, magma_queue_t queue ) { #if defined(PRECISION_z) // z precision requires CUDA ARCH 2.x; call CUBLAS version instead. magma_int_t arch = magma_getdevice_arch(); if ( arch < 200 ) { //magma_csymv( uplo, n, alpha, dA, ldda, dx, incx, beta, dy, incy ); //return MAGMA_SUCCESS; fprintf(stderr, "%s: %s\n", __func__, "not supported on CUDA ARCH 1.x"); return MAGMA_ERR_NOT_SUPPORTED; } #endif // -------------------- // [sdc] precisions, or z precision with CUDA ARCH 2.x bool upper = (uplo == MagmaUpper); magma_int_t blocks = magma_ceildiv( n, NB_X ); magma_int_t lwmin = ldda*blocks; /* * Test the input parameters. */ magma_int_t info = 0; if ((! upper) && (uplo != MagmaLower)) { info = -1; } else if ( n < 0 ) { info = -2; } else if ( ldda < max(1, n) ) { info = -5; } else if ( incx == 0 ) { info = -7; } else if ( incy == 0 ) { info = -10; } else if ( lwork < lwmin ) { info = -12; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( (n == 0) || ( MAGMA_C_EQUAL(alpha, MAGMA_C_ZERO) && MAGMA_C_EQUAL(beta, MAGMA_C_ONE) ) ) return info; dim3 grid( blocks, 1, 1 ); dim3 threads( NB_X, NB_Y, 1 ); dim3 threads_sum( NB_X, 1, 1 ); if ( upper ) { csymv_kernel_U<<< grid, threads, 0, queue->cuda_stream() >>> (n, dA, ldda, dx, incx, dwork); csymv_kernel_U_sum<<< grid, threads_sum, 0, queue->cuda_stream() >>> (n, alpha, ldda, beta, dy, incy, dwork); } else { csymv_kernel_L<<< grid, threads, 0, queue->cuda_stream() >>> (n, dA, ldda, dx, incx, dwork); csymv_kernel_L_sum<<< grid, threads_sum, 0, queue->cuda_stream() >>> (n, alpha, ldda, beta, dy, incy, dwork); } return info; } // end magmablas_csymv_work /***************************************************************************//** Purpose ------- magmablas_csymv performs the matrix-vector operation: y := alpha*A*x + beta*y, where alpha and beta are scalars, x and y are n element vectors and A is an n by n complex symmetric matrix. Arguments ---------- @param[in] uplo magma_uplo_t. On entry, UPLO specifies whether the upper or lower triangular part of the array A is to be referenced as follows: - = MagmaUpper: Only the upper triangular part of A is to be referenced. - = MagmaLower: Only the lower triangular part of A is to be referenced. @param[in] n INTEGER. On entry, N specifies the order of the matrix A. N must be at least zero. @param[in] alpha COMPLEX. On entry, ALPHA specifies the scalar alpha. @param[in] dA COMPLEX array of DIMENSION ( LDDA, n ). Before entry with UPLO = MagmaUpper, the leading n by n upper triangular part of the array A must contain the upper triangular part of the symmetric matrix and the strictly lower triangular part of A is not referenced. Before entry with UPLO = MagmaLower, the leading n by n lower triangular part of the array A must contain the lower triangular part of the symmetric matrix and the strictly upper triangular part of A is not referenced. Note that the imaginary parts of the diagonal elements need not be set and are assumed to be zero. @param[in] ldda INTEGER. On entry, LDDA specifies the first dimension of A as declared in the calling (sub) program. LDDA must be at least max( 1, n ). It is recommended that ldda is multiple of 16. Otherwise performance would be deteriorated as the memory accesses would not be fully coalescent. @param[in] dx COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCX ) ). Before entry, the incremented array X must contain the n element vector x. @param[in] incx INTEGER. On entry, INCX specifies the increment for the elements of X. INCX must not be zero. @param[in] beta COMPLEX. On entry, BETA specifies the scalar beta. When BETA is supplied as zero then Y need not be set on input. @param[in,out] dy COMPLEX array of dimension at least ( 1 + ( n - 1 )*abs( INCY ) ). Before entry, the incremented array Y must contain the n element vector y. On exit, Y is overwritten by the updated vector y. @param[in] incy INTEGER. On entry, INCY specifies the increment for the elements of Y. INCY must not be zero. @param[in] queue magma_queue_t Queue to execute in. @ingroup magma_symv *******************************************************************************/ extern "C" magma_int_t magmablas_csymv( magma_uplo_t uplo, magma_int_t n, magmaFloatComplex alpha, magmaFloatComplex_const_ptr dA, magma_int_t ldda, magmaFloatComplex_const_ptr dx, magma_int_t incx, magmaFloatComplex beta, magmaFloatComplex_ptr dy, magma_int_t incy, magma_queue_t queue ) { #if defined(PRECISION_z) // z precision requires CUDA ARCH 2.x; no CUBLAS version of csymv. magma_int_t arch = magma_getdevice_arch(); if ( arch < 200 ) { //magma_csymv( uplo, n, alpha, dA, ldda, dx, incx, beta, dy, incy ); //return MAGMA_SUCCESS; fprintf(stderr, "%s: %s\n", __func__, "not supported on CUDA ARCH 1.x"); return MAGMA_ERR_NOT_SUPPORTED; } #endif // -------------------- // [sdc] precisions, or z precision with CUDA ARCH 2.x bool upper = (uplo == MagmaUpper); /* * Test the input parameters. */ magma_int_t info = 0; if ((! upper) && (uplo != MagmaLower)) { info = -1; } else if ( n < 0 ) { info = -2; } else if ( ldda < max(1, n) ) { info = -5; } else if ( incx == 0 ) { info = -7; } else if ( incy == 0 ) { info = -10; } if (info != 0) { magma_xerbla( __func__, -(info) ); return info; } /* * Quick return if possible. */ if ( (n == 0) || ( MAGMA_C_EQUAL(alpha, MAGMA_C_ZERO) && MAGMA_C_EQUAL(beta, MAGMA_C_ONE) ) ) return info; magmaFloatComplex_ptr dwork; magma_int_t blocks = magma_ceildiv( n, NB_X ); magma_int_t lwork = ldda*blocks; magma_cmalloc( &dwork, lwork ); if ( dwork == NULL ) { info = MAGMA_ERR_DEVICE_ALLOC; magma_xerbla( __func__, -(info) ); return info; } magmablas_csymv_work( uplo, n, alpha, dA, ldda, dx, incx, beta, dy, incy, dwork, lwork, queue ); magma_free( dwork ); return info; } // end magmablas_csymv
7219f9f9ee344bf24b5a9bc9268055a10eb3f996.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <stdlib.h> #include <hip/hip_runtime.h> #include <assert.h> #include <math.h> //Reading array A from input file inp.txt typedef struct { int *array; size_t used; size_t size; } Array; void initArray(Array *a, size_t initialSize) { a->array = (int*) malloc(initialSize * sizeof(int)); a->used = 0; a->size = initialSize; } void insertArray(Array *a, int element) { if (a->used == a->size) { a->size += 1; a->array =(int*) realloc(a->array, a->size * sizeof(int)); } a->array[a->used++] = element; } Array initArrayA(){ FILE *fp; char str[50000]; Array a; initArray(&a, 1); /* opening file for reading */ fp = fopen("inp.txt" , "r"); if(fp == NULL) { printf("%s","error"); return a; } while( fgets (str, 50000, fp)!=NULL ) { /* writing content to stdout */ // printf("%s\n", str); char* token; char* rest = str; while ((token = strtok_r(rest, " , ", &rest))) insertArray(&a, atoi(token)); } fclose(fp); return a; } //Asserts for GPU errors #define gpuErrorCheck(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(hipError_t code, const char *file, int line, bool abort=true) { if (code != hipSuccess) { printf("GPUassert: %s %s %d\n", hipGetErrorString(code), file, line); if (abort) exit(code); } } __global__ void global_count_range_bins_kernel(int * d_out, int * d_in, int size) { int myId = threadIdx.x + blockDim.x * blockIdx.x; // stride is the total number of threads in the grid // Using stride increases the performance and benefits with scalability & thread reusage int stride = blockDim.x * gridDim.x; // do counts in global mem for (; myId < size; myId += stride) { atomicAdd(&(d_out[d_in[myId]/100]), 1); __syncthreads(); // make sure all adds at one stage are done! } } __global__ void shmem_count_range_bins_kernel(int * d_out, int * d_in, int size) { extern __shared__ int sdata[]; int myId = threadIdx.x + blockDim.x * blockIdx.x; int tid = threadIdx.x; // load shared mem from global mem sdata[tid] = 0; __syncthreads(); // stride is the total number of threads in the grid // Using stride increases the performance and benefits with scalability & thread reusage int stride = blockDim.x * gridDim.x; // do counts in shared mem for (; myId < size; myId += stride) { atomicAdd(&(sdata[d_in[myId]/100]), 1); __syncthreads(); // make sure all adds at one stage are done! } // assumes that threads per block size is atleast 10 atomicAdd(&d_out[tid], sdata[tid]); } //kernel to perform parallel prefix sum //assumes only 1 block (1 block can be utilized since we have only 10 elements) __global__ void prefixsum(int *d_out, int * d_in, int size) { extern __shared__ int sh_mem[]; int tid = threadIdx.x; int myId = blockIdx.x * blockDim.x + threadIdx.x; sh_mem[tid] = d_in[myId]; __syncthreads(); if (myId < size) { for (int d = 1; d < blockDim.x; d *=2) { if (tid >= d) { sh_mem[tid] += sh_mem[tid - d]; } __syncthreads(); } } d_out[myId] = sh_mem[tid]; } //Function to call corresponding kernel based on memory usage void count_bins(int * d_out, int * d_in, int size, bool usesSharedMemory) { const int maxThreadsPerBlock = 512; int threads = maxThreadsPerBlock; // handles non power of 2 inputs int blocks = ceil(float(size) / float(maxThreadsPerBlock)); if (usesSharedMemory) { //fprintf(q2a, "shared kernel in count \n"); hipLaunchKernelGGL(( shmem_count_range_bins_kernel), dim3(blocks), dim3(threads), threads * sizeof(int), 0, d_out, d_in, size); } else { //fprintf(q2a, "global kernel in count \n"); hipLaunchKernelGGL(( global_count_range_bins_kernel), dim3(blocks), dim3(threads), 0, 0, d_out, d_in, size); gpuErrorCheck( hipPeekAtLastError() ); gpuErrorCheck( hipDeviceSynchronize() ); } } int main(int argc, char **argv) { FILE *q2a; FILE *q2b; FILE *q2c; q2a = fopen("q2a.txt", "w"); q2b = fopen("q2b.txt", "w"); q2c = fopen("q2c.txt", "w"); int deviceCount; hipGetDeviceCount(&deviceCount); if (deviceCount == 0) { fprintf(q2a, "error: no devices supporting CUDA.\n"); exit(EXIT_FAILURE); } int dev = 0; hipSetDevice(dev); hipDeviceProp_t devProps; if (hipGetDeviceProperties(&devProps, dev) == 0) { fprintf(q2a, "Using device %d:\n", dev); fprintf(q2a, "%s; global mem: %dB; compute v%d.%d; clock: %d kHz\n", devProps.name, (int)devProps.totalGlobalMem, (int)devProps.major, (int)devProps.minor, (int)devProps.clockRate); } // generate the input array on the host Array A = initArrayA(); int * h_in = A.array; const int ARRAY_SIZE = A.size; const int ARRAY_BYTES = A.size * sizeof(int); fprintf(q2a, "Array size is %d\n", ARRAY_SIZE); // declare GPU memory pointers int * d_in, * d_out, * s_in, * s_out, *prefix_out, *prefix_in;; // allocate GPU memory hipMalloc((void **) &d_in, ARRAY_BYTES); hipMalloc((void **) &s_in, ARRAY_BYTES); hipMalloc((void **) &d_out, 10*sizeof(int)); hipMalloc((void **) &s_out, 10*sizeof(int)); // allocate memory for prefix sum, it has only 10 buckets hipMalloc((void **) &prefix_out, 10*sizeof(int)); hipMalloc((void **) &prefix_in, 10*sizeof(int)); hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); float elapsedTime; //Problem 2a - Using Global Memory to get counts fprintf(q2a,"Using Global Memory to get counts\n"); //fprintf(q2a, "Running global count\n"); // transfer the input array to the GPU hipMemcpy(d_in, h_in, ARRAY_BYTES, hipMemcpyHostToDevice); hipEventRecord(start, 0); count_bins(d_out, d_in, ARRAY_SIZE, false); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&elapsedTime, start, stop); fprintf(q2a, "Using Global memory - average time elapsed: %f\n", elapsedTime); // copy back the counts from GPU int b[10]; hipMemcpy(&b, d_out, 10*sizeof(int), hipMemcpyDeviceToHost); for(int i = 0; i < 10; i++) { fprintf(q2a, "Global Memory counts returned by device B[%d]: %d\n", i, b[i]); } //Problem 2b - Using Shared Memory to get counts // transfer the input array to the GPU hipMemcpy(s_in, h_in, ARRAY_BYTES, hipMemcpyHostToDevice); fprintf(q2b, "Array size is %d\n", ARRAY_SIZE); fprintf(q2b,"Using Shared Memory to get counts\n"); //fprintf(q2b, "Running shared count\n"); hipEventRecord(start, 0); count_bins(s_out, s_in, ARRAY_SIZE, false); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&elapsedTime, start, stop); fprintf(q2b, "Using Shared memory - average time elapsed: %f\n", elapsedTime); // copy back the counts from GPU int s[10]; hipMemcpy(&s, s_out, 10*sizeof(int), hipMemcpyDeviceToHost); for(int i = 0; i < 10; i++) { fprintf(q2b, "Shared Memory counts returned by device B[%d]: %d\n", i, s[i]); } // Problem 2c - Using Parallel Prefix SUM to calculate C fprintf(q2c, "Array size is %d\n", ARRAY_SIZE); // transfer the input scan array to the GPU hipMemcpy(prefix_in, b, 10 * sizeof(int), hipMemcpyHostToDevice); fprintf(q2c, "Running Parallel Prefix Sum\n"); hipEventRecord(start, 0); hipLaunchKernelGGL(( prefixsum), dim3(1), dim3(10), 10 * sizeof(int), 0, prefix_out, prefix_in, 10); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&elapsedTime, start, stop); fprintf(q2c, "Using Parallel Prefix Sum - average time elapsed: %f\n", elapsedTime); gpuErrorCheck( hipPeekAtLastError() ); gpuErrorCheck( hipDeviceSynchronize() ); // copy back the counts from GPU int c[10]; hipMemcpy(&c, prefix_out, 10*sizeof(int), hipMemcpyDeviceToHost); for(int i = 0; i < 10; i++) { fprintf(q2c, "Parallel Prefix sum returned by device: %d\n", c[i]); } // free GPU memory allocation hipFree(d_in); hipFree(d_out); hipFree(prefix_out); hipFree(prefix_in); hipFree(s_in); hipFree(s_out); return 0; } // Reference: https://developer.nvidia.com/blog/gpu-pro-tip-fast-histograms-using-shared-atomics-maxwell
7219f9f9ee344bf24b5a9bc9268055a10eb3f996.cu
#include <stdio.h> #include <stdlib.h> #include <cuda_runtime.h> #include <assert.h> #include <math.h> //Reading array A from input file inp.txt typedef struct { int *array; size_t used; size_t size; } Array; void initArray(Array *a, size_t initialSize) { a->array = (int*) malloc(initialSize * sizeof(int)); a->used = 0; a->size = initialSize; } void insertArray(Array *a, int element) { if (a->used == a->size) { a->size += 1; a->array =(int*) realloc(a->array, a->size * sizeof(int)); } a->array[a->used++] = element; } Array initArrayA(){ FILE *fp; char str[50000]; Array a; initArray(&a, 1); /* opening file for reading */ fp = fopen("inp.txt" , "r"); if(fp == NULL) { printf("%s","error"); return a; } while( fgets (str, 50000, fp)!=NULL ) { /* writing content to stdout */ // printf("%s\n", str); char* token; char* rest = str; while ((token = strtok_r(rest, " , ", &rest))) insertArray(&a, atoi(token)); } fclose(fp); return a; } //Asserts for GPU errors #define gpuErrorCheck(ans) { gpuAssert((ans), __FILE__, __LINE__); } inline void gpuAssert(cudaError_t code, const char *file, int line, bool abort=true) { if (code != cudaSuccess) { printf("GPUassert: %s %s %d\n", cudaGetErrorString(code), file, line); if (abort) exit(code); } } __global__ void global_count_range_bins_kernel(int * d_out, int * d_in, int size) { int myId = threadIdx.x + blockDim.x * blockIdx.x; // stride is the total number of threads in the grid // Using stride increases the performance and benefits with scalability & thread reusage int stride = blockDim.x * gridDim.x; // do counts in global mem for (; myId < size; myId += stride) { atomicAdd(&(d_out[d_in[myId]/100]), 1); __syncthreads(); // make sure all adds at one stage are done! } } __global__ void shmem_count_range_bins_kernel(int * d_out, int * d_in, int size) { extern __shared__ int sdata[]; int myId = threadIdx.x + blockDim.x * blockIdx.x; int tid = threadIdx.x; // load shared mem from global mem sdata[tid] = 0; __syncthreads(); // stride is the total number of threads in the grid // Using stride increases the performance and benefits with scalability & thread reusage int stride = blockDim.x * gridDim.x; // do counts in shared mem for (; myId < size; myId += stride) { atomicAdd(&(sdata[d_in[myId]/100]), 1); __syncthreads(); // make sure all adds at one stage are done! } // assumes that threads per block size is atleast 10 atomicAdd(&d_out[tid], sdata[tid]); } //kernel to perform parallel prefix sum //assumes only 1 block (1 block can be utilized since we have only 10 elements) __global__ void prefixsum(int *d_out, int * d_in, int size) { extern __shared__ int sh_mem[]; int tid = threadIdx.x; int myId = blockIdx.x * blockDim.x + threadIdx.x; sh_mem[tid] = d_in[myId]; __syncthreads(); if (myId < size) { for (int d = 1; d < blockDim.x; d *=2) { if (tid >= d) { sh_mem[tid] += sh_mem[tid - d]; } __syncthreads(); } } d_out[myId] = sh_mem[tid]; } //Function to call corresponding kernel based on memory usage void count_bins(int * d_out, int * d_in, int size, bool usesSharedMemory) { const int maxThreadsPerBlock = 512; int threads = maxThreadsPerBlock; // handles non power of 2 inputs int blocks = ceil(float(size) / float(maxThreadsPerBlock)); if (usesSharedMemory) { //fprintf(q2a, "shared kernel in count \n"); shmem_count_range_bins_kernel<<<blocks, threads, threads * sizeof(int)>>> (d_out, d_in, size); } else { //fprintf(q2a, "global kernel in count \n"); global_count_range_bins_kernel<<<blocks, threads>>>(d_out, d_in, size); gpuErrorCheck( cudaPeekAtLastError() ); gpuErrorCheck( cudaDeviceSynchronize() ); } } int main(int argc, char **argv) { FILE *q2a; FILE *q2b; FILE *q2c; q2a = fopen("q2a.txt", "w"); q2b = fopen("q2b.txt", "w"); q2c = fopen("q2c.txt", "w"); int deviceCount; cudaGetDeviceCount(&deviceCount); if (deviceCount == 0) { fprintf(q2a, "error: no devices supporting CUDA.\n"); exit(EXIT_FAILURE); } int dev = 0; cudaSetDevice(dev); cudaDeviceProp devProps; if (cudaGetDeviceProperties(&devProps, dev) == 0) { fprintf(q2a, "Using device %d:\n", dev); fprintf(q2a, "%s; global mem: %dB; compute v%d.%d; clock: %d kHz\n", devProps.name, (int)devProps.totalGlobalMem, (int)devProps.major, (int)devProps.minor, (int)devProps.clockRate); } // generate the input array on the host Array A = initArrayA(); int * h_in = A.array; const int ARRAY_SIZE = A.size; const int ARRAY_BYTES = A.size * sizeof(int); fprintf(q2a, "Array size is %d\n", ARRAY_SIZE); // declare GPU memory pointers int * d_in, * d_out, * s_in, * s_out, *prefix_out, *prefix_in;; // allocate GPU memory cudaMalloc((void **) &d_in, ARRAY_BYTES); cudaMalloc((void **) &s_in, ARRAY_BYTES); cudaMalloc((void **) &d_out, 10*sizeof(int)); cudaMalloc((void **) &s_out, 10*sizeof(int)); // allocate memory for prefix sum, it has only 10 buckets cudaMalloc((void **) &prefix_out, 10*sizeof(int)); cudaMalloc((void **) &prefix_in, 10*sizeof(int)); cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); float elapsedTime; //Problem 2a - Using Global Memory to get counts fprintf(q2a,"Using Global Memory to get counts\n"); //fprintf(q2a, "Running global count\n"); // transfer the input array to the GPU cudaMemcpy(d_in, h_in, ARRAY_BYTES, cudaMemcpyHostToDevice); cudaEventRecord(start, 0); count_bins(d_out, d_in, ARRAY_SIZE, false); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsedTime, start, stop); fprintf(q2a, "Using Global memory - average time elapsed: %f\n", elapsedTime); // copy back the counts from GPU int b[10]; cudaMemcpy(&b, d_out, 10*sizeof(int), cudaMemcpyDeviceToHost); for(int i = 0; i < 10; i++) { fprintf(q2a, "Global Memory counts returned by device B[%d]: %d\n", i, b[i]); } //Problem 2b - Using Shared Memory to get counts // transfer the input array to the GPU cudaMemcpy(s_in, h_in, ARRAY_BYTES, cudaMemcpyHostToDevice); fprintf(q2b, "Array size is %d\n", ARRAY_SIZE); fprintf(q2b,"Using Shared Memory to get counts\n"); //fprintf(q2b, "Running shared count\n"); cudaEventRecord(start, 0); count_bins(s_out, s_in, ARRAY_SIZE, false); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsedTime, start, stop); fprintf(q2b, "Using Shared memory - average time elapsed: %f\n", elapsedTime); // copy back the counts from GPU int s[10]; cudaMemcpy(&s, s_out, 10*sizeof(int), cudaMemcpyDeviceToHost); for(int i = 0; i < 10; i++) { fprintf(q2b, "Shared Memory counts returned by device B[%d]: %d\n", i, s[i]); } // Problem 2c - Using Parallel Prefix SUM to calculate C fprintf(q2c, "Array size is %d\n", ARRAY_SIZE); // transfer the input scan array to the GPU cudaMemcpy(prefix_in, b, 10 * sizeof(int), cudaMemcpyHostToDevice); fprintf(q2c, "Running Parallel Prefix Sum\n"); cudaEventRecord(start, 0); prefixsum<<<1, 10, 10 * sizeof(int)>>>(prefix_out, prefix_in, 10); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&elapsedTime, start, stop); fprintf(q2c, "Using Parallel Prefix Sum - average time elapsed: %f\n", elapsedTime); gpuErrorCheck( cudaPeekAtLastError() ); gpuErrorCheck( cudaDeviceSynchronize() ); // copy back the counts from GPU int c[10]; cudaMemcpy(&c, prefix_out, 10*sizeof(int), cudaMemcpyDeviceToHost); for(int i = 0; i < 10; i++) { fprintf(q2c, "Parallel Prefix sum returned by device: %d\n", c[i]); } // free GPU memory allocation cudaFree(d_in); cudaFree(d_out); cudaFree(prefix_out); cudaFree(prefix_in); cudaFree(s_in); cudaFree(s_out); return 0; } // Reference: https://developer.nvidia.com/blog/gpu-pro-tip-fast-histograms-using-shared-atomics-maxwell
ce086ced730d0b4472b356fdb9bc6352a8700a3c.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <helper_cuda.h> #include <iostream> __global__ void emptyKernel() {} int main() { const int N = 100000; float time, total = 0.f; hipEvent_t start, stop; hipEventCreate(&start); hipEventCreate(&stop); for (int j = 1; j <= 4096; j *= 2) { for (int k = 1; k <= 1024; k *= 2) { for (int i = 0; i < N; i++) { hipEventRecord(start, 0); hipLaunchKernelGGL(( emptyKernel), dim3(1), dim3(1), 0, 0, ); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&time, start, stop); total = total + time; } std::cout << "Kernel: " << j << "X" << k << "\tlaunch overhead: " << total / N * 1000 << " us\n"; total = 0.f; } } total = 0.f; void* dst = nullptr; void* src = nullptr; for (int i = 0; i < N; i++) { hipEventRecord(start, 0); checkCudaErrors(hipMemcpy(dst, src, 0, hipMemcpyDefault)); hipEventRecord(stop, 0); hipEventSynchronize(stop); hipEventElapsedTime(&time, start, stop); total = total + time; } std::cout << "\nData transfer overhead: " << total / N * 1000 << " us\n"; return 0; }
ce086ced730d0b4472b356fdb9bc6352a8700a3c.cu
#include <helper_cuda.h> #include <iostream> __global__ void emptyKernel() {} int main() { const int N = 100000; float time, total = 0.f; cudaEvent_t start, stop; cudaEventCreate(&start); cudaEventCreate(&stop); for (int j = 1; j <= 4096; j *= 2) { for (int k = 1; k <= 1024; k *= 2) { for (int i = 0; i < N; i++) { cudaEventRecord(start, 0); emptyKernel<<<1, 1>>>(); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&time, start, stop); total = total + time; } std::cout << "Kernel: " << j << "X" << k << "\tlaunch overhead: " << total / N * 1000 << " us\n"; total = 0.f; } } total = 0.f; void* dst = nullptr; void* src = nullptr; for (int i = 0; i < N; i++) { cudaEventRecord(start, 0); checkCudaErrors(cudaMemcpy(dst, src, 0, cudaMemcpyDefault)); cudaEventRecord(stop, 0); cudaEventSynchronize(stop); cudaEventElapsedTime(&time, start, stop); total = total + time; } std::cout << "\nData transfer overhead: " << total / N * 1000 << " us\n"; return 0; }
74bea52a368644a1c1fef6df5a594aea027fda73.hip
// !!! This is a file automatically generated by hipify!!! #include <stdio.h> #include <string.h> #include <stdarg.h> #ifdef UNIX #include <stdint.h> #include <unistd.h> #endif #ifndef NOMATLAB #include "mex.h" #endif // CUDA #include "hip/hip_runtime.h" #include "cudaCommon.h" #include "cudaGradientKernels.h" #include "cudaSourceScalarPotential.h" #define BLOCKDIMX 18 #define BLOCKDIMY 18 template <geometryType_t coords> __global__ void cukern_computeScalarGradient3D(double *phi, double *f_x, double *f_y, double *f_z, int3 arraysize); template <geometryType_t coords> __global__ void cukern_computeScalarGradient2D(double *phi, double *fx, double *fy, int3 arraysize); __global__ void cukern_applyPotentialGradient3D(double *fluid, double *fx, double *fy, double *fz, unsigned int arrayNumel); __global__ void cukern_applyPotentialGradient2D(double *fluid, double *fx, double *fy, unsigned int arrayNumel); __constant__ __device__ double devLambda[9]; #define LAMX devLambda[0] #define LAMY devLambda[1] #define LAMZ devLambda[2] // Define: F = -beta * rho * grad(phi) // rho_g = density for full effect of gravity // rho_c = minimum density to feel gravity at all // beta = { rho_g < rho : 1 } // { rho_c < rho < rho_g : [(rho-rho_c)/(rho_rho_g-rho_c)]^2 } // { rho < rho_c : 0 } // This provides a continuous (though not differentiable at rho = rho_g) way to surpress gravitation of the background fluid // The original process of cutting gravity off below a critical density a few times the minimum // density is believed to cause "blowups" at the inner edge of circular flow profiles due to being // discontinuous. If even smoothness is insufficient and smooth differentiability is required, // a more-times-continuous profile can be constructed, but let's not go there unless forced. // Density below which we force gravity effects to zero #define RHOMIN devLambda[3] #define RHOGRAV devLambda[4] // 1 / (rho_g - rho_c) #define G1 devLambda[5] // rho_c / (rho_g - rho_c) #define G2 devLambda[6] #define RINNER devLambda[7] #define DELTAR devLambda[8] __constant__ __device__ unsigned int devSlabdim[3]; #ifdef STANDALONE_MEX_FUNCTION int fetchMinDensity(mxArray *mxFluids, int fluidNum, double *rhoMin) { int status = SUCCESSFUL; mxArray *flprop = mxGetProperty(mxFluids, fluidNum, "MINMASS"); if(flprop != NULL) { rhoMin[0] = *((double *)mxGetPr(flprop)); } else { PRINT_FAULT_HEADER; printf("Unable to access fluid(%i).MINMASS property.\n", fluidNum); PRINT_FAULT_FOOTER; status = ERROR_NULL_POINTER; } return status; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs!=4) || (nlhs != 0)) mexErrMsgTxt("Wrong number of arguments: need cudaApplyScalarPotential(FluidManager, phi, GeometryManager, [dt, rho_nograv, rho_fullgrav])\n"); if(CHECK_CUDA_ERROR("entering cudaSourceScalarPotential") != SUCCESSFUL) { DROP_MEX_ERROR("Failed upon entry to cudaSourceScalarPotential."); } // Get source array info and create destination arrays MGArray fluid[5]; MGArray phi; int worked = MGA_accessMatlabArrays(prhs, 1, 1, &phi); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) { DROP_MEX_ERROR("Failed to access input arrays."); } // Each partition uses the same common parameters GeometryParams geom = accessMatlabGeometryClass(prhs[2]); // FIXME check for fail & return int ne = mxGetNumberOfElements(prhs[3]); if(ne != 3) { printf("Input argument 3 has %i arguments, not three. Require precisely 3: [dt rho_nog rho_fullg]\n", ne); DROP_MEX_ERROR("Crashing."); } double *sp = mxGetPr(prhs[3]); double dt = sp[0]; /* dt */ double rhoMinimum = sp[1]; /* minimum rho, rho_c */ double rhoFull = sp[2]; /* rho_g */ int numFluids = mxGetNumberOfElements(prhs[0]); int fluidct; for(fluidct = 0; fluidct < numFluids; fluidct++) { worked = MGA_accessFluidCanister(prhs[0], fluidct, &fluid[0]); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; mxArray *flprop = mxGetProperty(prhs[0], fluidct, "MINMASS"); if(flprop != NULL) { rhoMinimum = *((double *)mxGetPr(flprop)); } else { worked = ERROR_NULL_POINTER; break; } worked = sourcefunction_ScalarPotential(&fluid[0], &phi, dt, geom, rhoMinimum, rhoFull); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; } GridFluid fluids[numFluids]; for(fluidct = 0; fluidct < numFluids; fluidct++) { worked = MGA_accessFluidCanister(prhs[0], fluidct, &fluids[fluidct].data[0]); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; //fluids[fluidct].thermo = accessMatlabThermoDetails(mxGetProperty(prhs[0], fluidct, "thermoDetails")); worked = fetchMinDensity((mxArray *)prhs[0], fluidct, &fluids[fluidct].rhoMin); } if(worked != SUCCESSFUL) { DROP_MEX_ERROR("cudaSourceScalarPotential failed"); } } #endif int sourcefunction_ScalarPotential(MGArray *fluid, MGArray *phi, double dt, GeometryParams geom, double minRho, double rhoFullGravity) { double *dx = &geom.h[0]; dim3 gridsize, blocksize; int3 arraysize; int i, sub[6]; int worked; double lambda[9]; lambda[0] = dt/(2.0*dx[0]); lambda[1] = dt/(2.0*dx[1]); lambda[2] = dt/(2.0*dx[2]); lambda[3] = minRho; /* minimum rho, rho_c */ lambda[4] = rhoFullGravity; /* rho_g */ lambda[5] = 1.0/(lambda[4] - lambda[3]); /* 1/(rho_g - rho_c) */ lambda[6] = lambda[3]*lambda[5]; lambda[7] = geom.Rinner; lambda[8] = dx[1]; for(i = 0; i < fluid->nGPUs; i++) { hipSetDevice(fluid->deviceID[i]); hipMemcpyToSymbol((const void *)devLambda, lambda, 9*sizeof(double), 0, hipMemcpyHostToDevice); unsigned int sd[3]; sd[0] = (unsigned int)(fluid->slabPitch[i] / 8); hipMemcpyToSymbol((const void *)devSlabdim, sd, 1*sizeof(int), 0, hipMemcpyHostToDevice); worked = CHECK_CUDA_ERROR("hipMemcpyToSymbol"); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; } if(worked != SUCCESSFUL) return worked; int isThreeD = (fluid->dim[2] > 1); MGArray gradientStorage; worked = MGA_allocSlab(fluid, &gradientStorage, 3); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) return worked; worked = computeCentralGradient(phi, &gradientStorage, geom, 2, dt); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) return worked; double *gs; // Iterate over all partitions, and here we GO! for(i = 0; i < fluid->nGPUs; i++) { hipSetDevice(fluid->deviceID[i]); calcPartitionExtent(fluid, i, sub); arraysize.x = sub[3]; arraysize.y = sub[4]; arraysize.z = sub[5]; blocksize = makeDim3(BLOCKDIMX, BLOCKDIMY, 1); gridsize.x = arraysize.x / (blocksize.x - 2); gridsize.x += ((blocksize.x-2) * gridsize.x < arraysize.x); gridsize.y = arraysize.y / (blocksize.y - 2); gridsize.y += ((blocksize.y-2) * gridsize.y < arraysize.y); gridsize.z = 1; gs = gradientStorage.devicePtr[i]; if(isThreeD) { hipLaunchKernelGGL(( cukern_applyPotentialGradient3D), dim3(32), dim3(256), 0, 0, fluid[0].devicePtr[i], gs, gs+fluid->slabPitch[i]/8, gs+2*fluid->slabPitch[i]/8, fluid->partNumel[i]); worked = CHECK_CUDA_LAUNCH_ERROR(blocksize, gridsize, fluid, i, "cukern_applyPotentialGradient3D"); if(worked != SUCCESSFUL) break; } else { hipLaunchKernelGGL(( cukern_applyPotentialGradient2D), dim3(32), dim3(256), 0, 0, fluid[0].devicePtr[i], gs, gs+fluid->slabPitch[i]/8, fluid->partNumel[i]); worked = CHECK_CUDA_LAUNCH_ERROR(blocksize, gridsize, fluid, i, "cukern_applyPotentialGradient2D"); if(worked != SUCCESSFUL) break; } } if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) return worked; worked = MGA_delete(&gradientStorage); return CHECK_IMOGEN_ERROR(worked); } /* dP = -rho grad(phi) dt * dE = -rho v \cdot grad(phi) dt * * Exact integrals at fixed position: * P2 = P1 - rho grad(phi) t * E2 = E1 - P1 \cdot grad(phi) t + .5 rho grad(phi) \cdot grad(phi) t^2 * = E1 - dt grad(phi) \cdot ( P1 - .5 * rho * grad(phi) ) */ __global__ void cukern_applyPotentialGradient3D(double *fluid, double *fx, double *fy, double *fz, unsigned int arrayNumel) { unsigned int globAddr = threadIdx.x + blockDim.x*blockIdx.x; if(globAddr >= arrayNumel) return; double deltaphi; // Store derivative of phi in one direction double rhomin = devLambda[3]; double locrho, ener, mom; for(; globAddr < arrayNumel; globAddr += blockDim.x*gridDim.x) { ener = 0; locrho = fluid[globAddr]; // rho(z) -> rho if(locrho > rhomin) { mom = fluid[globAddr + 2*devSlabdim[0]]; // load px(z) -> phiC deltaphi = fx[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener = -deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 2*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; mom = fluid[globAddr + 3*devSlabdim[0]]; // load py(z) -> phiC deltaphi = fy[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener -= deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 3*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; mom = fluid[globAddr + 4*devSlabdim[0]]; deltaphi = fz[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener -= deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 4*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; // Store changed kinetic energy fluid[globAddr + devSlabdim[0]] += ener; } } } /* dP = -rho grad(phi) dt * dE = -rho v \cdot grad(phi) dt * * Exact integrals at fixed position: * P2 = P1 - rho grad(phi) t * E2 = E1 - P1 \cdot grad(phi) t + .5 rho grad(phi) \cdot grad(phi) t^2 * = E1 - dt grad(phi) \cdot ( P1 - .5 * rho * grad(phi) ) */ __global__ void cukern_applyPotentialGradient2D(double *fluid, double *fx, double *fy, unsigned int arrayNumel) { unsigned int globAddr = threadIdx.x + blockDim.x*blockIdx.x; if(globAddr >= arrayNumel) return; double deltaphi; // Store derivative of phi in one direction double rhomin = devLambda[3]; double locrho, ener, mom; for(; globAddr < arrayNumel; globAddr += blockDim.x*gridDim.x) { ener = 0; locrho = fluid[globAddr]; // rho(z) -> rho if(locrho > rhomin) { mom = fluid[globAddr + 2*devSlabdim[0]]; // load px(z) -> phiC deltaphi = fx[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener = -deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 2*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; mom = fluid[globAddr + 3*devSlabdim[0]]; // load py(z) -> phiC deltaphi = fy[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener -= deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 3*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; // Store change to kinetic energy fluid[globAddr + devSlabdim[0]] += ener; } } }
74bea52a368644a1c1fef6df5a594aea027fda73.cu
#include <stdio.h> #include <string.h> #include <stdarg.h> #ifdef UNIX #include <stdint.h> #include <unistd.h> #endif #ifndef NOMATLAB #include "mex.h" #endif // CUDA #include "cuda.h" #include "cudaCommon.h" #include "cudaGradientKernels.h" #include "cudaSourceScalarPotential.h" #define BLOCKDIMX 18 #define BLOCKDIMY 18 template <geometryType_t coords> __global__ void cukern_computeScalarGradient3D(double *phi, double *f_x, double *f_y, double *f_z, int3 arraysize); template <geometryType_t coords> __global__ void cukern_computeScalarGradient2D(double *phi, double *fx, double *fy, int3 arraysize); __global__ void cukern_applyPotentialGradient3D(double *fluid, double *fx, double *fy, double *fz, unsigned int arrayNumel); __global__ void cukern_applyPotentialGradient2D(double *fluid, double *fx, double *fy, unsigned int arrayNumel); __constant__ __device__ double devLambda[9]; #define LAMX devLambda[0] #define LAMY devLambda[1] #define LAMZ devLambda[2] // Define: F = -beta * rho * grad(phi) // rho_g = density for full effect of gravity // rho_c = minimum density to feel gravity at all // beta = { rho_g < rho : 1 } // { rho_c < rho < rho_g : [(rho-rho_c)/(rho_rho_g-rho_c)]^2 } // { rho < rho_c : 0 } // This provides a continuous (though not differentiable at rho = rho_g) way to surpress gravitation of the background fluid // The original process of cutting gravity off below a critical density a few times the minimum // density is believed to cause "blowups" at the inner edge of circular flow profiles due to being // discontinuous. If even smoothness is insufficient and smooth differentiability is required, // a more-times-continuous profile can be constructed, but let's not go there unless forced. // Density below which we force gravity effects to zero #define RHOMIN devLambda[3] #define RHOGRAV devLambda[4] // 1 / (rho_g - rho_c) #define G1 devLambda[5] // rho_c / (rho_g - rho_c) #define G2 devLambda[6] #define RINNER devLambda[7] #define DELTAR devLambda[8] __constant__ __device__ unsigned int devSlabdim[3]; #ifdef STANDALONE_MEX_FUNCTION int fetchMinDensity(mxArray *mxFluids, int fluidNum, double *rhoMin) { int status = SUCCESSFUL; mxArray *flprop = mxGetProperty(mxFluids, fluidNum, "MINMASS"); if(flprop != NULL) { rhoMin[0] = *((double *)mxGetPr(flprop)); } else { PRINT_FAULT_HEADER; printf("Unable to access fluid(%i).MINMASS property.\n", fluidNum); PRINT_FAULT_FOOTER; status = ERROR_NULL_POINTER; } return status; } void mexFunction(int nlhs, mxArray *plhs[], int nrhs, const mxArray *prhs[]) { if ((nrhs!=4) || (nlhs != 0)) mexErrMsgTxt("Wrong number of arguments: need cudaApplyScalarPotential(FluidManager, phi, GeometryManager, [dt, rho_nograv, rho_fullgrav])\n"); if(CHECK_CUDA_ERROR("entering cudaSourceScalarPotential") != SUCCESSFUL) { DROP_MEX_ERROR("Failed upon entry to cudaSourceScalarPotential."); } // Get source array info and create destination arrays MGArray fluid[5]; MGArray phi; int worked = MGA_accessMatlabArrays(prhs, 1, 1, &phi); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) { DROP_MEX_ERROR("Failed to access input arrays."); } // Each partition uses the same common parameters GeometryParams geom = accessMatlabGeometryClass(prhs[2]); // FIXME check for fail & return int ne = mxGetNumberOfElements(prhs[3]); if(ne != 3) { printf("Input argument 3 has %i arguments, not three. Require precisely 3: [dt rho_nog rho_fullg]\n", ne); DROP_MEX_ERROR("Crashing."); } double *sp = mxGetPr(prhs[3]); double dt = sp[0]; /* dt */ double rhoMinimum = sp[1]; /* minimum rho, rho_c */ double rhoFull = sp[2]; /* rho_g */ int numFluids = mxGetNumberOfElements(prhs[0]); int fluidct; for(fluidct = 0; fluidct < numFluids; fluidct++) { worked = MGA_accessFluidCanister(prhs[0], fluidct, &fluid[0]); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; mxArray *flprop = mxGetProperty(prhs[0], fluidct, "MINMASS"); if(flprop != NULL) { rhoMinimum = *((double *)mxGetPr(flprop)); } else { worked = ERROR_NULL_POINTER; break; } worked = sourcefunction_ScalarPotential(&fluid[0], &phi, dt, geom, rhoMinimum, rhoFull); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; } GridFluid fluids[numFluids]; for(fluidct = 0; fluidct < numFluids; fluidct++) { worked = MGA_accessFluidCanister(prhs[0], fluidct, &fluids[fluidct].data[0]); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; //fluids[fluidct].thermo = accessMatlabThermoDetails(mxGetProperty(prhs[0], fluidct, "thermoDetails")); worked = fetchMinDensity((mxArray *)prhs[0], fluidct, &fluids[fluidct].rhoMin); } if(worked != SUCCESSFUL) { DROP_MEX_ERROR("cudaSourceScalarPotential failed"); } } #endif int sourcefunction_ScalarPotential(MGArray *fluid, MGArray *phi, double dt, GeometryParams geom, double minRho, double rhoFullGravity) { double *dx = &geom.h[0]; dim3 gridsize, blocksize; int3 arraysize; int i, sub[6]; int worked; double lambda[9]; lambda[0] = dt/(2.0*dx[0]); lambda[1] = dt/(2.0*dx[1]); lambda[2] = dt/(2.0*dx[2]); lambda[3] = minRho; /* minimum rho, rho_c */ lambda[4] = rhoFullGravity; /* rho_g */ lambda[5] = 1.0/(lambda[4] - lambda[3]); /* 1/(rho_g - rho_c) */ lambda[6] = lambda[3]*lambda[5]; lambda[7] = geom.Rinner; lambda[8] = dx[1]; for(i = 0; i < fluid->nGPUs; i++) { cudaSetDevice(fluid->deviceID[i]); cudaMemcpyToSymbol((const void *)devLambda, lambda, 9*sizeof(double), 0, cudaMemcpyHostToDevice); unsigned int sd[3]; sd[0] = (unsigned int)(fluid->slabPitch[i] / 8); cudaMemcpyToSymbol((const void *)devSlabdim, sd, 1*sizeof(int), 0, cudaMemcpyHostToDevice); worked = CHECK_CUDA_ERROR("cudaMemcpyToSymbol"); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) break; } if(worked != SUCCESSFUL) return worked; int isThreeD = (fluid->dim[2] > 1); MGArray gradientStorage; worked = MGA_allocSlab(fluid, &gradientStorage, 3); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) return worked; worked = computeCentralGradient(phi, &gradientStorage, geom, 2, dt); if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) return worked; double *gs; // Iterate over all partitions, and here we GO! for(i = 0; i < fluid->nGPUs; i++) { cudaSetDevice(fluid->deviceID[i]); calcPartitionExtent(fluid, i, sub); arraysize.x = sub[3]; arraysize.y = sub[4]; arraysize.z = sub[5]; blocksize = makeDim3(BLOCKDIMX, BLOCKDIMY, 1); gridsize.x = arraysize.x / (blocksize.x - 2); gridsize.x += ((blocksize.x-2) * gridsize.x < arraysize.x); gridsize.y = arraysize.y / (blocksize.y - 2); gridsize.y += ((blocksize.y-2) * gridsize.y < arraysize.y); gridsize.z = 1; gs = gradientStorage.devicePtr[i]; if(isThreeD) { cukern_applyPotentialGradient3D<<<32, 256>>>(fluid[0].devicePtr[i], gs, gs+fluid->slabPitch[i]/8, gs+2*fluid->slabPitch[i]/8, fluid->partNumel[i]); worked = CHECK_CUDA_LAUNCH_ERROR(blocksize, gridsize, fluid, i, "cukern_applyPotentialGradient3D"); if(worked != SUCCESSFUL) break; } else { cukern_applyPotentialGradient2D<<<32, 256>>>(fluid[0].devicePtr[i], gs, gs+fluid->slabPitch[i]/8, fluid->partNumel[i]); worked = CHECK_CUDA_LAUNCH_ERROR(blocksize, gridsize, fluid, i, "cukern_applyPotentialGradient2D"); if(worked != SUCCESSFUL) break; } } if(CHECK_IMOGEN_ERROR(worked) != SUCCESSFUL) return worked; worked = MGA_delete(&gradientStorage); return CHECK_IMOGEN_ERROR(worked); } /* dP = -rho grad(phi) dt * dE = -rho v \cdot grad(phi) dt * * Exact integrals at fixed position: * P2 = P1 - rho grad(phi) t * E2 = E1 - P1 \cdot grad(phi) t + .5 rho grad(phi) \cdot grad(phi) t^2 * = E1 - dt grad(phi) \cdot ( P1 - .5 * rho * grad(phi) ) */ __global__ void cukern_applyPotentialGradient3D(double *fluid, double *fx, double *fy, double *fz, unsigned int arrayNumel) { unsigned int globAddr = threadIdx.x + blockDim.x*blockIdx.x; if(globAddr >= arrayNumel) return; double deltaphi; // Store derivative of phi in one direction double rhomin = devLambda[3]; double locrho, ener, mom; for(; globAddr < arrayNumel; globAddr += blockDim.x*gridDim.x) { ener = 0; locrho = fluid[globAddr]; // rho(z) -> rho if(locrho > rhomin) { mom = fluid[globAddr + 2*devSlabdim[0]]; // load px(z) -> phiC deltaphi = fx[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener = -deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 2*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; mom = fluid[globAddr + 3*devSlabdim[0]]; // load py(z) -> phiC deltaphi = fy[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener -= deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 3*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; mom = fluid[globAddr + 4*devSlabdim[0]]; deltaphi = fz[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener -= deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 4*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; // Store changed kinetic energy fluid[globAddr + devSlabdim[0]] += ener; } } } /* dP = -rho grad(phi) dt * dE = -rho v \cdot grad(phi) dt * * Exact integrals at fixed position: * P2 = P1 - rho grad(phi) t * E2 = E1 - P1 \cdot grad(phi) t + .5 rho grad(phi) \cdot grad(phi) t^2 * = E1 - dt grad(phi) \cdot ( P1 - .5 * rho * grad(phi) ) */ __global__ void cukern_applyPotentialGradient2D(double *fluid, double *fx, double *fy, unsigned int arrayNumel) { unsigned int globAddr = threadIdx.x + blockDim.x*blockIdx.x; if(globAddr >= arrayNumel) return; double deltaphi; // Store derivative of phi in one direction double rhomin = devLambda[3]; double locrho, ener, mom; for(; globAddr < arrayNumel; globAddr += blockDim.x*gridDim.x) { ener = 0; locrho = fluid[globAddr]; // rho(z) -> rho if(locrho > rhomin) { mom = fluid[globAddr + 2*devSlabdim[0]]; // load px(z) -> phiC deltaphi = fx[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener = -deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 2*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; mom = fluid[globAddr + 3*devSlabdim[0]]; // load py(z) -> phiC deltaphi = fy[globAddr]; if(locrho < RHOGRAV) { deltaphi *= (locrho*G1 - G2); } // G smoothly -> 0 as rho -> RHO_MIN ener -= deltaphi*(mom-.5*locrho*deltaphi); // exact KE change fluid[globAddr + 3*devSlabdim[0]] = mom - deltaphi*locrho; // store px <- px - dt * rho dphi/dx; // Store change to kinetic energy fluid[globAddr + devSlabdim[0]] += ener; } } }
600fa6b21be925c77faaae390811bcb9fab14aba.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include <stdio.h> #include "gpu.h" //propagation data float *g_Vx0; float *g_Vz0; float *g_sigmaxx0; float *g_sigmazz0; float *g_sigmaxz0; //extended propagation data residence in GPU device __device__ float *ex_aux_m2m3_c; __device__ float *ex_aux_m2_c; __device__ float *ex_aux_m3_c; __device__ float *ex_sigmaxx0; __device__ float *ex_sigmazz0; __device__ float *ex_sigmaxz0; __device__ float *ex_Vx0; __device__ float *ex_Vz0; __device__ float *ex_m1_x; __device__ float *ex_m1_z; //constant data, extended, with 10 more layers over the CPU version float *g_ex_m1_x; float *g_ex_m1_z; float *g_ex_aux_m2_c; float *g_ex_aux_m3_c; float *g_ex_aux_m2m3_c; extern "C" void rtm_gpu_init(int nt, int nz, int nx) { //set cuda devices and put all data onto gpu memory hipError_t cuda_ret; hipError_t err; //Set Device cuda_ret = hipSetDevice(0); if(cuda_ret != hipSuccess){ fprintf(stderr, "Failed to Set The cuda Device !\n"); } else{ fprintf(stderr, "GPU Device Set ====> OK\n"); } // data init hipMalloc(&g_Vx0,sizeof(float)*nx*nz*nt); hipMalloc(&g_Vz0,sizeof(float)*nx*nz*nt); hipMalloc(&g_sigmaxx0,sizeof(float)*nx*nz*nt); hipMalloc(&g_sigmazz0,sizeof(float)*nx*nz*nt); hipMalloc(&g_sigmaxz0,sizeof(float)*nx*nz*nt); hipMalloc(&g_ex_m1_x,sizeof(float)*(nx+10)*(nz+10)); hipMalloc(&g_ex_m1_z,sizeof(float)*(nx+10)*(nz+10)); hipMalloc(&g_ex_aux_m2_c,sizeof(float)*(nx+10)*(nz+10)); hipMalloc(&g_ex_aux_m3_c,sizeof(float)*(nx+10)*(nz+10)); hipMalloc(&g_ex_aux_m2m3_c,sizeof(float)*(nx+10)*(nz+10)); fprintf(stderr,"GPU Data Init ====> OK\n"); // data copy // hipMemcpy(g_Vx0, Vx0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_Vz0, Vz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_sigmaxx0, sigmaxx0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_sigmaxz0, sigmaxz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_sigmazz0, sigmazz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_m1_x, m1_x, sizeof(float)*nx*nz, hipMemcpyHostToDevice); // hipMemcpy(g_m1_z, m1_z, sizeof(float)*nx*nz, hipMemcpyHostToDevice); // hipMemcpy(g_aux_m2_c, aux_m2_c, sizeof(float)*nx*nz, hipMemcpyHostToDevice); // hipMemcpy(g_aux_m3_c, aux_m3_c, sizeof(float)*nx*nz, hipMemcpyHostToDevice); // hipMemcpy(g_aux_m2m3_c, aux_m2m3_c, sizeof(float)*nx*nz, hipMemcpyHostToDevice); // fprintf(stderr,"Data Copy To GPU OK\n"); } extern "C" void rtm_gpu_copy_in(int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0, //(nz, nx, nt) float * ex_m1_x,float * ex_m1_z,float * ex_aux_m2_c, float * ex_aux_m3_c, float * ex_aux_m2m3_c)//(nz, nx) { // data copy hipMemcpy(g_Vx0, Vx0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); hipMemcpy(g_Vz0, Vz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); hipMemcpy(g_sigmaxx0, sigmaxx0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); hipMemcpy(g_sigmaxz0, sigmaxz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); hipMemcpy(g_sigmazz0, sigmazz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); hipMemcpy(g_ex_m1_x, ex_m1_x, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); hipMemcpy(g_ex_m1_z, ex_m1_z, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); hipMemcpy(g_ex_aux_m2_c, ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); hipMemcpy(g_ex_aux_m3_c, ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); hipMemcpy(g_ex_aux_m2m3_c, ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); fprintf(stderr,"Copy out for debuging \n"); hipMemcpy(ex_m1_x, g_ex_m1_x, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_m1_z, g_ex_m1_z, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_aux_m2_c, g_ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_aux_m3_c, g_ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_aux_m2m3_c, g_ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); fprintf(stderr,"Data Copy To GPU ====> OK\n"); } extern "C" void rtm_gpu_copy_out_debug(int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0, //(nz, nx, nt) float * ex_m1_x,float * ex_m1_z,float * ex_aux_m2_c, float * ex_aux_m3_c, float * ex_aux_m2m3_c)//(nz, nx) { // data copy // hipMemcpy(g_Vx0, Vx0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_Vz0, Vz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_sigmaxx0, sigmaxx0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_sigmaxz0, sigmaxz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_sigmazz0, sigmazz0, sizeof(float)*nx*nz*nt, hipMemcpyHostToDevice); // hipMemcpy(g_ex_m1_x, ex_m1_x, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); // hipMemcpy(g_ex_m1_z, ex_m1_z, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); // hipMemcpy(g_ex_aux_m2_c, ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); // hipMemcpy(g_ex_aux_m3_c, ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); // hipMemcpy(g_ex_aux_m2m3_c, ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyHostToDevice); fprintf(stderr,"Copy out for debuging \n"); hipMemcpy(ex_m1_x, g_ex_m1_x, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_m1_z, g_ex_m1_z, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_aux_m2_c, g_ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_aux_m3_c, g_ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); hipMemcpy(ex_aux_m2m3_c, g_ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), hipMemcpyDeviceToHost); } extern "C" void rtm_gpu_copy_out(int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0)//, //(nz, nx, nt) { // data copy back from GPU mem hipMemcpy(Vx0, g_Vx0, sizeof(float)*nx*nz*nt, hipMemcpyDeviceToHost); hipMemcpy(Vz0, g_Vz0,sizeof(float)*nx*nz*nt, hipMemcpyDeviceToHost); hipMemcpy(sigmaxx0, g_sigmaxx0, sizeof(float)*nx*nz*nt, hipMemcpyDeviceToHost); hipMemcpy(sigmaxz0, g_sigmaxz0, sizeof(float)*nx*nz*nt, hipMemcpyDeviceToHost); hipMemcpy(sigmazz0, g_sigmazz0, sizeof(float)*nx*nz*nt, hipMemcpyDeviceToHost); //hipMemcpy(sigmazz0, g_sigmazz0, sizeof(float)*nx*nz*nt, hipMemcpyDeviceToHost); fprintf(stderr,"Data Copy To CPU ====> OK\n"); } extern "C" void rtm_gpu_final() { //release GPU memory space hipFree(&g_Vx0); hipFree(&g_Vz0); hipFree(&g_sigmaxx0); hipFree(&g_sigmazz0); hipFree(&g_sigmaxz0); hipFree(&g_ex_m1_x); hipFree(&g_ex_m1_z); hipFree(&g_ex_aux_m2_c); hipFree(&g_ex_aux_m3_c); hipFree(&g_ex_aux_m2m3_c); fprintf(stderr,"GPU Mem Released ====> OK\n"); } __global__ void rtm_gpu_kernel(int it,int nt, int nz, int nx, float * g_Vx0, float * g_Vz0, float * g_sigmaxx0, float * g_sigmazz0, float * g_sigmaxz0, //(nz, nx, nt) float * g_ex_m1_x,float * g_ex_m1_z,float * g_ex_aux_m2_c, float * g_ex_aux_m3_c, float * g_ex_aux_m2m3_c)//(nz+10, nx+10) { float c1=35.0/294912.0,c2=-405.0/229376.0,c3=567.0/40960.0,c4=-735.0/8192.0,c5=19845.0/16384.0; //GPU thread index int iz, ix; iz = blockIdx.x*blockDim.x + threadIdx.x; ix = blockIdx.y*blockDim.y + threadIdx.y; //gt = it; g_Vx0[index3d(iz,ix ,it)] = g_Vx0[index3d(iz,ix ,it)] + g_Vx0[index3d(iz, ix, it+2)] + g_ex_aux_m2m3_c[index_ex(iz,ix-5)]*c1*g_sigmaxx0[index3d(iz,ix-5,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-4)]*c2*g_sigmaxx0[index3d(iz,ix-4,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-3)]*c3*g_sigmaxx0[index3d(iz,ix-3,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-2)]*c4*g_sigmaxx0[index3d(iz,ix-2,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-1)]*c5*g_sigmaxx0[index3d(iz,ix-1,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix)] *c5*g_sigmaxx0[index3d(iz,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+1)]*c4*g_sigmaxx0[index3d(iz,ix+1,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+2)]*c3*g_sigmaxx0[index3d(iz,ix+2,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+3)]*c2*g_sigmaxx0[index3d(iz,ix+3,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+4)]*c1*g_sigmaxx0[index3d(iz,ix+4,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-5)]*c1*g_sigmazz0[index3d(iz,ix-5,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-4)]*c2*g_sigmazz0[index3d(iz,ix-4,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-3)]*c3*g_sigmazz0[index3d(iz,ix-3,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-2)]*c4*g_sigmazz0[index3d(iz,ix-2,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-1)]*c5*g_sigmazz0[index3d(iz,ix-1,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix)] *c5*g_sigmazz0[index3d(iz,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+1)]*c4*g_sigmazz0[index3d(iz,ix+1,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+2)]*c3*g_sigmazz0[index3d(iz,ix+2,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+3)]*c2*g_sigmazz0[index3d(iz,ix+3,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+4)]*c1*g_sigmazz0[index3d(iz,ix+4,it+1)] + g_ex_aux_m3_c[index_ex(iz-4,ix)]*c1*g_sigmaxz0[index3d(iz-4,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz-3,ix)]*c2*g_sigmaxz0[index3d(iz-3,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz-2,ix)]*c3*g_sigmaxz0[index3d(iz-2,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz-1,ix)]*c4*g_sigmaxz0[index3d(iz-1,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix)] *c5*g_sigmaxz0[index3d(iz,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+1,ix)]*c5*g_sigmaxz0[index3d(iz+1,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+2,ix)]*c4*g_sigmaxz0[index3d(iz+2,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+3,ix)]*c3*g_sigmaxz0[index3d(iz+3,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+4,ix)]*c2*g_sigmaxz0[index3d(iz+4,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+5,ix)]*c1*g_sigmaxz0[index3d(iz+5,ix,it+1)] ; __syncthreads(); g_Vz0[index3d(iz,ix ,it)] = g_Vz0[index3d(iz,ix ,it)] + g_Vz0[index3d(iz,ix ,it+2)] + g_ex_aux_m2_c[index_ex(iz-5,ix)]*c1*g_sigmaxx0[index3d(iz-5,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-4,ix)]*c2*g_sigmaxx0[index3d(iz-4,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-3,ix)]*c3*g_sigmaxx0[index3d(iz-3,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-2,ix)]*c4*g_sigmaxx0[index3d(iz-2,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-1,ix)]*c5*g_sigmaxx0[index3d(iz-1,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix)] *c5*g_sigmaxx0[index3d(iz,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+1,ix)]*c4*g_sigmaxx0[index3d(iz+1,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+2,ix)]*c3*g_sigmaxx0[index3d(iz+2,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+3,ix)]*c2*g_sigmaxx0[index3d(iz+3,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+4,ix)]*c1*g_sigmaxx0[index3d(iz+4,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-5,ix)]*c1*g_sigmazz0[index3d(iz-5,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-4,ix)]*c2*g_sigmazz0[index3d(iz-4,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-3,ix)]*c3*g_sigmazz0[index3d(iz-3,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-2,ix)]*c4*g_sigmazz0[index3d(iz-2,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-1,ix)]*c5*g_sigmazz0[index3d(iz-1,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix)] *c5*g_sigmazz0[index3d(iz,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+1,ix)]*c4*g_sigmazz0[index3d(iz+1,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+2,ix)]*c3*g_sigmazz0[index3d(iz+2,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+3,ix)]*c2*g_sigmazz0[index3d(iz+3,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+4,ix)]*c1*g_sigmazz0[index3d(iz+4,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-4)]*c1*g_sigmaxz0[index3d(iz,ix-4,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-3)]*c2*g_sigmaxz0[index3d(iz,ix-3,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-2)]*c3*g_sigmaxz0[index3d(iz,ix-2,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-1)]*c4*g_sigmaxz0[index3d(iz,ix-1,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix)] *c5*g_sigmaxz0[index3d(iz,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+1)]*c5*g_sigmaxz0[index3d(iz,ix+1,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+2)]*c4*g_sigmaxz0[index3d(iz,ix+2,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+3)]*c3*g_sigmaxz0[index3d(iz,ix+3,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+4)]*c2*g_sigmaxz0[index3d(iz,ix+4,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+5)]*c1*g_sigmaxz0[index3d(iz,ix+5,it+1)] ; } __global__ void rtm_gpu_kernelB(int it,int nt, int nz, int nx, float * g_Vx0, float * g_Vz0, float * g_sigmaxx0, float * g_sigmazz0, float * g_sigmaxz0, //(nz, nx, nt) float * g_ex_m1_x,float * g_ex_m1_z,float * g_ex_aux_m2_c, float * g_ex_aux_m3_c, float * g_ex_aux_m2m3_c)//(nz+10, nx+10) { float c1=35.0/294912.0,c2=-405.0/229376.0,c3=567.0/40960.0,c4=-735.0/8192.0,c5=19845.0/16384.0; int iz, ix; iz = blockIdx.x*blockDim.x + threadIdx.x; ix = blockIdx.y*blockDim.y + threadIdx.y; // g_sigmaxx0[index3d(iz,ix ,it)] = g_sigmaxx0[index3d(iz,ix ,it)] + g_sigmaxx0[index3d(iz,ix ,it+2)] // + g_ex_m1_x[index_ex(iz,ix-4)]*c1*g_Vx0[index3d(iz,ix-4,it+1)] // + g_ex_m1_x[index_ex(iz,ix-3)]*c2*g_Vx0[index3d(iz,ix-3,it+1)] // + g_ex_m1_x[index_ex(iz,ix-2)]*c3*g_Vx0[index3d(iz,ix-2,it+1)] // + g_ex_m1_x[index_ex(iz,ix-1)]*c4*g_Vx0[index3d(iz,ix-1,it+1)] // + g_ex_m1_x[index_ex(iz,ix)] *c5*g_Vx0[index3d(iz,ix,it+1)] // - g_ex_m1_x[index_ex(iz,ix+1)]*c5*g_Vx0[index3d(iz,ix+1,it+1)] // - g_ex_m1_x[index_ex(iz,ix+2)]*c4*g_Vx0[index3d(iz,ix+2,it+1)] // - g_ex_m1_x[index_ex(iz,ix+3)]*c3*g_Vx0[index3d(iz,ix+3,it+1)] // - g_ex_m1_x[index_ex(iz,ix+4)]*c2*g_Vx0[index3d(iz,ix+4,it+1)] // - g_ex_m1_x[index_ex(iz,ix+5)]*c1*g_Vx0[index3d(iz,ix+5,it+1)] ; // __syncthreads(); g_sigmazz0[index3d(iz,ix ,it)] = g_sigmazz0[index3d(iz,ix ,it)] + g_sigmazz0[index3d(iz,ix ,it+2)] + g_ex_m1_z[index_ex(iz-4,ix)]*c1*g_Vz0[index3d(iz-4,ix,it+1)] + g_ex_m1_z[index_ex(iz-3,ix)]*c2*g_Vz0[index3d(iz-3,ix,it+1)] + g_ex_m1_z[index_ex(iz-2,ix)]*c3*g_Vz0[index3d(iz-2,ix,it+1)] + g_ex_m1_z[index_ex(iz-1,ix)]*c4*g_Vz0[index3d(iz-1,ix,it+1)] + g_ex_m1_z[index_ex(iz,ix)] *c5*g_Vz0[index3d(iz,ix,it+1)] - g_ex_m1_z[index_ex(iz+1,ix)]*c5*g_Vz0[index3d(iz+1,ix,it+1)] - g_ex_m1_z[index_ex(iz+2,ix)]*c4*g_Vz0[index3d(iz+2,ix,it+1)] - g_ex_m1_z[index_ex(iz+3,ix)]*c3*g_Vz0[index3d(iz+3,ix,it+1)] - g_ex_m1_z[index_ex(iz+4,ix)]*c2*g_Vz0[index3d(iz+4,ix,it+1)] - g_ex_m1_z[index_ex(iz+5,ix)]*c1*g_Vz0[index3d(iz+5,ix,it+1)] ; __syncthreads(); // g_sigmaxz0[index3d(iz,ix ,it)] = g_sigmaxz0[index3d(iz,ix ,it)] + g_sigmaxz0[index3d(iz,ix ,it+2)] // + g_ex_m1_x[index_ex(iz-5,ix)]*c1*g_Vx0[index3d(iz-5,ix,it+1)] // + g_ex_m1_x[index_ex(iz-4,ix)]*c2*g_Vx0[index3d(iz-4,ix,it+1)] // + g_ex_m1_x[index_ex(iz-3,ix)]*c3*g_Vx0[index3d(iz-3,ix,it+1)] // + g_ex_m1_x[index_ex(iz-2,ix)]*c4*g_Vx0[index3d(iz-2,ix,it+1)] // + g_ex_m1_x[index_ex(iz-1,ix)]*c5*g_Vx0[index3d(iz-1,ix,it+1)] // - g_ex_m1_x[index_ex(iz,ix)] *c5*g_Vx0[index3d(iz,ix,it+1)] // - g_ex_m1_x[index_ex(iz+1,ix)]*c4*g_Vx0[index3d(iz+1,ix,it+1)] // - g_ex_m1_x[index_ex(iz+2,ix)]*c3*g_Vx0[index3d(iz+2,ix,it+1)] // - g_ex_m1_x[index_ex(iz+3,ix)]*c2*g_Vx0[index3d(iz+3,ix,it+1)] // - g_ex_m1_x[index_ex(iz+4,ix)]*c1*g_Vx0[index3d(iz+4,ix,it+1)] //; // // // //sigmaxz0[index3d(iz,ix ,it)] = sigmaxz0[index3d(iz,ix ,it)] // + g_ex_m1_z[index_ex(iz,ix-5)]*c1*g_Vz0[index3d(iz,ix-5,it+1)] // + g_ex_m1_z[index_ex(iz,ix-4)]*c2*g_Vz0[index3d(iz,ix-4,it+1)] // + g_ex_m1_z[index_ex(iz,ix-3)]*c3*g_Vz0[index3d(iz,ix-3,it+1)] // + g_ex_m1_z[index_ex(iz,ix-2)]*c4*g_Vz0[index3d(iz,ix-2,it+1)] // + g_ex_m1_z[index_ex(iz,ix-1)]*c5*g_Vz0[index3d(iz,ix-1,it+1)] // - g_ex_m1_z[index_ex(iz,ix)] *c5*g_Vz0[index3d(iz,ix,it+1)] // - g_ex_m1_z[index_ex(iz,ix+1)]*c4*g_Vz0[index3d(iz,ix+1,it+1)] // - g_ex_m1_z[index_ex(iz,ix+2)]*c3*g_Vz0[index3d(iz,ix+2,it+1)] // - g_ex_m1_z[index_ex(iz,ix+3)]*c2*g_Vz0[index3d(iz,ix+3,it+1)] // - g_ex_m1_z[index_ex(iz,ix+4)]*c1*g_Vz0[index3d(iz,ix+4,it+1)] ; // __syncthreads(); } extern "C" void rtm_gpu_func(int it, int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0, //(nz, nx, nt) float * ex_m1_x,float * ex_m1_z,float * ex_aux_m2_c, float * ex_aux_m3_c, float * ex_aux_m2m3_c,//)//(nz+10,nx+10) float * debug) { hipError_t err; hipEvent_t start, stop; float elapsedTime = 0.0f; int g_it; //time record //data copy in rtm_gpu_copy_in(nt, nz, nx, Vx0, Vz0, sigmaxx0, sigmazz0, sigmaxz0, ex_m1_x, ex_m1_z, ex_aux_m2_c, ex_aux_m3_c, ex_aux_m2m3_c); err = hipGetLastError(); if(hipSuccess != err){ fprintf(stderr, "Cuda error1: %s.\n", hipGetErrorString(err)); } fprintf(stderr,"GPU Computing ... ...(NZ=%d, NX=%d, TZ=%d, TX=%d)\n", nz, nx, TZ, TX); //for(g_it = nt-3; g_it>=0; g_it--){ dim3 dimGrid(nz/TZ, nx/TX); dim3 dimBlock(TZ, TX); //RTM kernel //hipEventRecord(start, 0); //fprintf(stderr,"TS=%d\n", g_it); hipLaunchKernelGGL(( rtm_gpu_kernel), dim3(dimGrid), dim3(dimBlock), 0, 0, it,nt, nz, nx, g_Vx0, g_Vz0, g_sigmaxx0, g_sigmazz0, g_sigmaxz0, g_ex_m1_x, g_ex_m1_z, g_ex_aux_m2_c, g_ex_aux_m3_c, g_ex_aux_m2m3_c); hipDeviceSynchronize(); hipLaunchKernelGGL(( rtm_gpu_kernelB), dim3(dimGrid), dim3(dimBlock), 0, 0, it,nt, nz, nx, g_Vx0, g_Vz0, g_sigmaxx0, g_sigmazz0, g_sigmaxz0, g_ex_m1_x, g_ex_m1_z, g_ex_aux_m2_c, g_ex_aux_m3_c, g_ex_aux_m2m3_c); hipDeviceSynchronize(); err = hipGetLastError(); if(hipSuccess != err){ fprintf(stderr, "Cuda error2: %s.\n", hipGetErrorString(err)); } //} fprintf(stderr, "Debugging here.\n"); rtm_gpu_copy_out(nt, nz, nx, Vx0, Vz0, sigmaxx0, debug, sigmaxz0); hipDeviceSynchronize(); rtm_gpu_copy_out_debug(nt, nz, nx, Vx0, Vz0, sigmaxx0, sigmazz0, sigmaxz0, ex_m1_x, ex_m1_z, ex_aux_m2_c, ex_aux_m3_c, ex_aux_m2m3_c); err = hipGetLastError(); if(hipSuccess != err){ fprintf(stderr, "Cuda error3: %s.\n", hipGetErrorString(err)); } //hipEventRecord(stop, 0); //hipEventSynchronize(stop); //hipEventElapsedTime(&elapsedTime, start, stop); //fprintf(stderr,"GPU Computational Elapsed Time: %.4f\n",elapsedTime); }
600fa6b21be925c77faaae390811bcb9fab14aba.cu
#include <stdio.h> #include "gpu.h" //propagation data float *g_Vx0; float *g_Vz0; float *g_sigmaxx0; float *g_sigmazz0; float *g_sigmaxz0; //extended propagation data residence in GPU device __device__ float *ex_aux_m2m3_c; __device__ float *ex_aux_m2_c; __device__ float *ex_aux_m3_c; __device__ float *ex_sigmaxx0; __device__ float *ex_sigmazz0; __device__ float *ex_sigmaxz0; __device__ float *ex_Vx0; __device__ float *ex_Vz0; __device__ float *ex_m1_x; __device__ float *ex_m1_z; //constant data, extended, with 10 more layers over the CPU version float *g_ex_m1_x; float *g_ex_m1_z; float *g_ex_aux_m2_c; float *g_ex_aux_m3_c; float *g_ex_aux_m2m3_c; extern "C" void rtm_gpu_init(int nt, int nz, int nx) { //set cuda devices and put all data onto gpu memory cudaError_t cuda_ret; cudaError_t err; //Set Device cuda_ret = cudaSetDevice(0); if(cuda_ret != cudaSuccess){ fprintf(stderr, "Failed to Set The cuda Device !\n"); } else{ fprintf(stderr, "GPU Device Set ====> OK\n"); } // data init cudaMalloc(&g_Vx0,sizeof(float)*nx*nz*nt); cudaMalloc(&g_Vz0,sizeof(float)*nx*nz*nt); cudaMalloc(&g_sigmaxx0,sizeof(float)*nx*nz*nt); cudaMalloc(&g_sigmazz0,sizeof(float)*nx*nz*nt); cudaMalloc(&g_sigmaxz0,sizeof(float)*nx*nz*nt); cudaMalloc(&g_ex_m1_x,sizeof(float)*(nx+10)*(nz+10)); cudaMalloc(&g_ex_m1_z,sizeof(float)*(nx+10)*(nz+10)); cudaMalloc(&g_ex_aux_m2_c,sizeof(float)*(nx+10)*(nz+10)); cudaMalloc(&g_ex_aux_m3_c,sizeof(float)*(nx+10)*(nz+10)); cudaMalloc(&g_ex_aux_m2m3_c,sizeof(float)*(nx+10)*(nz+10)); fprintf(stderr,"GPU Data Init ====> OK\n"); // data copy // cudaMemcpy(g_Vx0, Vx0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_Vz0, Vz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_sigmaxx0, sigmaxx0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_sigmaxz0, sigmaxz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_sigmazz0, sigmazz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_m1_x, m1_x, sizeof(float)*nx*nz, cudaMemcpyHostToDevice); // cudaMemcpy(g_m1_z, m1_z, sizeof(float)*nx*nz, cudaMemcpyHostToDevice); // cudaMemcpy(g_aux_m2_c, aux_m2_c, sizeof(float)*nx*nz, cudaMemcpyHostToDevice); // cudaMemcpy(g_aux_m3_c, aux_m3_c, sizeof(float)*nx*nz, cudaMemcpyHostToDevice); // cudaMemcpy(g_aux_m2m3_c, aux_m2m3_c, sizeof(float)*nx*nz, cudaMemcpyHostToDevice); // fprintf(stderr,"Data Copy To GPU OK\n"); } extern "C" void rtm_gpu_copy_in(int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0, //(nz, nx, nt) float * ex_m1_x,float * ex_m1_z,float * ex_aux_m2_c, float * ex_aux_m3_c, float * ex_aux_m2m3_c)//(nz, nx) { // data copy cudaMemcpy(g_Vx0, Vx0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); cudaMemcpy(g_Vz0, Vz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); cudaMemcpy(g_sigmaxx0, sigmaxx0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); cudaMemcpy(g_sigmaxz0, sigmaxz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); cudaMemcpy(g_sigmazz0, sigmazz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); cudaMemcpy(g_ex_m1_x, ex_m1_x, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); cudaMemcpy(g_ex_m1_z, ex_m1_z, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); cudaMemcpy(g_ex_aux_m2_c, ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); cudaMemcpy(g_ex_aux_m3_c, ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); cudaMemcpy(g_ex_aux_m2m3_c, ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); fprintf(stderr,"Copy out for debuging \n"); cudaMemcpy(ex_m1_x, g_ex_m1_x, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_m1_z, g_ex_m1_z, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_aux_m2_c, g_ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_aux_m3_c, g_ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_aux_m2m3_c, g_ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); fprintf(stderr,"Data Copy To GPU ====> OK\n"); } extern "C" void rtm_gpu_copy_out_debug(int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0, //(nz, nx, nt) float * ex_m1_x,float * ex_m1_z,float * ex_aux_m2_c, float * ex_aux_m3_c, float * ex_aux_m2m3_c)//(nz, nx) { // data copy // cudaMemcpy(g_Vx0, Vx0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_Vz0, Vz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_sigmaxx0, sigmaxx0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_sigmaxz0, sigmaxz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_sigmazz0, sigmazz0, sizeof(float)*nx*nz*nt, cudaMemcpyHostToDevice); // cudaMemcpy(g_ex_m1_x, ex_m1_x, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); // cudaMemcpy(g_ex_m1_z, ex_m1_z, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); // cudaMemcpy(g_ex_aux_m2_c, ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); // cudaMemcpy(g_ex_aux_m3_c, ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); // cudaMemcpy(g_ex_aux_m2m3_c, ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyHostToDevice); fprintf(stderr,"Copy out for debuging \n"); cudaMemcpy(ex_m1_x, g_ex_m1_x, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_m1_z, g_ex_m1_z, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_aux_m2_c, g_ex_aux_m2_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_aux_m3_c, g_ex_aux_m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); cudaMemcpy(ex_aux_m2m3_c, g_ex_aux_m2m3_c, sizeof(float)*(nx+10)*(nz+10), cudaMemcpyDeviceToHost); } extern "C" void rtm_gpu_copy_out(int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0)//, //(nz, nx, nt) { // data copy back from GPU mem cudaMemcpy(Vx0, g_Vx0, sizeof(float)*nx*nz*nt, cudaMemcpyDeviceToHost); cudaMemcpy(Vz0, g_Vz0,sizeof(float)*nx*nz*nt, cudaMemcpyDeviceToHost); cudaMemcpy(sigmaxx0, g_sigmaxx0, sizeof(float)*nx*nz*nt, cudaMemcpyDeviceToHost); cudaMemcpy(sigmaxz0, g_sigmaxz0, sizeof(float)*nx*nz*nt, cudaMemcpyDeviceToHost); cudaMemcpy(sigmazz0, g_sigmazz0, sizeof(float)*nx*nz*nt, cudaMemcpyDeviceToHost); //cudaMemcpy(sigmazz0, g_sigmazz0, sizeof(float)*nx*nz*nt, cudaMemcpyDeviceToHost); fprintf(stderr,"Data Copy To CPU ====> OK\n"); } extern "C" void rtm_gpu_final() { //release GPU memory space cudaFree(&g_Vx0); cudaFree(&g_Vz0); cudaFree(&g_sigmaxx0); cudaFree(&g_sigmazz0); cudaFree(&g_sigmaxz0); cudaFree(&g_ex_m1_x); cudaFree(&g_ex_m1_z); cudaFree(&g_ex_aux_m2_c); cudaFree(&g_ex_aux_m3_c); cudaFree(&g_ex_aux_m2m3_c); fprintf(stderr,"GPU Mem Released ====> OK\n"); } __global__ void rtm_gpu_kernel(int it,int nt, int nz, int nx, float * g_Vx0, float * g_Vz0, float * g_sigmaxx0, float * g_sigmazz0, float * g_sigmaxz0, //(nz, nx, nt) float * g_ex_m1_x,float * g_ex_m1_z,float * g_ex_aux_m2_c, float * g_ex_aux_m3_c, float * g_ex_aux_m2m3_c)//(nz+10, nx+10) { float c1=35.0/294912.0,c2=-405.0/229376.0,c3=567.0/40960.0,c4=-735.0/8192.0,c5=19845.0/16384.0; //GPU thread index int iz, ix; iz = blockIdx.x*blockDim.x + threadIdx.x; ix = blockIdx.y*blockDim.y + threadIdx.y; //gt = it; g_Vx0[index3d(iz,ix ,it)] = g_Vx0[index3d(iz,ix ,it)] + g_Vx0[index3d(iz, ix, it+2)] + g_ex_aux_m2m3_c[index_ex(iz,ix-5)]*c1*g_sigmaxx0[index3d(iz,ix-5,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-4)]*c2*g_sigmaxx0[index3d(iz,ix-4,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-3)]*c3*g_sigmaxx0[index3d(iz,ix-3,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-2)]*c4*g_sigmaxx0[index3d(iz,ix-2,it+1)] + g_ex_aux_m2m3_c[index_ex(iz,ix-1)]*c5*g_sigmaxx0[index3d(iz,ix-1,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix)] *c5*g_sigmaxx0[index3d(iz,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+1)]*c4*g_sigmaxx0[index3d(iz,ix+1,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+2)]*c3*g_sigmaxx0[index3d(iz,ix+2,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+3)]*c2*g_sigmaxx0[index3d(iz,ix+3,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix+4)]*c1*g_sigmaxx0[index3d(iz,ix+4,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-5)]*c1*g_sigmazz0[index3d(iz,ix-5,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-4)]*c2*g_sigmazz0[index3d(iz,ix-4,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-3)]*c3*g_sigmazz0[index3d(iz,ix-3,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-2)]*c4*g_sigmazz0[index3d(iz,ix-2,it+1)] + g_ex_aux_m2_c[index_ex(iz,ix-1)]*c5*g_sigmazz0[index3d(iz,ix-1,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix)] *c5*g_sigmazz0[index3d(iz,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+1)]*c4*g_sigmazz0[index3d(iz,ix+1,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+2)]*c3*g_sigmazz0[index3d(iz,ix+2,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+3)]*c2*g_sigmazz0[index3d(iz,ix+3,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix+4)]*c1*g_sigmazz0[index3d(iz,ix+4,it+1)] + g_ex_aux_m3_c[index_ex(iz-4,ix)]*c1*g_sigmaxz0[index3d(iz-4,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz-3,ix)]*c2*g_sigmaxz0[index3d(iz-3,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz-2,ix)]*c3*g_sigmaxz0[index3d(iz-2,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz-1,ix)]*c4*g_sigmaxz0[index3d(iz-1,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix)] *c5*g_sigmaxz0[index3d(iz,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+1,ix)]*c5*g_sigmaxz0[index3d(iz+1,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+2,ix)]*c4*g_sigmaxz0[index3d(iz+2,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+3,ix)]*c3*g_sigmaxz0[index3d(iz+3,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+4,ix)]*c2*g_sigmaxz0[index3d(iz+4,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz+5,ix)]*c1*g_sigmaxz0[index3d(iz+5,ix,it+1)] ; __syncthreads(); g_Vz0[index3d(iz,ix ,it)] = g_Vz0[index3d(iz,ix ,it)] + g_Vz0[index3d(iz,ix ,it+2)] + g_ex_aux_m2_c[index_ex(iz-5,ix)]*c1*g_sigmaxx0[index3d(iz-5,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-4,ix)]*c2*g_sigmaxx0[index3d(iz-4,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-3,ix)]*c3*g_sigmaxx0[index3d(iz-3,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-2,ix)]*c4*g_sigmaxx0[index3d(iz-2,ix,it+1)] + g_ex_aux_m2_c[index_ex(iz-1,ix)]*c5*g_sigmaxx0[index3d(iz-1,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz,ix)] *c5*g_sigmaxx0[index3d(iz,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+1,ix)]*c4*g_sigmaxx0[index3d(iz+1,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+2,ix)]*c3*g_sigmaxx0[index3d(iz+2,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+3,ix)]*c2*g_sigmaxx0[index3d(iz+3,ix,it+1)] - g_ex_aux_m2_c[index_ex(iz+4,ix)]*c1*g_sigmaxx0[index3d(iz+4,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-5,ix)]*c1*g_sigmazz0[index3d(iz-5,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-4,ix)]*c2*g_sigmazz0[index3d(iz-4,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-3,ix)]*c3*g_sigmazz0[index3d(iz-3,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-2,ix)]*c4*g_sigmazz0[index3d(iz-2,ix,it+1)] + g_ex_aux_m2m3_c[index_ex(iz-1,ix)]*c5*g_sigmazz0[index3d(iz-1,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz,ix)] *c5*g_sigmazz0[index3d(iz,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+1,ix)]*c4*g_sigmazz0[index3d(iz+1,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+2,ix)]*c3*g_sigmazz0[index3d(iz+2,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+3,ix)]*c2*g_sigmazz0[index3d(iz+3,ix,it+1)] - g_ex_aux_m2m3_c[index_ex(iz+4,ix)]*c1*g_sigmazz0[index3d(iz+4,ix,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-4)]*c1*g_sigmaxz0[index3d(iz,ix-4,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-3)]*c2*g_sigmaxz0[index3d(iz,ix-3,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-2)]*c3*g_sigmaxz0[index3d(iz,ix-2,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix-1)]*c4*g_sigmaxz0[index3d(iz,ix-1,it+1)] + g_ex_aux_m3_c[index_ex(iz,ix)] *c5*g_sigmaxz0[index3d(iz,ix,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+1)]*c5*g_sigmaxz0[index3d(iz,ix+1,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+2)]*c4*g_sigmaxz0[index3d(iz,ix+2,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+3)]*c3*g_sigmaxz0[index3d(iz,ix+3,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+4)]*c2*g_sigmaxz0[index3d(iz,ix+4,it+1)] - g_ex_aux_m3_c[index_ex(iz,ix+5)]*c1*g_sigmaxz0[index3d(iz,ix+5,it+1)] ; } __global__ void rtm_gpu_kernelB(int it,int nt, int nz, int nx, float * g_Vx0, float * g_Vz0, float * g_sigmaxx0, float * g_sigmazz0, float * g_sigmaxz0, //(nz, nx, nt) float * g_ex_m1_x,float * g_ex_m1_z,float * g_ex_aux_m2_c, float * g_ex_aux_m3_c, float * g_ex_aux_m2m3_c)//(nz+10, nx+10) { float c1=35.0/294912.0,c2=-405.0/229376.0,c3=567.0/40960.0,c4=-735.0/8192.0,c5=19845.0/16384.0; int iz, ix; iz = blockIdx.x*blockDim.x + threadIdx.x; ix = blockIdx.y*blockDim.y + threadIdx.y; // g_sigmaxx0[index3d(iz,ix ,it)] = g_sigmaxx0[index3d(iz,ix ,it)] + g_sigmaxx0[index3d(iz,ix ,it+2)] // + g_ex_m1_x[index_ex(iz,ix-4)]*c1*g_Vx0[index3d(iz,ix-4,it+1)] // + g_ex_m1_x[index_ex(iz,ix-3)]*c2*g_Vx0[index3d(iz,ix-3,it+1)] // + g_ex_m1_x[index_ex(iz,ix-2)]*c3*g_Vx0[index3d(iz,ix-2,it+1)] // + g_ex_m1_x[index_ex(iz,ix-1)]*c4*g_Vx0[index3d(iz,ix-1,it+1)] // + g_ex_m1_x[index_ex(iz,ix)] *c5*g_Vx0[index3d(iz,ix,it+1)] // - g_ex_m1_x[index_ex(iz,ix+1)]*c5*g_Vx0[index3d(iz,ix+1,it+1)] // - g_ex_m1_x[index_ex(iz,ix+2)]*c4*g_Vx0[index3d(iz,ix+2,it+1)] // - g_ex_m1_x[index_ex(iz,ix+3)]*c3*g_Vx0[index3d(iz,ix+3,it+1)] // - g_ex_m1_x[index_ex(iz,ix+4)]*c2*g_Vx0[index3d(iz,ix+4,it+1)] // - g_ex_m1_x[index_ex(iz,ix+5)]*c1*g_Vx0[index3d(iz,ix+5,it+1)] ; // __syncthreads(); g_sigmazz0[index3d(iz,ix ,it)] = g_sigmazz0[index3d(iz,ix ,it)] + g_sigmazz0[index3d(iz,ix ,it+2)] + g_ex_m1_z[index_ex(iz-4,ix)]*c1*g_Vz0[index3d(iz-4,ix,it+1)] + g_ex_m1_z[index_ex(iz-3,ix)]*c2*g_Vz0[index3d(iz-3,ix,it+1)] + g_ex_m1_z[index_ex(iz-2,ix)]*c3*g_Vz0[index3d(iz-2,ix,it+1)] + g_ex_m1_z[index_ex(iz-1,ix)]*c4*g_Vz0[index3d(iz-1,ix,it+1)] + g_ex_m1_z[index_ex(iz,ix)] *c5*g_Vz0[index3d(iz,ix,it+1)] - g_ex_m1_z[index_ex(iz+1,ix)]*c5*g_Vz0[index3d(iz+1,ix,it+1)] - g_ex_m1_z[index_ex(iz+2,ix)]*c4*g_Vz0[index3d(iz+2,ix,it+1)] - g_ex_m1_z[index_ex(iz+3,ix)]*c3*g_Vz0[index3d(iz+3,ix,it+1)] - g_ex_m1_z[index_ex(iz+4,ix)]*c2*g_Vz0[index3d(iz+4,ix,it+1)] - g_ex_m1_z[index_ex(iz+5,ix)]*c1*g_Vz0[index3d(iz+5,ix,it+1)] ; __syncthreads(); // g_sigmaxz0[index3d(iz,ix ,it)] = g_sigmaxz0[index3d(iz,ix ,it)] + g_sigmaxz0[index3d(iz,ix ,it+2)] // + g_ex_m1_x[index_ex(iz-5,ix)]*c1*g_Vx0[index3d(iz-5,ix,it+1)] // + g_ex_m1_x[index_ex(iz-4,ix)]*c2*g_Vx0[index3d(iz-4,ix,it+1)] // + g_ex_m1_x[index_ex(iz-3,ix)]*c3*g_Vx0[index3d(iz-3,ix,it+1)] // + g_ex_m1_x[index_ex(iz-2,ix)]*c4*g_Vx0[index3d(iz-2,ix,it+1)] // + g_ex_m1_x[index_ex(iz-1,ix)]*c5*g_Vx0[index3d(iz-1,ix,it+1)] // - g_ex_m1_x[index_ex(iz,ix)] *c5*g_Vx0[index3d(iz,ix,it+1)] // - g_ex_m1_x[index_ex(iz+1,ix)]*c4*g_Vx0[index3d(iz+1,ix,it+1)] // - g_ex_m1_x[index_ex(iz+2,ix)]*c3*g_Vx0[index3d(iz+2,ix,it+1)] // - g_ex_m1_x[index_ex(iz+3,ix)]*c2*g_Vx0[index3d(iz+3,ix,it+1)] // - g_ex_m1_x[index_ex(iz+4,ix)]*c1*g_Vx0[index3d(iz+4,ix,it+1)] //; // // // //sigmaxz0[index3d(iz,ix ,it)] = sigmaxz0[index3d(iz,ix ,it)] // + g_ex_m1_z[index_ex(iz,ix-5)]*c1*g_Vz0[index3d(iz,ix-5,it+1)] // + g_ex_m1_z[index_ex(iz,ix-4)]*c2*g_Vz0[index3d(iz,ix-4,it+1)] // + g_ex_m1_z[index_ex(iz,ix-3)]*c3*g_Vz0[index3d(iz,ix-3,it+1)] // + g_ex_m1_z[index_ex(iz,ix-2)]*c4*g_Vz0[index3d(iz,ix-2,it+1)] // + g_ex_m1_z[index_ex(iz,ix-1)]*c5*g_Vz0[index3d(iz,ix-1,it+1)] // - g_ex_m1_z[index_ex(iz,ix)] *c5*g_Vz0[index3d(iz,ix,it+1)] // - g_ex_m1_z[index_ex(iz,ix+1)]*c4*g_Vz0[index3d(iz,ix+1,it+1)] // - g_ex_m1_z[index_ex(iz,ix+2)]*c3*g_Vz0[index3d(iz,ix+2,it+1)] // - g_ex_m1_z[index_ex(iz,ix+3)]*c2*g_Vz0[index3d(iz,ix+3,it+1)] // - g_ex_m1_z[index_ex(iz,ix+4)]*c1*g_Vz0[index3d(iz,ix+4,it+1)] ; // __syncthreads(); } extern "C" void rtm_gpu_func(int it, int nt, int nz, int nx, float * Vx0, float * Vz0, float * sigmaxx0, float * sigmazz0, float * sigmaxz0, //(nz, nx, nt) float * ex_m1_x,float * ex_m1_z,float * ex_aux_m2_c, float * ex_aux_m3_c, float * ex_aux_m2m3_c,//)//(nz+10,nx+10) float * debug) { cudaError_t err; cudaEvent_t start, stop; float elapsedTime = 0.0f; int g_it; //time record //data copy in rtm_gpu_copy_in(nt, nz, nx, Vx0, Vz0, sigmaxx0, sigmazz0, sigmaxz0, ex_m1_x, ex_m1_z, ex_aux_m2_c, ex_aux_m3_c, ex_aux_m2m3_c); err = cudaGetLastError(); if(cudaSuccess != err){ fprintf(stderr, "Cuda error1: %s.\n", cudaGetErrorString(err)); } fprintf(stderr,"GPU Computing ... ...(NZ=%d, NX=%d, TZ=%d, TX=%d)\n", nz, nx, TZ, TX); //for(g_it = nt-3; g_it>=0; g_it--){ dim3 dimGrid(nz/TZ, nx/TX); dim3 dimBlock(TZ, TX); //RTM kernel //cudaEventRecord(start, 0); //fprintf(stderr,"TS=%d\n", g_it); rtm_gpu_kernel<<<dimGrid, dimBlock>>>(it,nt, nz, nx, g_Vx0, g_Vz0, g_sigmaxx0, g_sigmazz0, g_sigmaxz0, g_ex_m1_x, g_ex_m1_z, g_ex_aux_m2_c, g_ex_aux_m3_c, g_ex_aux_m2m3_c); cudaThreadSynchronize(); rtm_gpu_kernelB<<<dimGrid, dimBlock>>>(it,nt, nz, nx, g_Vx0, g_Vz0, g_sigmaxx0, g_sigmazz0, g_sigmaxz0, g_ex_m1_x, g_ex_m1_z, g_ex_aux_m2_c, g_ex_aux_m3_c, g_ex_aux_m2m3_c); cudaThreadSynchronize(); err = cudaGetLastError(); if(cudaSuccess != err){ fprintf(stderr, "Cuda error2: %s.\n", cudaGetErrorString(err)); } //} fprintf(stderr, "Debugging here.\n"); rtm_gpu_copy_out(nt, nz, nx, Vx0, Vz0, sigmaxx0, debug, sigmaxz0); cudaThreadSynchronize(); rtm_gpu_copy_out_debug(nt, nz, nx, Vx0, Vz0, sigmaxx0, sigmazz0, sigmaxz0, ex_m1_x, ex_m1_z, ex_aux_m2_c, ex_aux_m3_c, ex_aux_m2m3_c); err = cudaGetLastError(); if(cudaSuccess != err){ fprintf(stderr, "Cuda error3: %s.\n", cudaGetErrorString(err)); } //cudaEventRecord(stop, 0); //cudaEventSynchronize(stop); //cudaEventElapsedTime(&elapsedTime, start, stop); //fprintf(stderr,"GPU Computational Elapsed Time: %.4f\n",elapsedTime); }
08683e448a1a980b5a9388834c8eff1a77dc623a.hip
// !!! This is a file automatically generated by hipify!!! /* Compile with: gcc physics.c -o physics -O2 -lm -std=c99 -O2 Optimization -lm Link to math lib -std=c99 Use of for(;;;) with declaration among other things Usage (3D viewer): ./physics > data && ./physicsViewer data Usage (debug): ./physics Jan Mas Rovira Andrs Mingorance Lpez Albert Puente Encinas */ #include <stdio.h> // e.g. printf #include <stdlib.h> // e.g. malloc, RAND_MAX, exit #include <math.h> // e.g. sin, abs #include <sys/time.h> #include <hip/hip_runtime.h> // Algorithm parameters #define N 256*16 // Si incrementa FALLA (+110 MB)! #define ITERATIONS 2000 #define G 9.81 #define BOUNCE_DECAY 0.5 #define GLOBAL_DECAY 0.004 #define POINT_RADIUS 0.3 #define TIME_SPEED 0.0075 #define MAX_TRIES 1e4 #define SEED 27 #define DUMP_RATIO 2 // CUDA Variables #define nThreads 1024 #define nBlocks N/nThreads // c++ style #define bool int #define true 1 #define false 0 #define WALLS true // Timers unsigned long long initialGenTime; unsigned long long interactionsTime; unsigned long long worldInteractionsTime; unsigned long long gravityTime; unsigned long long advanceTime; unsigned long long frameTime; unsigned long long totalTime; inline void tic(unsigned long long* time) { struct timeval t; gettimeofday(&t, NULL); *time = t.tv_sec*1000000 + t.tv_usec - *time; } #define toc tic // Output toggles bool DUMP; typedef struct { float x, y, z; } Vector; typedef struct { float x, y, z; // Position Vector velocity; // Velocity } Point; typedef struct { Point points[N]; } PointSet; void checkCudaError(char msg[]) { hipError_t error; error = hipGetLastError(); if (error) { printf("Error: %s: %s\n", msg, hipGetErrorString(error)); exit(1); } } inline float dist(Point* a, Point* b) { return sqrt(pow(a->x - b->x, 2)+pow(a->y - b->y, 2)+pow(a->z - b->z, 2)); } __device__ inline float gpu_dist(Point* a, Point* b) { return sqrt(pow(a->x - b->x, 2)+pow(a->y - b->y, 2)+pow(a->z - b->z, 2)); } __device__ inline float distNext(Point* a, Point* b) { return sqrt( pow(a->x + a->velocity.x*TIME_SPEED - (b->x + b->velocity.x*TIME_SPEED), 2)+ pow(a->y + a->velocity.y*TIME_SPEED - (b->y + b->velocity.y*TIME_SPEED), 2)+ pow(a->z + a->velocity.z*TIME_SPEED - (b->z + b->velocity.z*TIME_SPEED), 2)); } bool collides(Point* p, PointSet* PS, int from, int to) { for (int i = from; i < to; ++i) { if (dist(p, &PS->points[i]) < POINT_RADIUS*2) { return true; } } return false; } __device__ Vector diffVector(Point* a, Point* b) { Vector v; v.x = a->x - b->x; v.y = a->y - b->y; v.z = a->z - b->z; return v; } __device__ inline float dotProduct(Vector a, Vector b) { return a.x*b.x + a.y*b.y + a.z*b.z; } __global__ void kernel_interaction(PointSet* P, PointSet* Q) { int index = blockIdx.x * blockDim.x + threadIdx.x; int j = 1 + floor(-0.5 + sqrt(0.25 + 2 * index)); int triangularNumber = j * (j - 1) / 2; int i = index - triangularNumber; Point* a = &P->points[i]; Point* b = &P->points[j]; float distance = gpu_dist(a, b); if (distance > 2*POINT_RADIUS + 0.05) return; if (distance == 0) return; // AVOID NAN, PROVISIONAL if (distance < distNext(a, b)) return; Point* aq = &Q->points[i]; Point* bq = &Q->points[j]; // Get the components of the velocity vectors which are parallel to the collision. // The perpendicular component remains the same for both fish Vector collision = diffVector(a, b); // //distance = 2*POINT_RADIUS; collision.x /= distance; collision.y /= distance; collision.z /= distance; float aci = dotProduct(collision, a->velocity); float bci = dotProduct(collision, b->velocity); // Replace the collision velocity components with the new ones atomicAdd(&aq->velocity.x, (bci - aci) * collision.x); atomicAdd(&aq->velocity.y, (bci - aci) * collision.y); atomicAdd(&aq->velocity.z, (bci - aci) * collision.z); atomicAdd(&bq->velocity.x, (aci - bci) * collision.x); atomicAdd(&bq->velocity.y, (aci - bci) * collision.y); atomicAdd(&bq->velocity.z, (aci - bci) * collision.z); } void computeInteraction(PointSet* gpu_P, PointSet* gpu_Q) { /* * (n*(n-1))/2 elements * because we are emulating the following loop * * for (int i = 0; i < N; ++i) * for (int j = i + 1; j < N; ++j) * kernel_interaction(i, j); */ // nThreads is 1024 int nElem = (N*(N-1))/2; int nElemBlocks = nElem/nThreads; hipLaunchKernelGGL(( kernel_interaction), dim3(nElemBlocks), dim3(nThreads), 0, 0, gpu_P, gpu_Q); checkCudaError((char *) "kernel call in interaction"); hipDeviceSynchronize(); } __global__ void kernel_gravity(PointSet* P) { int id = blockIdx.x * blockDim.x + threadIdx.x; P->points[id].velocity.y -= G*TIME_SPEED; } void applyGravity(PointSet* gpu_P) { hipLaunchKernelGGL(( kernel_gravity), dim3(nBlocks), dim3(nThreads), 0, 0, gpu_P); checkCudaError((char *) "kernel call in applyGravity"); hipDeviceSynchronize(); } __global__ void kernel_advance(PointSet* P, PointSet* Q) { int id = blockIdx.x * blockDim.x + threadIdx.x; Point* p = &P->points[id]; p->x += p->velocity.x*TIME_SPEED; p->y += p->velocity.y*TIME_SPEED; p->z += p->velocity.z*TIME_SPEED; p->velocity.x *= (1-GLOBAL_DECAY); p->velocity.y *= (1-GLOBAL_DECAY); p->velocity.z *= (1-GLOBAL_DECAY); Q->points[id] = *p; } void advanceAndCopy(PointSet* gpu_P, PointSet* gpu_Q) { hipLaunchKernelGGL(( kernel_advance), dim3(nBlocks), dim3(nThreads), 0, 0, gpu_P, gpu_Q); checkCudaError((char *) "kernel call in advance"); hipDeviceSynchronize(); } __device__ inline void ifelse(bool condition, float* dest, float a, float b) { *dest = condition*a + !condition*b; } __global__ void kernel_world(PointSet* P) { int id = blockIdx.x * blockDim.x + threadIdx.x; Point* p = &P->points[id]; if (p->y < POINT_RADIUS) { p->y = POINT_RADIUS; p->velocity.y = abs(p->velocity.y) * (1.0 - BOUNCE_DECAY); } if (WALLS) { // 4 walls x = -10, 10 and z = -10, 10 if (p->x < -10.0 + POINT_RADIUS) { p->x = -10 + POINT_RADIUS; p->velocity.x = abs(p->velocity.x) * (1.0 - BOUNCE_DECAY); } else if (p->x > 10.0 - POINT_RADIUS) { p->x = 10 - POINT_RADIUS; p->velocity.x = -abs(p->velocity.x) * (1.0 - BOUNCE_DECAY); } if (p->z < -10.0 + POINT_RADIUS) { p->z = -10 + POINT_RADIUS; p->velocity.z = abs(p->velocity.z) * (1.0 - BOUNCE_DECAY); } else if (p->z > 10.0 - POINT_RADIUS) { p->z = 10 - POINT_RADIUS; p->velocity.z = -abs(p->velocity.z) * (1.0 - BOUNCE_DECAY); } } } void computeInteractionWorld(PointSet* gpu_P) { hipLaunchKernelGGL(( kernel_world), dim3(nBlocks), dim3(nThreads), 0, 0, gpu_P); checkCudaError((char *) "kernel call in interactionWorld"); hipDeviceSynchronize(); } void computePhysics(PointSet* gpu_P, PointSet* gpu_Q) { tic(&gravityTime); applyGravity(gpu_Q); toc(&gravityTime); tic(&worldInteractionsTime); computeInteractionWorld(gpu_Q); tic(&worldInteractionsTime); tic(&interactionsTime); computeInteraction(gpu_P, gpu_Q); tic(&interactionsTime); tic(&advanceTime); advanceAndCopy(gpu_Q, gpu_P); toc(&advanceTime); } void generateInitialConfiguration(PointSet* gpu_P, PointSet* gpu_Q) { tic(&initialGenTime); PointSet* P = (PointSet*) malloc(sizeof(PointSet)); for (int i = 0; i < N; ++i) { Point* p = &P->points[i]; p->x = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; p->y = 80.0*(float)rand()/(float)(RAND_MAX) + 1.0; p->z = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; p->velocity.x = 0.0; p->velocity.y = -3.5; p->velocity.z = 0.0; int tests = 0; while (tests < MAX_TRIES && collides(p, P, 0, i)) { p->x = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; p->y = 80.0*(float)rand()/(float)(RAND_MAX) + 1.0; p->z = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; ++tests; } if (tests == MAX_TRIES) { printf("Error during the generation of the initial conf.\n"); exit(1); } } hipMemcpy(gpu_P, P, sizeof(PointSet), hipMemcpyHostToDevice); checkCudaError((char *) "host -> gpu_P"); hipMemcpy(gpu_Q, P, sizeof(PointSet), hipMemcpyHostToDevice); checkCudaError((char *) "host -> gpu_Q"); hipDeviceSynchronize(); toc(&initialGenTime); } void DUMPInitialParams() { printf("%i %i %f\n", N, ITERATIONS/DUMP_RATIO, POINT_RADIUS); } __global__ void kernel_print(PointSet* P) { int id = blockIdx.x * blockDim.x + threadIdx.x; printf("%f %f %f\n", P->points[id].x, P->points[id].y, P->points[id].z); } void dump(PointSet* gpu_P) { hipLaunchKernelGGL(( kernel_print), dim3(nBlocks), dim3(nThreads), 0, 0, gpu_P); checkCudaError((char *) "kernel call in interaction"); hipDeviceSynchronize(); } void initTimes() { initialGenTime = 0; interactionsTime = 0; worldInteractionsTime = 0; gravityTime = 0; advanceTime = 0; frameTime = 0; totalTime = 0; } void printTimes() { printf("CUDA physics algorithm has finished:\n"); printf(" Init gen: %f s.\n", (double)initialGenTime/1000000); printf(" Interactions: %f s.\n", (double)interactionsTime/1000000); printf(" World int.: %f s.\n", (double)worldInteractionsTime/1000000); printf(" Gravity: %f s.\n", (double)gravityTime/1000000); printf(" Advance: %f s.\n", (double)advanceTime/1000000); // printf(" Avg. frame: %f s.\n", (double)frameTime/(ITERATIONS*1000000)); printf(" Total time: %f s.\n", (double)totalTime/1000000); } void sequentialPhysics() { DUMPInitialParams(); PointSet* gpu_P; PointSet* gpu_Q; hipMalloc((void **) &gpu_P, sizeof(PointSet)); checkCudaError((char *) "hipMalloc of P"); hipMalloc((void **) &gpu_Q, sizeof(PointSet)); checkCudaError((char *) "hipMalloc of Q"); tic(&totalTime); srand(SEED); generateInitialConfiguration(gpu_P, gpu_Q); // *CPU_P = *gpu_P = *gpu_Q for (int i = 0; i < ITERATIONS; ++i) { tic(&frameTime); computePhysics(gpu_P, gpu_Q); if (DUMP) { if (i%DUMP_RATIO == 0) dump(gpu_P); } else printf("IT %i\n", i); toc(&frameTime); } toc(&totalTime); if (!DUMP) printTimes(); } int main(int argc, char** argv) { DUMP = (argc == 1); sequentialPhysics(); return 0; }
08683e448a1a980b5a9388834c8eff1a77dc623a.cu
/* Compile with: gcc physics.c -o physics -O2 -lm -std=c99 -O2 Optimization -lm Link to math lib -std=c99 Use of for(;;;) with declaration among other things Usage (3D viewer): ./physics > data && ./physicsViewer data Usage (debug): ./physics Jan Mas Rovira Andrés Mingorance López Albert Puente Encinas */ #include <stdio.h> // e.g. printf #include <stdlib.h> // e.g. malloc, RAND_MAX, exit #include <math.h> // e.g. sin, abs #include <sys/time.h> #include <cuda.h> // Algorithm parameters #define N 256*16 // Si incrementa FALLA (+110 MB)! #define ITERATIONS 2000 #define G 9.81 #define BOUNCE_DECAY 0.5 #define GLOBAL_DECAY 0.004 #define POINT_RADIUS 0.3 #define TIME_SPEED 0.0075 #define MAX_TRIES 1e4 #define SEED 27 #define DUMP_RATIO 2 // CUDA Variables #define nThreads 1024 #define nBlocks N/nThreads // c++ style #define bool int #define true 1 #define false 0 #define WALLS true // Timers unsigned long long initialGenTime; unsigned long long interactionsTime; unsigned long long worldInteractionsTime; unsigned long long gravityTime; unsigned long long advanceTime; unsigned long long frameTime; unsigned long long totalTime; inline void tic(unsigned long long* time) { struct timeval t; gettimeofday(&t, NULL); *time = t.tv_sec*1000000 + t.tv_usec - *time; } #define toc tic // Output toggles bool DUMP; typedef struct { float x, y, z; } Vector; typedef struct { float x, y, z; // Position Vector velocity; // Velocity } Point; typedef struct { Point points[N]; } PointSet; void checkCudaError(char msg[]) { cudaError_t error; error = cudaGetLastError(); if (error) { printf("Error: %s: %s\n", msg, cudaGetErrorString(error)); exit(1); } } inline float dist(Point* a, Point* b) { return sqrt(pow(a->x - b->x, 2)+pow(a->y - b->y, 2)+pow(a->z - b->z, 2)); } __device__ inline float gpu_dist(Point* a, Point* b) { return sqrt(pow(a->x - b->x, 2)+pow(a->y - b->y, 2)+pow(a->z - b->z, 2)); } __device__ inline float distNext(Point* a, Point* b) { return sqrt( pow(a->x + a->velocity.x*TIME_SPEED - (b->x + b->velocity.x*TIME_SPEED), 2)+ pow(a->y + a->velocity.y*TIME_SPEED - (b->y + b->velocity.y*TIME_SPEED), 2)+ pow(a->z + a->velocity.z*TIME_SPEED - (b->z + b->velocity.z*TIME_SPEED), 2)); } bool collides(Point* p, PointSet* PS, int from, int to) { for (int i = from; i < to; ++i) { if (dist(p, &PS->points[i]) < POINT_RADIUS*2) { return true; } } return false; } __device__ Vector diffVector(Point* a, Point* b) { Vector v; v.x = a->x - b->x; v.y = a->y - b->y; v.z = a->z - b->z; return v; } __device__ inline float dotProduct(Vector a, Vector b) { return a.x*b.x + a.y*b.y + a.z*b.z; } __global__ void kernel_interaction(PointSet* P, PointSet* Q) { int index = blockIdx.x * blockDim.x + threadIdx.x; int j = 1 + floor(-0.5 + sqrt(0.25 + 2 * index)); int triangularNumber = j * (j - 1) / 2; int i = index - triangularNumber; Point* a = &P->points[i]; Point* b = &P->points[j]; float distance = gpu_dist(a, b); if (distance > 2*POINT_RADIUS + 0.05) return; if (distance == 0) return; // AVOID NAN, PROVISIONAL if (distance < distNext(a, b)) return; Point* aq = &Q->points[i]; Point* bq = &Q->points[j]; // Get the components of the velocity vectors which are parallel to the collision. // The perpendicular component remains the same for both fish Vector collision = diffVector(a, b); // //distance = 2*POINT_RADIUS; collision.x /= distance; collision.y /= distance; collision.z /= distance; float aci = dotProduct(collision, a->velocity); float bci = dotProduct(collision, b->velocity); // Replace the collision velocity components with the new ones atomicAdd(&aq->velocity.x, (bci - aci) * collision.x); atomicAdd(&aq->velocity.y, (bci - aci) * collision.y); atomicAdd(&aq->velocity.z, (bci - aci) * collision.z); atomicAdd(&bq->velocity.x, (aci - bci) * collision.x); atomicAdd(&bq->velocity.y, (aci - bci) * collision.y); atomicAdd(&bq->velocity.z, (aci - bci) * collision.z); } void computeInteraction(PointSet* gpu_P, PointSet* gpu_Q) { /* * (n*(n-1))/2 elements * because we are emulating the following loop * * for (int i = 0; i < N; ++i) * for (int j = i + 1; j < N; ++j) * kernel_interaction(i, j); */ // nThreads is 1024 int nElem = (N*(N-1))/2; int nElemBlocks = nElem/nThreads; kernel_interaction<<<nElemBlocks, nThreads>>>(gpu_P, gpu_Q); checkCudaError((char *) "kernel call in interaction"); cudaDeviceSynchronize(); } __global__ void kernel_gravity(PointSet* P) { int id = blockIdx.x * blockDim.x + threadIdx.x; P->points[id].velocity.y -= G*TIME_SPEED; } void applyGravity(PointSet* gpu_P) { kernel_gravity<<<nBlocks, nThreads>>>(gpu_P); checkCudaError((char *) "kernel call in applyGravity"); cudaDeviceSynchronize(); } __global__ void kernel_advance(PointSet* P, PointSet* Q) { int id = blockIdx.x * blockDim.x + threadIdx.x; Point* p = &P->points[id]; p->x += p->velocity.x*TIME_SPEED; p->y += p->velocity.y*TIME_SPEED; p->z += p->velocity.z*TIME_SPEED; p->velocity.x *= (1-GLOBAL_DECAY); p->velocity.y *= (1-GLOBAL_DECAY); p->velocity.z *= (1-GLOBAL_DECAY); Q->points[id] = *p; } void advanceAndCopy(PointSet* gpu_P, PointSet* gpu_Q) { kernel_advance<<<nBlocks, nThreads>>>(gpu_P, gpu_Q); checkCudaError((char *) "kernel call in advance"); cudaDeviceSynchronize(); } __device__ inline void ifelse(bool condition, float* dest, float a, float b) { *dest = condition*a + !condition*b; } __global__ void kernel_world(PointSet* P) { int id = blockIdx.x * blockDim.x + threadIdx.x; Point* p = &P->points[id]; if (p->y < POINT_RADIUS) { p->y = POINT_RADIUS; p->velocity.y = abs(p->velocity.y) * (1.0 - BOUNCE_DECAY); } if (WALLS) { // 4 walls x = -10, 10 and z = -10, 10 if (p->x < -10.0 + POINT_RADIUS) { p->x = -10 + POINT_RADIUS; p->velocity.x = abs(p->velocity.x) * (1.0 - BOUNCE_DECAY); } else if (p->x > 10.0 - POINT_RADIUS) { p->x = 10 - POINT_RADIUS; p->velocity.x = -abs(p->velocity.x) * (1.0 - BOUNCE_DECAY); } if (p->z < -10.0 + POINT_RADIUS) { p->z = -10 + POINT_RADIUS; p->velocity.z = abs(p->velocity.z) * (1.0 - BOUNCE_DECAY); } else if (p->z > 10.0 - POINT_RADIUS) { p->z = 10 - POINT_RADIUS; p->velocity.z = -abs(p->velocity.z) * (1.0 - BOUNCE_DECAY); } } } void computeInteractionWorld(PointSet* gpu_P) { kernel_world<<<nBlocks, nThreads>>>(gpu_P); checkCudaError((char *) "kernel call in interactionWorld"); cudaDeviceSynchronize(); } void computePhysics(PointSet* gpu_P, PointSet* gpu_Q) { tic(&gravityTime); applyGravity(gpu_Q); toc(&gravityTime); tic(&worldInteractionsTime); computeInteractionWorld(gpu_Q); tic(&worldInteractionsTime); tic(&interactionsTime); computeInteraction(gpu_P, gpu_Q); tic(&interactionsTime); tic(&advanceTime); advanceAndCopy(gpu_Q, gpu_P); toc(&advanceTime); } void generateInitialConfiguration(PointSet* gpu_P, PointSet* gpu_Q) { tic(&initialGenTime); PointSet* P = (PointSet*) malloc(sizeof(PointSet)); for (int i = 0; i < N; ++i) { Point* p = &P->points[i]; p->x = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; p->y = 80.0*(float)rand()/(float)(RAND_MAX) + 1.0; p->z = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; p->velocity.x = 0.0; p->velocity.y = -3.5; p->velocity.z = 0.0; int tests = 0; while (tests < MAX_TRIES && collides(p, P, 0, i)) { p->x = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; p->y = 80.0*(float)rand()/(float)(RAND_MAX) + 1.0; p->z = 12.0*(float)rand()/(float)(RAND_MAX) - 6.0; ++tests; } if (tests == MAX_TRIES) { printf("Error during the generation of the initial conf.\n"); exit(1); } } cudaMemcpy(gpu_P, P, sizeof(PointSet), cudaMemcpyHostToDevice); checkCudaError((char *) "host -> gpu_P"); cudaMemcpy(gpu_Q, P, sizeof(PointSet), cudaMemcpyHostToDevice); checkCudaError((char *) "host -> gpu_Q"); cudaDeviceSynchronize(); toc(&initialGenTime); } void DUMPInitialParams() { printf("%i %i %f\n", N, ITERATIONS/DUMP_RATIO, POINT_RADIUS); } __global__ void kernel_print(PointSet* P) { int id = blockIdx.x * blockDim.x + threadIdx.x; printf("%f %f %f\n", P->points[id].x, P->points[id].y, P->points[id].z); } void dump(PointSet* gpu_P) { kernel_print<<<nBlocks, nThreads>>>(gpu_P); checkCudaError((char *) "kernel call in interaction"); cudaDeviceSynchronize(); } void initTimes() { initialGenTime = 0; interactionsTime = 0; worldInteractionsTime = 0; gravityTime = 0; advanceTime = 0; frameTime = 0; totalTime = 0; } void printTimes() { printf("CUDA physics algorithm has finished:\n"); printf(" Init gen: %f s.\n", (double)initialGenTime/1000000); printf(" Interactions: %f s.\n", (double)interactionsTime/1000000); printf(" World int.: %f s.\n", (double)worldInteractionsTime/1000000); printf(" Gravity: %f s.\n", (double)gravityTime/1000000); printf(" Advance: %f s.\n", (double)advanceTime/1000000); // printf(" Avg. frame: %f s.\n", (double)frameTime/(ITERATIONS*1000000)); printf(" Total time: %f s.\n", (double)totalTime/1000000); } void sequentialPhysics() { DUMPInitialParams(); PointSet* gpu_P; PointSet* gpu_Q; cudaMalloc((void **) &gpu_P, sizeof(PointSet)); checkCudaError((char *) "cudaMalloc of P"); cudaMalloc((void **) &gpu_Q, sizeof(PointSet)); checkCudaError((char *) "cudaMalloc of Q"); tic(&totalTime); srand(SEED); generateInitialConfiguration(gpu_P, gpu_Q); // *CPU_P = *gpu_P = *gpu_Q for (int i = 0; i < ITERATIONS; ++i) { tic(&frameTime); computePhysics(gpu_P, gpu_Q); if (DUMP) { if (i%DUMP_RATIO == 0) dump(gpu_P); } else printf("IT %i\n", i); toc(&frameTime); } toc(&totalTime); if (!DUMP) printTimes(); } int main(int argc, char** argv) { DUMP = (argc == 1); sequentialPhysics(); return 0; }
8e8b6460f1f263d01f8aa1606ca4b8f346b1f1b5.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" // Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. #include <ATen/ATen.h> #include <ATen/hip/HIPContext.h> #include <ATen/hip/impl/HIPGuardImplMasqueradingAsCUDA.h> #include <float.h> #include <math.h> #include <thrust/tuple.h> #include <cstdio> #include <tuple> #include "rasterize_points/bitmask.cuh" #include "rasterize_points/rasterization_utils.cuh" #include "utils/float_math.cuh" #include "utils/geometry_utils.cuh" namespace { // A structure for holding details about a pixel. struct Pixel { float z; int64_t idx; // idx of face float dist; // abs distance of pixel to face float3 bary; }; __device__ bool operator<(const Pixel& a, const Pixel& b) { return a.z < b.z; } __device__ float FloatMin3(const float p1, const float p2, const float p3) { return fminf(p1, fminf(p2, p3)); } __device__ float FloatMax3(const float p1, const float p2, const float p3) { return fmaxf(p1, fmaxf(p2, p3)); } // Get the xyz coordinates of the three vertices for the face given by the // index face_idx into face_verts. __device__ thrust::tuple<float3, float3, float3> GetSingleFaceVerts( const float* face_verts, int face_idx) { const float x0 = face_verts[face_idx * 9 + 0]; const float y0 = face_verts[face_idx * 9 + 1]; const float z0 = face_verts[face_idx * 9 + 2]; const float x1 = face_verts[face_idx * 9 + 3]; const float y1 = face_verts[face_idx * 9 + 4]; const float z1 = face_verts[face_idx * 9 + 5]; const float x2 = face_verts[face_idx * 9 + 6]; const float y2 = face_verts[face_idx * 9 + 7]; const float z2 = face_verts[face_idx * 9 + 8]; const float3 v0xyz = make_float3(x0, y0, z0); const float3 v1xyz = make_float3(x1, y1, z1); const float3 v2xyz = make_float3(x2, y2, z2); return thrust::make_tuple(v0xyz, v1xyz, v2xyz); } // Get the min/max x/y/z values for the face given by vertices v0, v1, v2. __device__ thrust::tuple<float2, float2, float2> GetFaceBoundingBox(float3 v0, float3 v1, float3 v2) { const float xmin = FloatMin3(v0.x, v1.x, v2.x); const float ymin = FloatMin3(v0.y, v1.y, v2.y); const float zmin = FloatMin3(v0.z, v1.z, v2.z); const float xmax = FloatMax3(v0.x, v1.x, v2.x); const float ymax = FloatMax3(v0.y, v1.y, v2.y); const float zmax = FloatMax3(v0.z, v1.z, v2.z); return thrust::make_tuple( make_float2(xmin, xmax), make_float2(ymin, ymax), make_float2(zmin, zmax)); } // Check if the point (px, py) lies outside the face bounding box face_bbox. // Return true if the point is outside. __device__ bool CheckPointOutsideBoundingBox( float3 v0, float3 v1, float3 v2, float blur_radius, float2 pxy) { const auto bbox = GetFaceBoundingBox(v0, v1, v2); const float2 xlims = thrust::get<0>(bbox); const float2 ylims = thrust::get<1>(bbox); const float2 zlims = thrust::get<2>(bbox); const float x_min = xlims.x - blur_radius; const float y_min = ylims.x - blur_radius; const float x_max = xlims.y + blur_radius; const float y_max = ylims.y + blur_radius; // Faces with at least one vertex behind the camera won't render correctly // and should be removed or clipped before calling the rasterizer const bool z_invalid = zlims.x < kEpsilon; // Check if the current point is oustside the triangle bounding box. return ( pxy.x > x_max || pxy.x < x_min || pxy.y > y_max || pxy.y < y_min || z_invalid); } // This function checks if a pixel given by xy location pxy lies within the // face with index face_idx in face_verts. One of the inputs is a list (q) // which contains Pixel structs with the indices of the faces which intersect // with this pixel sorted by closest z distance. If the point pxy lies in the // face, the list (q) is updated and re-orderered in place. In addition // the auxillary variables q_size, q_max_z and q_max_idx are also modified. // This code is shared between RasterizeMeshesNaiveCudaKernel and // RasterizeMeshesFineCudaKernel. template <typename FaceQ> __device__ void CheckPixelInsideFace( const float* face_verts, // (F, 3, 3) const int64_t* clipped_faces_neighbor_idx, // (F,) const int face_idx, int& q_size, float& q_max_z, int& q_max_idx, FaceQ& q, const float blur_radius, const float2 pxy, // Coordinates of the pixel const int K, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces) { const auto v012 = GetSingleFaceVerts(face_verts, face_idx); const float3 v0 = thrust::get<0>(v012); const float3 v1 = thrust::get<1>(v012); const float3 v2 = thrust::get<2>(v012); // Only need xy for barycentric coordinates and distance calculations. const float2 v0xy = make_float2(v0.x, v0.y); const float2 v1xy = make_float2(v1.x, v1.y); const float2 v2xy = make_float2(v2.x, v2.y); // Perform checks and skip if: // 1. the face is behind the camera // 2. the face is facing away from the camera // 3. the face has very small face area // 4. the pixel is outside the face bbox const float zmax = FloatMax3(v0.z, v1.z, v2.z); const bool outside_bbox = CheckPointOutsideBoundingBox( v0, v1, v2, sqrt(blur_radius), pxy); // use sqrt of blur for bbox const float face_area = EdgeFunctionForward(v0xy, v1xy, v2xy); // Check if the face is visible to the camera. const bool back_face = face_area < 0.0; const bool zero_face_area = (face_area <= kEpsilon && face_area >= -1.0f * kEpsilon); if (zmax < 0 || cull_backfaces && back_face || outside_bbox || zero_face_area) { return; } // Calculate barycentric coords and euclidean dist to triangle. const float3 p_bary0 = BarycentricCoordsForward(pxy, v0xy, v1xy, v2xy); const float3 p_bary = !perspective_correct ? p_bary0 : BarycentricPerspectiveCorrectionForward(p_bary0, v0.z, v1.z, v2.z); const float3 p_bary_clip = !clip_barycentric_coords ? p_bary : BarycentricClipForward(p_bary); const float pz = p_bary_clip.x * v0.z + p_bary_clip.y * v1.z + p_bary_clip.z * v2.z; if (pz < 0) { return; // Face is behind the image plane. } // Get abs squared distance const float dist = PointTriangleDistanceForward(pxy, v0xy, v1xy, v2xy); // Use the unclipped bary coordinates to determine if the point is inside the // face. const bool inside = p_bary.x > 0.0f && p_bary.y > 0.0f && p_bary.z > 0.0f; const float signed_dist = inside ? -dist : dist; // Check if pixel is outside blur region if (!inside && dist >= blur_radius) { return; } // Handle the case where a face (f) partially behind the image plane is // clipped to a quadrilateral and then split into two faces (t1, t2). In this // case we: // 1. Find the index of the neighboring face (e.g. for t1 need index of t2) // 2. Check if the neighboring face (t2) is already in the top K faces // 3. If yes, compare the distance of the pixel to t1 with the distance to t2. // 4. If dist_t1 < dist_t2, overwrite the values for t2 in the top K faces. const int neighbor_idx = clipped_faces_neighbor_idx[face_idx]; int neighbor_idx_top_k = -1; // Check if neighboring face is already in the top K. // -1 is the fill value in clipped_faces_neighbor_idx if (neighbor_idx != -1) { // Only need to loop until q_size. for (int i = 0; i < q_size; i++) { if (q[i].idx == neighbor_idx) { neighbor_idx_top_k = i; break; } } } // If neighbor idx is not -1 then it is in the top K struct. if (neighbor_idx_top_k != -1) { // If dist of current face is less than neighbor then overwrite the // neighbor face values in the top K struct. float neighbor_dist = abs(q[neighbor_idx_top_k].dist); if (dist < neighbor_dist) { // Overwrite the neighbor face values q[neighbor_idx_top_k] = {pz, face_idx, signed_dist, p_bary_clip}; // If pz > q_max then overwrite the max values and index of the max. // q_size stays the same. if (pz > q_max_z) { q_max_z = pz; q_max_idx = neighbor_idx_top_k; } } } else { // Handle as a normal face if (q_size < K) { // Just insert it. q[q_size] = {pz, face_idx, signed_dist, p_bary_clip}; if (pz > q_max_z) { q_max_z = pz; q_max_idx = q_size; } q_size++; } else if (pz < q_max_z) { // Overwrite the old max, and find the new max. q[q_max_idx] = {pz, face_idx, signed_dist, p_bary_clip}; q_max_z = pz; for (int i = 0; i < K; i++) { if (q[i].z > q_max_z) { q_max_z = q[i].z; q_max_idx = i; } } } } } } // namespace // **************************************************************************** // * NAIVE RASTERIZATION * // **************************************************************************** __global__ void RasterizeMeshesNaiveCudaKernel( const float* face_verts, const int64_t* mesh_to_face_first_idx, const int64_t* num_faces_per_mesh, const int64_t* clipped_faces_neighbor_idx, const float blur_radius, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces, const int N, const int H, const int W, const int K, int64_t* face_idxs, float* zbuf, float* pix_dists, float* bary) { // Simple version: One thread per output pixel int num_threads = gridDim.x * blockDim.x; int tid = blockDim.x * blockIdx.x + threadIdx.x; for (int i = tid; i < N * H * W; i += num_threads) { // Convert linear index to 3D index const int n = i / (H * W); // batch index. const int pix_idx = i % (H * W); // Reverse ordering of X and Y axes const int yi = H - 1 - pix_idx / W; const int xi = W - 1 - pix_idx % W; // screen coordinates to ndc coordiantes of pixel. const float xf = PixToNonSquareNdc(xi, W, H); const float yf = PixToNonSquareNdc(yi, H, W); const float2 pxy = make_float2(xf, yf); // For keeping track of the K closest points we want a data structure // that (1) gives O(1) access to the closest point for easy comparisons, // and (2) allows insertion of new elements. In the CPU version we use // std::priority_queue; then (2) is O(log K). We can't use STL // containers in CUDA; we could roll our own max heap in an array, but // that would likely have a lot of warp divergence so we do something // simpler instead: keep the elements in an unsorted array, but keep // track of the max value and the index of the max value. Then (1) is // still O(1) time, while (2) is O(K) with a clean loop. Since K <= 8 // this should be fast enough for our purposes. Pixel q[kMaxPointsPerPixel]; int q_size = 0; float q_max_z = -1000; int q_max_idx = -1; // Using the batch index of the thread get the start and stop // indices for the faces. const int64_t face_start_idx = mesh_to_face_first_idx[n]; const int64_t face_stop_idx = face_start_idx + num_faces_per_mesh[n]; // Loop through the faces in the mesh. for (int f = face_start_idx; f < face_stop_idx; ++f) { // Check if the pixel pxy is inside the face bounding box and if it is, // update q, q_size, q_max_z and q_max_idx in place. CheckPixelInsideFace( face_verts, clipped_faces_neighbor_idx, f, q_size, q_max_z, q_max_idx, q, blur_radius, pxy, K, perspective_correct, clip_barycentric_coords, cull_backfaces); } // TODO: make sorting an option as only top k is needed, not sorted values. BubbleSort(q, q_size); int idx = n * H * W * K + pix_idx * K; for (int k = 0; k < q_size; ++k) { face_idxs[idx + k] = q[k].idx; zbuf[idx + k] = q[k].z; pix_dists[idx + k] = q[k].dist; bary[(idx + k) * 3 + 0] = q[k].bary.x; bary[(idx + k) * 3 + 1] = q[k].bary.y; bary[(idx + k) * 3 + 2] = q[k].bary.z; } } } std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> RasterizeMeshesNaiveCuda( const at::Tensor& face_verts, const at::Tensor& mesh_to_faces_packed_first_idx, const at::Tensor& num_faces_per_mesh, const at::Tensor& clipped_faces_neighbor_idx, const std::tuple<int, int> image_size, const float blur_radius, const int num_closest, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces) { TORCH_CHECK( face_verts.ndimension() == 3 && face_verts.size(1) == 3 && face_verts.size(2) == 3, "face_verts must have dimensions (num_faces, 3, 3)"); TORCH_CHECK( num_faces_per_mesh.size(0) == mesh_to_faces_packed_first_idx.size(0), "num_faces_per_mesh must have save size first dimension as mesh_to_faces_packed_first_idx"); TORCH_CHECK( clipped_faces_neighbor_idx.size(0) == face_verts.size(0), "clipped_faces_neighbor_idx must have save size first dimension as face_verts"); if (num_closest > kMaxPointsPerPixel) { std::stringstream ss; ss << "Must have points_per_pixel <= " << kMaxPointsPerPixel; AT_ERROR(ss.str()); } // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, mesh_to_faces_packed_first_idx_t{ mesh_to_faces_packed_first_idx, "mesh_to_faces_packed_first_idx", 2}, num_faces_per_mesh_t{num_faces_per_mesh, "num_faces_per_mesh", 3}, clipped_faces_neighbor_idx_t{ clipped_faces_neighbor_idx, "clipped_faces_neighbor_idx", 4}; at::CheckedFrom c = "RasterizeMeshesNaiveCuda"; at::checkAllSameGPU( c, {face_verts_t, mesh_to_faces_packed_first_idx_t, num_faces_per_mesh_t, clipped_faces_neighbor_idx_t}); // Set the device for the kernel launch based on the device of the input at::hip::HIPGuardMasqueradingAsCUDA device_guard(face_verts.device()); hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA(); const int N = num_faces_per_mesh.size(0); // batch size. const int H = std::get<0>(image_size); const int W = std::get<1>(image_size); const int K = num_closest; auto long_opts = num_faces_per_mesh.options().dtype(at::kLong); auto float_opts = face_verts.options().dtype(at::kFloat); at::Tensor face_idxs = at::full({N, H, W, K}, -1, long_opts); at::Tensor zbuf = at::full({N, H, W, K}, -1, float_opts); at::Tensor pix_dists = at::full({N, H, W, K}, -1, float_opts); at::Tensor bary = at::full({N, H, W, K, 3}, -1, float_opts); if (face_idxs.numel() == 0) { AT_CUDA_CHECK(hipGetLastError()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); } const size_t blocks = 1024; const size_t threads = 64; hipLaunchKernelGGL(( RasterizeMeshesNaiveCudaKernel), dim3(blocks), dim3(threads), 0, stream, face_verts.contiguous().data_ptr<float>(), mesh_to_faces_packed_first_idx.contiguous().data_ptr<int64_t>(), num_faces_per_mesh.contiguous().data_ptr<int64_t>(), clipped_faces_neighbor_idx.contiguous().data_ptr<int64_t>(), blur_radius, perspective_correct, clip_barycentric_coords, cull_backfaces, N, H, W, K, face_idxs.data_ptr<int64_t>(), zbuf.data_ptr<float>(), pix_dists.data_ptr<float>(), bary.data_ptr<float>()); AT_CUDA_CHECK(hipGetLastError()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); } // **************************************************************************** // * BACKWARD PASS * // **************************************************************************** // TODO: benchmark parallelizing over faces_verts instead of over pixels. __global__ void RasterizeMeshesBackwardCudaKernel( const float* face_verts, // (F, 3, 3) const int64_t* pix_to_face, // (N, H, W, K) const bool perspective_correct, const bool clip_barycentric_coords, const int N, const int H, const int W, const int K, const float* grad_zbuf, // (N, H, W, K) const float* grad_bary, // (N, H, W, K, 3) const float* grad_dists, // (N, H, W, K) float* grad_face_verts) { // (F, 3, 3) // Parallelize over each pixel in images of // size H * W, for each image in the batch of size N. const int num_threads = gridDim.x * blockDim.x; const int tid = blockIdx.x * blockDim.x + threadIdx.x; for (int t_i = tid; t_i < N * H * W; t_i += num_threads) { // Convert linear index to 3D index const int n = t_i / (H * W); // batch index. const int pix_idx = t_i % (H * W); // Reverse ordering of X and Y axes. const int yi = H - 1 - pix_idx / W; const int xi = W - 1 - pix_idx % W; const float xf = PixToNonSquareNdc(xi, W, H); const float yf = PixToNonSquareNdc(yi, H, W); const float2 pxy = make_float2(xf, yf); // Loop over all the faces for this pixel. for (int k = 0; k < K; k++) { // Index into (N, H, W, K, :) grad tensors // pixel index + top k index int i = n * H * W * K + pix_idx * K + k; const int f = pix_to_face[i]; if (f < 0) { continue; // padded face. } // Get xyz coordinates of the three face vertices. const auto v012 = GetSingleFaceVerts(face_verts, f); const float3 v0 = thrust::get<0>(v012); const float3 v1 = thrust::get<1>(v012); const float3 v2 = thrust::get<2>(v012); // Only neex xy for barycentric coordinate and distance calculations. const float2 v0xy = make_float2(v0.x, v0.y); const float2 v1xy = make_float2(v1.x, v1.y); const float2 v2xy = make_float2(v2.x, v2.y); // Get upstream gradients for the face. const float grad_dist_upstream = grad_dists[i]; const float grad_zbuf_upstream = grad_zbuf[i]; const float grad_bary_upstream_w0 = grad_bary[i * 3 + 0]; const float grad_bary_upstream_w1 = grad_bary[i * 3 + 1]; const float grad_bary_upstream_w2 = grad_bary[i * 3 + 2]; const float3 grad_bary_upstream = make_float3( grad_bary_upstream_w0, grad_bary_upstream_w1, grad_bary_upstream_w2); const float3 b_w = BarycentricCoordsForward(pxy, v0xy, v1xy, v2xy); const float3 b_pp = !perspective_correct ? b_w : BarycentricPerspectiveCorrectionForward(b_w, v0.z, v1.z, v2.z); const float3 b_w_clip = !clip_barycentric_coords ? b_pp : BarycentricClipForward(b_pp); const bool inside = b_pp.x > 0.0f && b_pp.y > 0.0f && b_pp.z > 0.0f; const float sign = inside ? -1.0f : 1.0f; auto grad_dist_f = PointTriangleDistanceBackward( pxy, v0xy, v1xy, v2xy, sign * grad_dist_upstream); const float2 ddist_d_v0 = thrust::get<1>(grad_dist_f); const float2 ddist_d_v1 = thrust::get<2>(grad_dist_f); const float2 ddist_d_v2 = thrust::get<3>(grad_dist_f); // Upstream gradient for barycentric coords from zbuf calculation: // zbuf = bary_w0 * z0 + bary_w1 * z1 + bary_w2 * z2 // Therefore // d_zbuf/d_bary_w0 = z0 // d_zbuf/d_bary_w1 = z1 // d_zbuf/d_bary_w2 = z2 const float3 d_zbuf_d_bwclip = make_float3(v0.z, v1.z, v2.z); // Total upstream barycentric gradients are the sum of // external upstream gradients and contribution from zbuf. const float3 grad_bary_f_sum = (grad_bary_upstream + grad_zbuf_upstream * d_zbuf_d_bwclip); float3 grad_bary0 = grad_bary_f_sum; if (clip_barycentric_coords) { grad_bary0 = BarycentricClipBackward(b_w, grad_bary_f_sum); } float dz0_persp = 0.0f, dz1_persp = 0.0f, dz2_persp = 0.0f; if (perspective_correct) { auto perspective_grads = BarycentricPerspectiveCorrectionBackward( b_w, v0.z, v1.z, v2.z, grad_bary0); grad_bary0 = thrust::get<0>(perspective_grads); dz0_persp = thrust::get<1>(perspective_grads); dz1_persp = thrust::get<2>(perspective_grads); dz2_persp = thrust::get<3>(perspective_grads); } auto grad_bary_f = BarycentricCoordsBackward(pxy, v0xy, v1xy, v2xy, grad_bary0); const float2 dbary_d_v0 = thrust::get<1>(grad_bary_f); const float2 dbary_d_v1 = thrust::get<2>(grad_bary_f); const float2 dbary_d_v2 = thrust::get<3>(grad_bary_f); atomicAdd(grad_face_verts + f * 9 + 0, dbary_d_v0.x + ddist_d_v0.x); atomicAdd(grad_face_verts + f * 9 + 1, dbary_d_v0.y + ddist_d_v0.y); atomicAdd( grad_face_verts + f * 9 + 2, grad_zbuf_upstream * b_w_clip.x + dz0_persp); atomicAdd(grad_face_verts + f * 9 + 3, dbary_d_v1.x + ddist_d_v1.x); atomicAdd(grad_face_verts + f * 9 + 4, dbary_d_v1.y + ddist_d_v1.y); atomicAdd( grad_face_verts + f * 9 + 5, grad_zbuf_upstream * b_w_clip.y + dz1_persp); atomicAdd(grad_face_verts + f * 9 + 6, dbary_d_v2.x + ddist_d_v2.x); atomicAdd(grad_face_verts + f * 9 + 7, dbary_d_v2.y + ddist_d_v2.y); atomicAdd( grad_face_verts + f * 9 + 8, grad_zbuf_upstream * b_w_clip.z + dz2_persp); } } } at::Tensor RasterizeMeshesBackwardCuda( const at::Tensor& face_verts, // (F, 3, 3) const at::Tensor& pix_to_face, // (N, H, W, K) const at::Tensor& grad_zbuf, // (N, H, W, K) const at::Tensor& grad_bary, // (N, H, W, K, 3) const at::Tensor& grad_dists, // (N, H, W, K) const bool perspective_correct, const bool clip_barycentric_coords) { // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, pix_to_face_t{pix_to_face, "pix_to_face", 2}, grad_zbuf_t{grad_zbuf, "grad_zbuf", 3}, grad_bary_t{grad_bary, "grad_bary", 4}, grad_dists_t{grad_dists, "grad_dists", 5}; at::CheckedFrom c = "RasterizeMeshesBackwardCuda"; at::checkAllSameGPU( c, {face_verts_t, pix_to_face_t, grad_zbuf_t, grad_bary_t, grad_dists_t}); at::checkAllSameType( c, {face_verts_t, grad_zbuf_t, grad_bary_t, grad_dists_t}); // Set the device for the kernel launch based on the device of the input at::hip::HIPGuardMasqueradingAsCUDA device_guard(face_verts.device()); hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA(); const int F = face_verts.size(0); const int N = pix_to_face.size(0); const int H = pix_to_face.size(1); const int W = pix_to_face.size(2); const int K = pix_to_face.size(3); at::Tensor grad_face_verts = at::zeros({F, 3, 3}, face_verts.options()); if (grad_face_verts.numel() == 0) { AT_CUDA_CHECK(hipGetLastError()); return grad_face_verts; } const size_t blocks = 1024; const size_t threads = 64; hipLaunchKernelGGL(( RasterizeMeshesBackwardCudaKernel), dim3(blocks), dim3(threads), 0, stream, face_verts.contiguous().data_ptr<float>(), pix_to_face.contiguous().data_ptr<int64_t>(), perspective_correct, clip_barycentric_coords, N, H, W, K, grad_zbuf.contiguous().data_ptr<float>(), grad_bary.contiguous().data_ptr<float>(), grad_dists.contiguous().data_ptr<float>(), grad_face_verts.data_ptr<float>()); AT_CUDA_CHECK(hipGetLastError()); return grad_face_verts; } // **************************************************************************** // * COARSE RASTERIZATION * // **************************************************************************** __global__ void RasterizeMeshesCoarseCudaKernel( const float* face_verts, const int64_t* mesh_to_face_first_idx, const int64_t* num_faces_per_mesh, const float blur_radius, const int N, const int F, const int H, const int W, const int bin_size, const int chunk_size, const int max_faces_per_bin, int* faces_per_bin, int* bin_faces) { extern __shared__ char sbuf[]; const int M = max_faces_per_bin; // Integer divide round up const int num_bins_x = 1 + (W - 1) / bin_size; const int num_bins_y = 1 + (H - 1) / bin_size; // NDC range depends on the ratio of W/H // The shorter side from (H, W) is given an NDC range of 2.0 and // the other side is scaled by the ratio of H:W. const float NDC_x_half_range = NonSquareNdcRange(W, H) / 2.0f; const float NDC_y_half_range = NonSquareNdcRange(H, W) / 2.0f; // Size of half a pixel in NDC units is the NDC half range // divided by the corresponding image dimension const float half_pix_x = NDC_x_half_range / W; const float half_pix_y = NDC_y_half_range / H; // This is a boolean array of shape (num_bins_y, num_bins_x, chunk_size) // stored in shared memory that will track whether each point in the chunk // falls into each bin of the image. BitMask binmask((unsigned int*)sbuf, num_bins_y, num_bins_x, chunk_size); // Have each block handle a chunk of faces const int chunks_per_batch = 1 + (F - 1) / chunk_size; const int num_chunks = N * chunks_per_batch; for (int chunk = blockIdx.x; chunk < num_chunks; chunk += gridDim.x) { const int batch_idx = chunk / chunks_per_batch; // batch index const int chunk_idx = chunk % chunks_per_batch; const int face_start_idx = chunk_idx * chunk_size; binmask.block_clear(); const int64_t mesh_face_start_idx = mesh_to_face_first_idx[batch_idx]; const int64_t mesh_face_stop_idx = mesh_face_start_idx + num_faces_per_mesh[batch_idx]; // Have each thread handle a different face within the chunk for (int f = threadIdx.x; f < chunk_size; f += blockDim.x) { const int f_idx = face_start_idx + f; // Check if face index corresponds to the mesh in the batch given by // batch_idx if (f_idx >= mesh_face_stop_idx || f_idx < mesh_face_start_idx) { continue; } // Get xyz coordinates of the three face vertices. const auto v012 = GetSingleFaceVerts(face_verts, f_idx); const float3 v0 = thrust::get<0>(v012); const float3 v1 = thrust::get<1>(v012); const float3 v2 = thrust::get<2>(v012); // Compute screen-space bbox for the triangle expanded by blur. float xmin = FloatMin3(v0.x, v1.x, v2.x) - sqrt(blur_radius); float ymin = FloatMin3(v0.y, v1.y, v2.y) - sqrt(blur_radius); float xmax = FloatMax3(v0.x, v1.x, v2.x) + sqrt(blur_radius); float ymax = FloatMax3(v0.y, v1.y, v2.y) + sqrt(blur_radius); float zmin = FloatMin3(v0.z, v1.z, v2.z); // Faces with at least one vertex behind the camera won't render // correctly and should be removed or clipped before calling the // rasterizer if (zmin < kEpsilon) { continue; } // Brute-force search over all bins; TODO(T54294966) something smarter. for (int by = 0; by < num_bins_y; ++by) { // Y coordinate of the top and bottom of the bin. // PixToNdc gives the location of the center of each pixel, so we // need to add/subtract a half pixel to get the true extent of the bin. // Reverse ordering of Y axis so that +Y is upwards in the image. const float bin_y_min = PixToNonSquareNdc(by * bin_size, H, W) - half_pix_y; const float bin_y_max = PixToNonSquareNdc((by + 1) * bin_size - 1, H, W) + half_pix_y; const bool y_overlap = (ymin <= bin_y_max) && (bin_y_min < ymax); for (int bx = 0; bx < num_bins_x; ++bx) { // X coordinate of the left and right of the bin. // Reverse ordering of x axis so that +X is left. const float bin_x_max = PixToNonSquareNdc((bx + 1) * bin_size - 1, W, H) + half_pix_x; const float bin_x_min = PixToNonSquareNdc(bx * bin_size, W, H) - half_pix_x; const bool x_overlap = (xmin <= bin_x_max) && (bin_x_min < xmax); if (y_overlap && x_overlap) { binmask.set(by, bx, f); } } } } __syncthreads(); // Now we have processed every face in the current chunk. We need to // count the number of faces in each bin so we can write the indices // out to global memory. We have each thread handle a different bin. for (int byx = threadIdx.x; byx < num_bins_y * num_bins_x; byx += blockDim.x) { const int by = byx / num_bins_x; const int bx = byx % num_bins_x; const int count = binmask.count(by, bx); const int faces_per_bin_idx = batch_idx * num_bins_y * num_bins_x + by * num_bins_x + bx; // This atomically increments the (global) number of faces found // in the current bin, and gets the previous value of the counter; // this effectively allocates space in the bin_faces array for the // faces in the current chunk that fall into this bin. const int start = atomicAdd(faces_per_bin + faces_per_bin_idx, count); // Now loop over the binmask and write the active bits for this bin // out to bin_faces. int next_idx = batch_idx * num_bins_y * num_bins_x * M + by * num_bins_x * M + bx * M + start; for (int f = 0; f < chunk_size; ++f) { if (binmask.get(by, bx, f)) { // TODO(T54296346) find the correct method for handling errors in // CUDA. Throw an error if num_faces_per_bin > max_faces_per_bin. // Either decrease bin size or increase max_faces_per_bin bin_faces[next_idx] = face_start_idx + f; next_idx++; } } } __syncthreads(); } } at::Tensor RasterizeMeshesCoarseCuda( const at::Tensor& face_verts, const at::Tensor& mesh_to_face_first_idx, const at::Tensor& num_faces_per_mesh, const std::tuple<int, int> image_size, const float blur_radius, const int bin_size, const int max_faces_per_bin) { TORCH_CHECK( face_verts.ndimension() == 3 && face_verts.size(1) == 3 && face_verts.size(2) == 3, "face_verts must have dimensions (num_faces, 3, 3)"); // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, mesh_to_face_first_idx_t{ mesh_to_face_first_idx, "mesh_to_face_first_idx", 2}, num_faces_per_mesh_t{num_faces_per_mesh, "num_faces_per_mesh", 3}; at::CheckedFrom c = "RasterizeMeshesCoarseCuda"; at::checkAllSameGPU( c, {face_verts_t, mesh_to_face_first_idx_t, num_faces_per_mesh_t}); // Set the device for the kernel launch based on the device of the input at::hip::HIPGuardMasqueradingAsCUDA device_guard(face_verts.device()); hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA(); const int H = std::get<0>(image_size); const int W = std::get<1>(image_size); const int F = face_verts.size(0); const int N = num_faces_per_mesh.size(0); const int M = max_faces_per_bin; // Integer divide round up. const int num_bins_y = 1 + (H - 1) / bin_size; const int num_bins_x = 1 + (W - 1) / bin_size; if (num_bins_y >= kMaxItemsPerBin || num_bins_x >= kMaxItemsPerBin) { std::stringstream ss; ss << "In Coarse Rasterizer got num_bins_y: " << num_bins_y << ", num_bins_x: " << num_bins_x << ", " << "; that's too many!"; AT_ERROR(ss.str()); } auto opts = num_faces_per_mesh.options().dtype(at::kInt); at::Tensor faces_per_bin = at::zeros({N, num_bins_y, num_bins_x}, opts); at::Tensor bin_faces = at::full({N, num_bins_y, num_bins_x, M}, -1, opts); if (bin_faces.numel() == 0) { AT_CUDA_CHECK(hipGetLastError()); return bin_faces; } const int chunk_size = 512; const size_t shared_size = num_bins_y * num_bins_x * chunk_size / 8; const size_t blocks = 64; const size_t threads = 512; hipLaunchKernelGGL(( RasterizeMeshesCoarseCudaKernel), dim3(blocks), dim3(threads), shared_size, stream, face_verts.contiguous().data_ptr<float>(), mesh_to_face_first_idx.contiguous().data_ptr<int64_t>(), num_faces_per_mesh.contiguous().data_ptr<int64_t>(), blur_radius, N, F, H, W, bin_size, chunk_size, M, faces_per_bin.data_ptr<int32_t>(), bin_faces.data_ptr<int32_t>()); AT_CUDA_CHECK(hipGetLastError()); return bin_faces; } // **************************************************************************** // * FINE RASTERIZATION * // **************************************************************************** __global__ void RasterizeMeshesFineCudaKernel( const float* face_verts, // (F, 3, 3) const int32_t* bin_faces, // (N, BH, BW, T) const int64_t* clipped_faces_neighbor_idx, // (F,) const float blur_radius, const int bin_size, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces, const int N, const int BH, const int BW, const int M, const int H, const int W, const int K, int64_t* face_idxs, // (N, H, W, K) float* zbuf, // (N, H, W, K) float* pix_dists, // (N, H, W, K) float* bary // (N, H, W, K, 3) ) { // This can be more than H * W if H or W are not divisible by bin_size. int num_pixels = N * BH * BW * bin_size * bin_size; int num_threads = gridDim.x * blockDim.x; int tid = blockIdx.x * blockDim.x + threadIdx.x; for (int pid = tid; pid < num_pixels; pid += num_threads) { // Convert linear index into bin and pixel indices. We make the within // block pixel ids move the fastest, so that adjacent threads will fall // into the same bin; this should give them coalesced memory reads when // they read from faces and bin_faces. int i = pid; const int n = i / (BH * BW * bin_size * bin_size); i %= BH * BW * bin_size * bin_size; // bin index y const int by = i / (BW * bin_size * bin_size); i %= BW * bin_size * bin_size; // bin index y const int bx = i / (bin_size * bin_size); // pixel within the bin i %= bin_size * bin_size; // Pixel x, y indices const int yi = i / bin_size + by * bin_size; const int xi = i % bin_size + bx * bin_size; if (yi >= H || xi >= W) continue; const float xf = PixToNonSquareNdc(xi, W, H); const float yf = PixToNonSquareNdc(yi, H, W); const float2 pxy = make_float2(xf, yf); // This part looks like the naive rasterization kernel, except we use // bin_faces to only look at a subset of faces already known to fall // in this bin. TODO abstract out this logic into some data structure // that is shared by both kernels? Pixel q[kMaxPointsPerPixel]; int q_size = 0; float q_max_z = -1000; int q_max_idx = -1; for (int m = 0; m < M; m++) { const int f = bin_faces[n * BH * BW * M + by * BW * M + bx * M + m]; if (f < 0) { continue; // bin_faces uses -1 as a sentinal value. } // Check if the pixel pxy is inside the face bounding box and if it is, // update q, q_size, q_max_z and q_max_idx in place. CheckPixelInsideFace( face_verts, clipped_faces_neighbor_idx, f, q_size, q_max_z, q_max_idx, q, blur_radius, pxy, K, perspective_correct, clip_barycentric_coords, cull_backfaces); } // Now we've looked at all the faces for this bin, so we can write // output for the current pixel. // TODO: make sorting an option as only top k is needed, not sorted values. BubbleSort(q, q_size); // Reverse ordering of the X and Y axis so that // in the image +Y is pointing up and +X is pointing left. const int yidx = H - 1 - yi; const int xidx = W - 1 - xi; const int pix_idx = n * H * W * K + yidx * W * K + xidx * K; for (int k = 0; k < q_size; k++) { face_idxs[pix_idx + k] = q[k].idx; zbuf[pix_idx + k] = q[k].z; pix_dists[pix_idx + k] = q[k].dist; bary[(pix_idx + k) * 3 + 0] = q[k].bary.x; bary[(pix_idx + k) * 3 + 1] = q[k].bary.y; bary[(pix_idx + k) * 3 + 2] = q[k].bary.z; } } } std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> RasterizeMeshesFineCuda( const at::Tensor& face_verts, const at::Tensor& bin_faces, const at::Tensor& clipped_faces_neighbor_idx, const std::tuple<int, int> image_size, const float blur_radius, const int bin_size, const int faces_per_pixel, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces) { TORCH_CHECK( face_verts.ndimension() == 3 && face_verts.size(1) == 3 && face_verts.size(2) == 3, "face_verts must have dimensions (num_faces, 3, 3)"); TORCH_CHECK(bin_faces.ndimension() == 4, "bin_faces must have 4 dimensions"); TORCH_CHECK( clipped_faces_neighbor_idx.size(0) == face_verts.size(0), "clipped_faces_neighbor_idx must have the same first dimension as face_verts"); // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, bin_faces_t{bin_faces, "bin_faces", 2}, clipped_faces_neighbor_idx_t{ clipped_faces_neighbor_idx, "clipped_faces_neighbor_idx", 3}; at::CheckedFrom c = "RasterizeMeshesFineCuda"; at::checkAllSameGPU( c, {face_verts_t, bin_faces_t, clipped_faces_neighbor_idx_t}); // Set the device for the kernel launch based on the device of the input at::hip::HIPGuardMasqueradingAsCUDA device_guard(face_verts.device()); hipStream_t stream = at::hip::getCurrentHIPStreamMasqueradingAsCUDA(); // bin_faces shape (N, BH, BW, M) const int N = bin_faces.size(0); const int BH = bin_faces.size(1); const int BW = bin_faces.size(2); const int M = bin_faces.size(3); const int K = faces_per_pixel; const int H = std::get<0>(image_size); const int W = std::get<1>(image_size); if (K > kMaxPointsPerPixel) { AT_ERROR("Must have num_closest <= 150"); } auto long_opts = bin_faces.options().dtype(at::kLong); auto float_opts = face_verts.options().dtype(at::kFloat); at::Tensor face_idxs = at::full({N, H, W, K}, -1, long_opts); at::Tensor zbuf = at::full({N, H, W, K}, -1, float_opts); at::Tensor pix_dists = at::full({N, H, W, K}, -1, float_opts); at::Tensor bary = at::full({N, H, W, K, 3}, -1, float_opts); if (face_idxs.numel() == 0) { AT_CUDA_CHECK(hipGetLastError()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); } const size_t blocks = 1024; const size_t threads = 64; hipLaunchKernelGGL(( RasterizeMeshesFineCudaKernel), dim3(blocks), dim3(threads), 0, stream, face_verts.contiguous().data_ptr<float>(), bin_faces.contiguous().data_ptr<int32_t>(), clipped_faces_neighbor_idx.contiguous().data_ptr<int64_t>(), blur_radius, bin_size, perspective_correct, clip_barycentric_coords, cull_backfaces, N, BH, BW, M, H, W, K, face_idxs.data_ptr<int64_t>(), zbuf.data_ptr<float>(), pix_dists.data_ptr<float>(), bary.data_ptr<float>()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); }
8e8b6460f1f263d01f8aa1606ca4b8f346b1f1b5.cu
// Copyright (c) Facebook, Inc. and its affiliates. All rights reserved. #include <ATen/ATen.h> #include <ATen/cuda/CUDAContext.h> #include <c10/cuda/CUDAGuard.h> #include <float.h> #include <math.h> #include <thrust/tuple.h> #include <cstdio> #include <tuple> #include "rasterize_points/bitmask.cuh" #include "rasterize_points/rasterization_utils.cuh" #include "utils/float_math.cuh" #include "utils/geometry_utils.cuh" namespace { // A structure for holding details about a pixel. struct Pixel { float z; int64_t idx; // idx of face float dist; // abs distance of pixel to face float3 bary; }; __device__ bool operator<(const Pixel& a, const Pixel& b) { return a.z < b.z; } __device__ float FloatMin3(const float p1, const float p2, const float p3) { return fminf(p1, fminf(p2, p3)); } __device__ float FloatMax3(const float p1, const float p2, const float p3) { return fmaxf(p1, fmaxf(p2, p3)); } // Get the xyz coordinates of the three vertices for the face given by the // index face_idx into face_verts. __device__ thrust::tuple<float3, float3, float3> GetSingleFaceVerts( const float* face_verts, int face_idx) { const float x0 = face_verts[face_idx * 9 + 0]; const float y0 = face_verts[face_idx * 9 + 1]; const float z0 = face_verts[face_idx * 9 + 2]; const float x1 = face_verts[face_idx * 9 + 3]; const float y1 = face_verts[face_idx * 9 + 4]; const float z1 = face_verts[face_idx * 9 + 5]; const float x2 = face_verts[face_idx * 9 + 6]; const float y2 = face_verts[face_idx * 9 + 7]; const float z2 = face_verts[face_idx * 9 + 8]; const float3 v0xyz = make_float3(x0, y0, z0); const float3 v1xyz = make_float3(x1, y1, z1); const float3 v2xyz = make_float3(x2, y2, z2); return thrust::make_tuple(v0xyz, v1xyz, v2xyz); } // Get the min/max x/y/z values for the face given by vertices v0, v1, v2. __device__ thrust::tuple<float2, float2, float2> GetFaceBoundingBox(float3 v0, float3 v1, float3 v2) { const float xmin = FloatMin3(v0.x, v1.x, v2.x); const float ymin = FloatMin3(v0.y, v1.y, v2.y); const float zmin = FloatMin3(v0.z, v1.z, v2.z); const float xmax = FloatMax3(v0.x, v1.x, v2.x); const float ymax = FloatMax3(v0.y, v1.y, v2.y); const float zmax = FloatMax3(v0.z, v1.z, v2.z); return thrust::make_tuple( make_float2(xmin, xmax), make_float2(ymin, ymax), make_float2(zmin, zmax)); } // Check if the point (px, py) lies outside the face bounding box face_bbox. // Return true if the point is outside. __device__ bool CheckPointOutsideBoundingBox( float3 v0, float3 v1, float3 v2, float blur_radius, float2 pxy) { const auto bbox = GetFaceBoundingBox(v0, v1, v2); const float2 xlims = thrust::get<0>(bbox); const float2 ylims = thrust::get<1>(bbox); const float2 zlims = thrust::get<2>(bbox); const float x_min = xlims.x - blur_radius; const float y_min = ylims.x - blur_radius; const float x_max = xlims.y + blur_radius; const float y_max = ylims.y + blur_radius; // Faces with at least one vertex behind the camera won't render correctly // and should be removed or clipped before calling the rasterizer const bool z_invalid = zlims.x < kEpsilon; // Check if the current point is oustside the triangle bounding box. return ( pxy.x > x_max || pxy.x < x_min || pxy.y > y_max || pxy.y < y_min || z_invalid); } // This function checks if a pixel given by xy location pxy lies within the // face with index face_idx in face_verts. One of the inputs is a list (q) // which contains Pixel structs with the indices of the faces which intersect // with this pixel sorted by closest z distance. If the point pxy lies in the // face, the list (q) is updated and re-orderered in place. In addition // the auxillary variables q_size, q_max_z and q_max_idx are also modified. // This code is shared between RasterizeMeshesNaiveCudaKernel and // RasterizeMeshesFineCudaKernel. template <typename FaceQ> __device__ void CheckPixelInsideFace( const float* face_verts, // (F, 3, 3) const int64_t* clipped_faces_neighbor_idx, // (F,) const int face_idx, int& q_size, float& q_max_z, int& q_max_idx, FaceQ& q, const float blur_radius, const float2 pxy, // Coordinates of the pixel const int K, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces) { const auto v012 = GetSingleFaceVerts(face_verts, face_idx); const float3 v0 = thrust::get<0>(v012); const float3 v1 = thrust::get<1>(v012); const float3 v2 = thrust::get<2>(v012); // Only need xy for barycentric coordinates and distance calculations. const float2 v0xy = make_float2(v0.x, v0.y); const float2 v1xy = make_float2(v1.x, v1.y); const float2 v2xy = make_float2(v2.x, v2.y); // Perform checks and skip if: // 1. the face is behind the camera // 2. the face is facing away from the camera // 3. the face has very small face area // 4. the pixel is outside the face bbox const float zmax = FloatMax3(v0.z, v1.z, v2.z); const bool outside_bbox = CheckPointOutsideBoundingBox( v0, v1, v2, sqrt(blur_radius), pxy); // use sqrt of blur for bbox const float face_area = EdgeFunctionForward(v0xy, v1xy, v2xy); // Check if the face is visible to the camera. const bool back_face = face_area < 0.0; const bool zero_face_area = (face_area <= kEpsilon && face_area >= -1.0f * kEpsilon); if (zmax < 0 || cull_backfaces && back_face || outside_bbox || zero_face_area) { return; } // Calculate barycentric coords and euclidean dist to triangle. const float3 p_bary0 = BarycentricCoordsForward(pxy, v0xy, v1xy, v2xy); const float3 p_bary = !perspective_correct ? p_bary0 : BarycentricPerspectiveCorrectionForward(p_bary0, v0.z, v1.z, v2.z); const float3 p_bary_clip = !clip_barycentric_coords ? p_bary : BarycentricClipForward(p_bary); const float pz = p_bary_clip.x * v0.z + p_bary_clip.y * v1.z + p_bary_clip.z * v2.z; if (pz < 0) { return; // Face is behind the image plane. } // Get abs squared distance const float dist = PointTriangleDistanceForward(pxy, v0xy, v1xy, v2xy); // Use the unclipped bary coordinates to determine if the point is inside the // face. const bool inside = p_bary.x > 0.0f && p_bary.y > 0.0f && p_bary.z > 0.0f; const float signed_dist = inside ? -dist : dist; // Check if pixel is outside blur region if (!inside && dist >= blur_radius) { return; } // Handle the case where a face (f) partially behind the image plane is // clipped to a quadrilateral and then split into two faces (t1, t2). In this // case we: // 1. Find the index of the neighboring face (e.g. for t1 need index of t2) // 2. Check if the neighboring face (t2) is already in the top K faces // 3. If yes, compare the distance of the pixel to t1 with the distance to t2. // 4. If dist_t1 < dist_t2, overwrite the values for t2 in the top K faces. const int neighbor_idx = clipped_faces_neighbor_idx[face_idx]; int neighbor_idx_top_k = -1; // Check if neighboring face is already in the top K. // -1 is the fill value in clipped_faces_neighbor_idx if (neighbor_idx != -1) { // Only need to loop until q_size. for (int i = 0; i < q_size; i++) { if (q[i].idx == neighbor_idx) { neighbor_idx_top_k = i; break; } } } // If neighbor idx is not -1 then it is in the top K struct. if (neighbor_idx_top_k != -1) { // If dist of current face is less than neighbor then overwrite the // neighbor face values in the top K struct. float neighbor_dist = abs(q[neighbor_idx_top_k].dist); if (dist < neighbor_dist) { // Overwrite the neighbor face values q[neighbor_idx_top_k] = {pz, face_idx, signed_dist, p_bary_clip}; // If pz > q_max then overwrite the max values and index of the max. // q_size stays the same. if (pz > q_max_z) { q_max_z = pz; q_max_idx = neighbor_idx_top_k; } } } else { // Handle as a normal face if (q_size < K) { // Just insert it. q[q_size] = {pz, face_idx, signed_dist, p_bary_clip}; if (pz > q_max_z) { q_max_z = pz; q_max_idx = q_size; } q_size++; } else if (pz < q_max_z) { // Overwrite the old max, and find the new max. q[q_max_idx] = {pz, face_idx, signed_dist, p_bary_clip}; q_max_z = pz; for (int i = 0; i < K; i++) { if (q[i].z > q_max_z) { q_max_z = q[i].z; q_max_idx = i; } } } } } } // namespace // **************************************************************************** // * NAIVE RASTERIZATION * // **************************************************************************** __global__ void RasterizeMeshesNaiveCudaKernel( const float* face_verts, const int64_t* mesh_to_face_first_idx, const int64_t* num_faces_per_mesh, const int64_t* clipped_faces_neighbor_idx, const float blur_radius, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces, const int N, const int H, const int W, const int K, int64_t* face_idxs, float* zbuf, float* pix_dists, float* bary) { // Simple version: One thread per output pixel int num_threads = gridDim.x * blockDim.x; int tid = blockDim.x * blockIdx.x + threadIdx.x; for (int i = tid; i < N * H * W; i += num_threads) { // Convert linear index to 3D index const int n = i / (H * W); // batch index. const int pix_idx = i % (H * W); // Reverse ordering of X and Y axes const int yi = H - 1 - pix_idx / W; const int xi = W - 1 - pix_idx % W; // screen coordinates to ndc coordiantes of pixel. const float xf = PixToNonSquareNdc(xi, W, H); const float yf = PixToNonSquareNdc(yi, H, W); const float2 pxy = make_float2(xf, yf); // For keeping track of the K closest points we want a data structure // that (1) gives O(1) access to the closest point for easy comparisons, // and (2) allows insertion of new elements. In the CPU version we use // std::priority_queue; then (2) is O(log K). We can't use STL // containers in CUDA; we could roll our own max heap in an array, but // that would likely have a lot of warp divergence so we do something // simpler instead: keep the elements in an unsorted array, but keep // track of the max value and the index of the max value. Then (1) is // still O(1) time, while (2) is O(K) with a clean loop. Since K <= 8 // this should be fast enough for our purposes. Pixel q[kMaxPointsPerPixel]; int q_size = 0; float q_max_z = -1000; int q_max_idx = -1; // Using the batch index of the thread get the start and stop // indices for the faces. const int64_t face_start_idx = mesh_to_face_first_idx[n]; const int64_t face_stop_idx = face_start_idx + num_faces_per_mesh[n]; // Loop through the faces in the mesh. for (int f = face_start_idx; f < face_stop_idx; ++f) { // Check if the pixel pxy is inside the face bounding box and if it is, // update q, q_size, q_max_z and q_max_idx in place. CheckPixelInsideFace( face_verts, clipped_faces_neighbor_idx, f, q_size, q_max_z, q_max_idx, q, blur_radius, pxy, K, perspective_correct, clip_barycentric_coords, cull_backfaces); } // TODO: make sorting an option as only top k is needed, not sorted values. BubbleSort(q, q_size); int idx = n * H * W * K + pix_idx * K; for (int k = 0; k < q_size; ++k) { face_idxs[idx + k] = q[k].idx; zbuf[idx + k] = q[k].z; pix_dists[idx + k] = q[k].dist; bary[(idx + k) * 3 + 0] = q[k].bary.x; bary[(idx + k) * 3 + 1] = q[k].bary.y; bary[(idx + k) * 3 + 2] = q[k].bary.z; } } } std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> RasterizeMeshesNaiveCuda( const at::Tensor& face_verts, const at::Tensor& mesh_to_faces_packed_first_idx, const at::Tensor& num_faces_per_mesh, const at::Tensor& clipped_faces_neighbor_idx, const std::tuple<int, int> image_size, const float blur_radius, const int num_closest, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces) { TORCH_CHECK( face_verts.ndimension() == 3 && face_verts.size(1) == 3 && face_verts.size(2) == 3, "face_verts must have dimensions (num_faces, 3, 3)"); TORCH_CHECK( num_faces_per_mesh.size(0) == mesh_to_faces_packed_first_idx.size(0), "num_faces_per_mesh must have save size first dimension as mesh_to_faces_packed_first_idx"); TORCH_CHECK( clipped_faces_neighbor_idx.size(0) == face_verts.size(0), "clipped_faces_neighbor_idx must have save size first dimension as face_verts"); if (num_closest > kMaxPointsPerPixel) { std::stringstream ss; ss << "Must have points_per_pixel <= " << kMaxPointsPerPixel; AT_ERROR(ss.str()); } // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, mesh_to_faces_packed_first_idx_t{ mesh_to_faces_packed_first_idx, "mesh_to_faces_packed_first_idx", 2}, num_faces_per_mesh_t{num_faces_per_mesh, "num_faces_per_mesh", 3}, clipped_faces_neighbor_idx_t{ clipped_faces_neighbor_idx, "clipped_faces_neighbor_idx", 4}; at::CheckedFrom c = "RasterizeMeshesNaiveCuda"; at::checkAllSameGPU( c, {face_verts_t, mesh_to_faces_packed_first_idx_t, num_faces_per_mesh_t, clipped_faces_neighbor_idx_t}); // Set the device for the kernel launch based on the device of the input at::cuda::CUDAGuard device_guard(face_verts.device()); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); const int N = num_faces_per_mesh.size(0); // batch size. const int H = std::get<0>(image_size); const int W = std::get<1>(image_size); const int K = num_closest; auto long_opts = num_faces_per_mesh.options().dtype(at::kLong); auto float_opts = face_verts.options().dtype(at::kFloat); at::Tensor face_idxs = at::full({N, H, W, K}, -1, long_opts); at::Tensor zbuf = at::full({N, H, W, K}, -1, float_opts); at::Tensor pix_dists = at::full({N, H, W, K}, -1, float_opts); at::Tensor bary = at::full({N, H, W, K, 3}, -1, float_opts); if (face_idxs.numel() == 0) { AT_CUDA_CHECK(cudaGetLastError()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); } const size_t blocks = 1024; const size_t threads = 64; RasterizeMeshesNaiveCudaKernel<<<blocks, threads, 0, stream>>>( face_verts.contiguous().data_ptr<float>(), mesh_to_faces_packed_first_idx.contiguous().data_ptr<int64_t>(), num_faces_per_mesh.contiguous().data_ptr<int64_t>(), clipped_faces_neighbor_idx.contiguous().data_ptr<int64_t>(), blur_radius, perspective_correct, clip_barycentric_coords, cull_backfaces, N, H, W, K, face_idxs.data_ptr<int64_t>(), zbuf.data_ptr<float>(), pix_dists.data_ptr<float>(), bary.data_ptr<float>()); AT_CUDA_CHECK(cudaGetLastError()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); } // **************************************************************************** // * BACKWARD PASS * // **************************************************************************** // TODO: benchmark parallelizing over faces_verts instead of over pixels. __global__ void RasterizeMeshesBackwardCudaKernel( const float* face_verts, // (F, 3, 3) const int64_t* pix_to_face, // (N, H, W, K) const bool perspective_correct, const bool clip_barycentric_coords, const int N, const int H, const int W, const int K, const float* grad_zbuf, // (N, H, W, K) const float* grad_bary, // (N, H, W, K, 3) const float* grad_dists, // (N, H, W, K) float* grad_face_verts) { // (F, 3, 3) // Parallelize over each pixel in images of // size H * W, for each image in the batch of size N. const int num_threads = gridDim.x * blockDim.x; const int tid = blockIdx.x * blockDim.x + threadIdx.x; for (int t_i = tid; t_i < N * H * W; t_i += num_threads) { // Convert linear index to 3D index const int n = t_i / (H * W); // batch index. const int pix_idx = t_i % (H * W); // Reverse ordering of X and Y axes. const int yi = H - 1 - pix_idx / W; const int xi = W - 1 - pix_idx % W; const float xf = PixToNonSquareNdc(xi, W, H); const float yf = PixToNonSquareNdc(yi, H, W); const float2 pxy = make_float2(xf, yf); // Loop over all the faces for this pixel. for (int k = 0; k < K; k++) { // Index into (N, H, W, K, :) grad tensors // pixel index + top k index int i = n * H * W * K + pix_idx * K + k; const int f = pix_to_face[i]; if (f < 0) { continue; // padded face. } // Get xyz coordinates of the three face vertices. const auto v012 = GetSingleFaceVerts(face_verts, f); const float3 v0 = thrust::get<0>(v012); const float3 v1 = thrust::get<1>(v012); const float3 v2 = thrust::get<2>(v012); // Only neex xy for barycentric coordinate and distance calculations. const float2 v0xy = make_float2(v0.x, v0.y); const float2 v1xy = make_float2(v1.x, v1.y); const float2 v2xy = make_float2(v2.x, v2.y); // Get upstream gradients for the face. const float grad_dist_upstream = grad_dists[i]; const float grad_zbuf_upstream = grad_zbuf[i]; const float grad_bary_upstream_w0 = grad_bary[i * 3 + 0]; const float grad_bary_upstream_w1 = grad_bary[i * 3 + 1]; const float grad_bary_upstream_w2 = grad_bary[i * 3 + 2]; const float3 grad_bary_upstream = make_float3( grad_bary_upstream_w0, grad_bary_upstream_w1, grad_bary_upstream_w2); const float3 b_w = BarycentricCoordsForward(pxy, v0xy, v1xy, v2xy); const float3 b_pp = !perspective_correct ? b_w : BarycentricPerspectiveCorrectionForward(b_w, v0.z, v1.z, v2.z); const float3 b_w_clip = !clip_barycentric_coords ? b_pp : BarycentricClipForward(b_pp); const bool inside = b_pp.x > 0.0f && b_pp.y > 0.0f && b_pp.z > 0.0f; const float sign = inside ? -1.0f : 1.0f; auto grad_dist_f = PointTriangleDistanceBackward( pxy, v0xy, v1xy, v2xy, sign * grad_dist_upstream); const float2 ddist_d_v0 = thrust::get<1>(grad_dist_f); const float2 ddist_d_v1 = thrust::get<2>(grad_dist_f); const float2 ddist_d_v2 = thrust::get<3>(grad_dist_f); // Upstream gradient for barycentric coords from zbuf calculation: // zbuf = bary_w0 * z0 + bary_w1 * z1 + bary_w2 * z2 // Therefore // d_zbuf/d_bary_w0 = z0 // d_zbuf/d_bary_w1 = z1 // d_zbuf/d_bary_w2 = z2 const float3 d_zbuf_d_bwclip = make_float3(v0.z, v1.z, v2.z); // Total upstream barycentric gradients are the sum of // external upstream gradients and contribution from zbuf. const float3 grad_bary_f_sum = (grad_bary_upstream + grad_zbuf_upstream * d_zbuf_d_bwclip); float3 grad_bary0 = grad_bary_f_sum; if (clip_barycentric_coords) { grad_bary0 = BarycentricClipBackward(b_w, grad_bary_f_sum); } float dz0_persp = 0.0f, dz1_persp = 0.0f, dz2_persp = 0.0f; if (perspective_correct) { auto perspective_grads = BarycentricPerspectiveCorrectionBackward( b_w, v0.z, v1.z, v2.z, grad_bary0); grad_bary0 = thrust::get<0>(perspective_grads); dz0_persp = thrust::get<1>(perspective_grads); dz1_persp = thrust::get<2>(perspective_grads); dz2_persp = thrust::get<3>(perspective_grads); } auto grad_bary_f = BarycentricCoordsBackward(pxy, v0xy, v1xy, v2xy, grad_bary0); const float2 dbary_d_v0 = thrust::get<1>(grad_bary_f); const float2 dbary_d_v1 = thrust::get<2>(grad_bary_f); const float2 dbary_d_v2 = thrust::get<3>(grad_bary_f); atomicAdd(grad_face_verts + f * 9 + 0, dbary_d_v0.x + ddist_d_v0.x); atomicAdd(grad_face_verts + f * 9 + 1, dbary_d_v0.y + ddist_d_v0.y); atomicAdd( grad_face_verts + f * 9 + 2, grad_zbuf_upstream * b_w_clip.x + dz0_persp); atomicAdd(grad_face_verts + f * 9 + 3, dbary_d_v1.x + ddist_d_v1.x); atomicAdd(grad_face_verts + f * 9 + 4, dbary_d_v1.y + ddist_d_v1.y); atomicAdd( grad_face_verts + f * 9 + 5, grad_zbuf_upstream * b_w_clip.y + dz1_persp); atomicAdd(grad_face_verts + f * 9 + 6, dbary_d_v2.x + ddist_d_v2.x); atomicAdd(grad_face_verts + f * 9 + 7, dbary_d_v2.y + ddist_d_v2.y); atomicAdd( grad_face_verts + f * 9 + 8, grad_zbuf_upstream * b_w_clip.z + dz2_persp); } } } at::Tensor RasterizeMeshesBackwardCuda( const at::Tensor& face_verts, // (F, 3, 3) const at::Tensor& pix_to_face, // (N, H, W, K) const at::Tensor& grad_zbuf, // (N, H, W, K) const at::Tensor& grad_bary, // (N, H, W, K, 3) const at::Tensor& grad_dists, // (N, H, W, K) const bool perspective_correct, const bool clip_barycentric_coords) { // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, pix_to_face_t{pix_to_face, "pix_to_face", 2}, grad_zbuf_t{grad_zbuf, "grad_zbuf", 3}, grad_bary_t{grad_bary, "grad_bary", 4}, grad_dists_t{grad_dists, "grad_dists", 5}; at::CheckedFrom c = "RasterizeMeshesBackwardCuda"; at::checkAllSameGPU( c, {face_verts_t, pix_to_face_t, grad_zbuf_t, grad_bary_t, grad_dists_t}); at::checkAllSameType( c, {face_verts_t, grad_zbuf_t, grad_bary_t, grad_dists_t}); // Set the device for the kernel launch based on the device of the input at::cuda::CUDAGuard device_guard(face_verts.device()); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); const int F = face_verts.size(0); const int N = pix_to_face.size(0); const int H = pix_to_face.size(1); const int W = pix_to_face.size(2); const int K = pix_to_face.size(3); at::Tensor grad_face_verts = at::zeros({F, 3, 3}, face_verts.options()); if (grad_face_verts.numel() == 0) { AT_CUDA_CHECK(cudaGetLastError()); return grad_face_verts; } const size_t blocks = 1024; const size_t threads = 64; RasterizeMeshesBackwardCudaKernel<<<blocks, threads, 0, stream>>>( face_verts.contiguous().data_ptr<float>(), pix_to_face.contiguous().data_ptr<int64_t>(), perspective_correct, clip_barycentric_coords, N, H, W, K, grad_zbuf.contiguous().data_ptr<float>(), grad_bary.contiguous().data_ptr<float>(), grad_dists.contiguous().data_ptr<float>(), grad_face_verts.data_ptr<float>()); AT_CUDA_CHECK(cudaGetLastError()); return grad_face_verts; } // **************************************************************************** // * COARSE RASTERIZATION * // **************************************************************************** __global__ void RasterizeMeshesCoarseCudaKernel( const float* face_verts, const int64_t* mesh_to_face_first_idx, const int64_t* num_faces_per_mesh, const float blur_radius, const int N, const int F, const int H, const int W, const int bin_size, const int chunk_size, const int max_faces_per_bin, int* faces_per_bin, int* bin_faces) { extern __shared__ char sbuf[]; const int M = max_faces_per_bin; // Integer divide round up const int num_bins_x = 1 + (W - 1) / bin_size; const int num_bins_y = 1 + (H - 1) / bin_size; // NDC range depends on the ratio of W/H // The shorter side from (H, W) is given an NDC range of 2.0 and // the other side is scaled by the ratio of H:W. const float NDC_x_half_range = NonSquareNdcRange(W, H) / 2.0f; const float NDC_y_half_range = NonSquareNdcRange(H, W) / 2.0f; // Size of half a pixel in NDC units is the NDC half range // divided by the corresponding image dimension const float half_pix_x = NDC_x_half_range / W; const float half_pix_y = NDC_y_half_range / H; // This is a boolean array of shape (num_bins_y, num_bins_x, chunk_size) // stored in shared memory that will track whether each point in the chunk // falls into each bin of the image. BitMask binmask((unsigned int*)sbuf, num_bins_y, num_bins_x, chunk_size); // Have each block handle a chunk of faces const int chunks_per_batch = 1 + (F - 1) / chunk_size; const int num_chunks = N * chunks_per_batch; for (int chunk = blockIdx.x; chunk < num_chunks; chunk += gridDim.x) { const int batch_idx = chunk / chunks_per_batch; // batch index const int chunk_idx = chunk % chunks_per_batch; const int face_start_idx = chunk_idx * chunk_size; binmask.block_clear(); const int64_t mesh_face_start_idx = mesh_to_face_first_idx[batch_idx]; const int64_t mesh_face_stop_idx = mesh_face_start_idx + num_faces_per_mesh[batch_idx]; // Have each thread handle a different face within the chunk for (int f = threadIdx.x; f < chunk_size; f += blockDim.x) { const int f_idx = face_start_idx + f; // Check if face index corresponds to the mesh in the batch given by // batch_idx if (f_idx >= mesh_face_stop_idx || f_idx < mesh_face_start_idx) { continue; } // Get xyz coordinates of the three face vertices. const auto v012 = GetSingleFaceVerts(face_verts, f_idx); const float3 v0 = thrust::get<0>(v012); const float3 v1 = thrust::get<1>(v012); const float3 v2 = thrust::get<2>(v012); // Compute screen-space bbox for the triangle expanded by blur. float xmin = FloatMin3(v0.x, v1.x, v2.x) - sqrt(blur_radius); float ymin = FloatMin3(v0.y, v1.y, v2.y) - sqrt(blur_radius); float xmax = FloatMax3(v0.x, v1.x, v2.x) + sqrt(blur_radius); float ymax = FloatMax3(v0.y, v1.y, v2.y) + sqrt(blur_radius); float zmin = FloatMin3(v0.z, v1.z, v2.z); // Faces with at least one vertex behind the camera won't render // correctly and should be removed or clipped before calling the // rasterizer if (zmin < kEpsilon) { continue; } // Brute-force search over all bins; TODO(T54294966) something smarter. for (int by = 0; by < num_bins_y; ++by) { // Y coordinate of the top and bottom of the bin. // PixToNdc gives the location of the center of each pixel, so we // need to add/subtract a half pixel to get the true extent of the bin. // Reverse ordering of Y axis so that +Y is upwards in the image. const float bin_y_min = PixToNonSquareNdc(by * bin_size, H, W) - half_pix_y; const float bin_y_max = PixToNonSquareNdc((by + 1) * bin_size - 1, H, W) + half_pix_y; const bool y_overlap = (ymin <= bin_y_max) && (bin_y_min < ymax); for (int bx = 0; bx < num_bins_x; ++bx) { // X coordinate of the left and right of the bin. // Reverse ordering of x axis so that +X is left. const float bin_x_max = PixToNonSquareNdc((bx + 1) * bin_size - 1, W, H) + half_pix_x; const float bin_x_min = PixToNonSquareNdc(bx * bin_size, W, H) - half_pix_x; const bool x_overlap = (xmin <= bin_x_max) && (bin_x_min < xmax); if (y_overlap && x_overlap) { binmask.set(by, bx, f); } } } } __syncthreads(); // Now we have processed every face in the current chunk. We need to // count the number of faces in each bin so we can write the indices // out to global memory. We have each thread handle a different bin. for (int byx = threadIdx.x; byx < num_bins_y * num_bins_x; byx += blockDim.x) { const int by = byx / num_bins_x; const int bx = byx % num_bins_x; const int count = binmask.count(by, bx); const int faces_per_bin_idx = batch_idx * num_bins_y * num_bins_x + by * num_bins_x + bx; // This atomically increments the (global) number of faces found // in the current bin, and gets the previous value of the counter; // this effectively allocates space in the bin_faces array for the // faces in the current chunk that fall into this bin. const int start = atomicAdd(faces_per_bin + faces_per_bin_idx, count); // Now loop over the binmask and write the active bits for this bin // out to bin_faces. int next_idx = batch_idx * num_bins_y * num_bins_x * M + by * num_bins_x * M + bx * M + start; for (int f = 0; f < chunk_size; ++f) { if (binmask.get(by, bx, f)) { // TODO(T54296346) find the correct method for handling errors in // CUDA. Throw an error if num_faces_per_bin > max_faces_per_bin. // Either decrease bin size or increase max_faces_per_bin bin_faces[next_idx] = face_start_idx + f; next_idx++; } } } __syncthreads(); } } at::Tensor RasterizeMeshesCoarseCuda( const at::Tensor& face_verts, const at::Tensor& mesh_to_face_first_idx, const at::Tensor& num_faces_per_mesh, const std::tuple<int, int> image_size, const float blur_radius, const int bin_size, const int max_faces_per_bin) { TORCH_CHECK( face_verts.ndimension() == 3 && face_verts.size(1) == 3 && face_verts.size(2) == 3, "face_verts must have dimensions (num_faces, 3, 3)"); // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, mesh_to_face_first_idx_t{ mesh_to_face_first_idx, "mesh_to_face_first_idx", 2}, num_faces_per_mesh_t{num_faces_per_mesh, "num_faces_per_mesh", 3}; at::CheckedFrom c = "RasterizeMeshesCoarseCuda"; at::checkAllSameGPU( c, {face_verts_t, mesh_to_face_first_idx_t, num_faces_per_mesh_t}); // Set the device for the kernel launch based on the device of the input at::cuda::CUDAGuard device_guard(face_verts.device()); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); const int H = std::get<0>(image_size); const int W = std::get<1>(image_size); const int F = face_verts.size(0); const int N = num_faces_per_mesh.size(0); const int M = max_faces_per_bin; // Integer divide round up. const int num_bins_y = 1 + (H - 1) / bin_size; const int num_bins_x = 1 + (W - 1) / bin_size; if (num_bins_y >= kMaxItemsPerBin || num_bins_x >= kMaxItemsPerBin) { std::stringstream ss; ss << "In Coarse Rasterizer got num_bins_y: " << num_bins_y << ", num_bins_x: " << num_bins_x << ", " << "; that's too many!"; AT_ERROR(ss.str()); } auto opts = num_faces_per_mesh.options().dtype(at::kInt); at::Tensor faces_per_bin = at::zeros({N, num_bins_y, num_bins_x}, opts); at::Tensor bin_faces = at::full({N, num_bins_y, num_bins_x, M}, -1, opts); if (bin_faces.numel() == 0) { AT_CUDA_CHECK(cudaGetLastError()); return bin_faces; } const int chunk_size = 512; const size_t shared_size = num_bins_y * num_bins_x * chunk_size / 8; const size_t blocks = 64; const size_t threads = 512; RasterizeMeshesCoarseCudaKernel<<<blocks, threads, shared_size, stream>>>( face_verts.contiguous().data_ptr<float>(), mesh_to_face_first_idx.contiguous().data_ptr<int64_t>(), num_faces_per_mesh.contiguous().data_ptr<int64_t>(), blur_radius, N, F, H, W, bin_size, chunk_size, M, faces_per_bin.data_ptr<int32_t>(), bin_faces.data_ptr<int32_t>()); AT_CUDA_CHECK(cudaGetLastError()); return bin_faces; } // **************************************************************************** // * FINE RASTERIZATION * // **************************************************************************** __global__ void RasterizeMeshesFineCudaKernel( const float* face_verts, // (F, 3, 3) const int32_t* bin_faces, // (N, BH, BW, T) const int64_t* clipped_faces_neighbor_idx, // (F,) const float blur_radius, const int bin_size, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces, const int N, const int BH, const int BW, const int M, const int H, const int W, const int K, int64_t* face_idxs, // (N, H, W, K) float* zbuf, // (N, H, W, K) float* pix_dists, // (N, H, W, K) float* bary // (N, H, W, K, 3) ) { // This can be more than H * W if H or W are not divisible by bin_size. int num_pixels = N * BH * BW * bin_size * bin_size; int num_threads = gridDim.x * blockDim.x; int tid = blockIdx.x * blockDim.x + threadIdx.x; for (int pid = tid; pid < num_pixels; pid += num_threads) { // Convert linear index into bin and pixel indices. We make the within // block pixel ids move the fastest, so that adjacent threads will fall // into the same bin; this should give them coalesced memory reads when // they read from faces and bin_faces. int i = pid; const int n = i / (BH * BW * bin_size * bin_size); i %= BH * BW * bin_size * bin_size; // bin index y const int by = i / (BW * bin_size * bin_size); i %= BW * bin_size * bin_size; // bin index y const int bx = i / (bin_size * bin_size); // pixel within the bin i %= bin_size * bin_size; // Pixel x, y indices const int yi = i / bin_size + by * bin_size; const int xi = i % bin_size + bx * bin_size; if (yi >= H || xi >= W) continue; const float xf = PixToNonSquareNdc(xi, W, H); const float yf = PixToNonSquareNdc(yi, H, W); const float2 pxy = make_float2(xf, yf); // This part looks like the naive rasterization kernel, except we use // bin_faces to only look at a subset of faces already known to fall // in this bin. TODO abstract out this logic into some data structure // that is shared by both kernels? Pixel q[kMaxPointsPerPixel]; int q_size = 0; float q_max_z = -1000; int q_max_idx = -1; for (int m = 0; m < M; m++) { const int f = bin_faces[n * BH * BW * M + by * BW * M + bx * M + m]; if (f < 0) { continue; // bin_faces uses -1 as a sentinal value. } // Check if the pixel pxy is inside the face bounding box and if it is, // update q, q_size, q_max_z and q_max_idx in place. CheckPixelInsideFace( face_verts, clipped_faces_neighbor_idx, f, q_size, q_max_z, q_max_idx, q, blur_radius, pxy, K, perspective_correct, clip_barycentric_coords, cull_backfaces); } // Now we've looked at all the faces for this bin, so we can write // output for the current pixel. // TODO: make sorting an option as only top k is needed, not sorted values. BubbleSort(q, q_size); // Reverse ordering of the X and Y axis so that // in the image +Y is pointing up and +X is pointing left. const int yidx = H - 1 - yi; const int xidx = W - 1 - xi; const int pix_idx = n * H * W * K + yidx * W * K + xidx * K; for (int k = 0; k < q_size; k++) { face_idxs[pix_idx + k] = q[k].idx; zbuf[pix_idx + k] = q[k].z; pix_dists[pix_idx + k] = q[k].dist; bary[(pix_idx + k) * 3 + 0] = q[k].bary.x; bary[(pix_idx + k) * 3 + 1] = q[k].bary.y; bary[(pix_idx + k) * 3 + 2] = q[k].bary.z; } } } std::tuple<at::Tensor, at::Tensor, at::Tensor, at::Tensor> RasterizeMeshesFineCuda( const at::Tensor& face_verts, const at::Tensor& bin_faces, const at::Tensor& clipped_faces_neighbor_idx, const std::tuple<int, int> image_size, const float blur_radius, const int bin_size, const int faces_per_pixel, const bool perspective_correct, const bool clip_barycentric_coords, const bool cull_backfaces) { TORCH_CHECK( face_verts.ndimension() == 3 && face_verts.size(1) == 3 && face_verts.size(2) == 3, "face_verts must have dimensions (num_faces, 3, 3)"); TORCH_CHECK(bin_faces.ndimension() == 4, "bin_faces must have 4 dimensions"); TORCH_CHECK( clipped_faces_neighbor_idx.size(0) == face_verts.size(0), "clipped_faces_neighbor_idx must have the same first dimension as face_verts"); // Check inputs are on the same device at::TensorArg face_verts_t{face_verts, "face_verts", 1}, bin_faces_t{bin_faces, "bin_faces", 2}, clipped_faces_neighbor_idx_t{ clipped_faces_neighbor_idx, "clipped_faces_neighbor_idx", 3}; at::CheckedFrom c = "RasterizeMeshesFineCuda"; at::checkAllSameGPU( c, {face_verts_t, bin_faces_t, clipped_faces_neighbor_idx_t}); // Set the device for the kernel launch based on the device of the input at::cuda::CUDAGuard device_guard(face_verts.device()); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); // bin_faces shape (N, BH, BW, M) const int N = bin_faces.size(0); const int BH = bin_faces.size(1); const int BW = bin_faces.size(2); const int M = bin_faces.size(3); const int K = faces_per_pixel; const int H = std::get<0>(image_size); const int W = std::get<1>(image_size); if (K > kMaxPointsPerPixel) { AT_ERROR("Must have num_closest <= 150"); } auto long_opts = bin_faces.options().dtype(at::kLong); auto float_opts = face_verts.options().dtype(at::kFloat); at::Tensor face_idxs = at::full({N, H, W, K}, -1, long_opts); at::Tensor zbuf = at::full({N, H, W, K}, -1, float_opts); at::Tensor pix_dists = at::full({N, H, W, K}, -1, float_opts); at::Tensor bary = at::full({N, H, W, K, 3}, -1, float_opts); if (face_idxs.numel() == 0) { AT_CUDA_CHECK(cudaGetLastError()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); } const size_t blocks = 1024; const size_t threads = 64; RasterizeMeshesFineCudaKernel<<<blocks, threads, 0, stream>>>( face_verts.contiguous().data_ptr<float>(), bin_faces.contiguous().data_ptr<int32_t>(), clipped_faces_neighbor_idx.contiguous().data_ptr<int64_t>(), blur_radius, bin_size, perspective_correct, clip_barycentric_coords, cull_backfaces, N, BH, BW, M, H, W, K, face_idxs.data_ptr<int64_t>(), zbuf.data_ptr<float>(), pix_dists.data_ptr<float>(), bary.data_ptr<float>()); return std::make_tuple(face_idxs, zbuf, bary, pix_dists); }
484a5ebbc338241b051dbe731a5110618d835940.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" /** * Copyright 2022 Huawei Technologies Co., Ltd * * 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 <complex.h> #include "tril_triu_impl.cuh" #include "plugin/device/gpu/kernel/cuda_impl/cuda_ops/complex.h" template <typename R> using Complex = mindspore::utils::Complex<R>; template <typename T> __global__ void Tril(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; output[pos] = row + diagonal >= col ? input[pos] : static_cast<T>(0.0); } return; } template <typename T> __global__ void Triu(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; output[pos] = row + diagonal <= col ? input[pos] : static_cast<T>(0.0); } return; } template <> __global__ void Triu(const size_t size, const Complex<float> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<float> *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; float rs_real = row + diagonal <= col ? input[pos].real() : static_cast<float>(0.0); float rs_imag = row + diagonal <= col ? input[pos].imag() : static_cast<float>(0.0); output[pos].real(rs_real); output[pos].imag(rs_imag); } return; } template <> __global__ void Triu(const size_t size, const Complex<double> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<double> *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; double rs_real = row + diagonal <= col ? input[pos].real() : static_cast<double>(0.0); double rs_imag = row + diagonal <= col ? input[pos].imag() : static_cast<double>(0.0); output[pos].real(rs_real); output[pos].imag(rs_imag); } return; } template <typename T> void CalTril(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output, const uint32_t &device_id, hipStream_t cuda_stream) { hipLaunchKernelGGL(( Tril), dim3(CUDA_BLOCKS(device_id, size)), dim3(CUDA_THREADS(device_id)), 0, cuda_stream, size, input, diagonal, matrix_row, matrix_col, output); return; } template <typename T> void CalTriu(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output, const uint32_t &device_id, hipStream_t cuda_stream) { hipLaunchKernelGGL(( Triu), dim3(CUDA_BLOCKS(device_id, size)), dim3(CUDA_THREADS(device_id)), 0, cuda_stream, size, input, diagonal, matrix_row, matrix_col, output); return; } template CUDA_LIB_EXPORT void CalTril<uint8_t>(const size_t size, const uint8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint8_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<uint16_t>(const size_t size, const uint16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint16_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<uint32_t>(const size_t size, const uint32_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint32_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<uint64_t>(const size_t size, const uint64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint64_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int8_t>(const size_t size, const int8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int8_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int16_t>(const size_t size, const int16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int16_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int>(const size_t size, const int *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int64_t>(const size_t size, const int64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int64_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<half>(const size_t size, const half *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, half *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<float>(const size_t size, const float *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, float *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<double>(const size_t size, const double *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, double *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<bool>(const size_t size, const bool *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, bool *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint8_t>(const size_t size, const uint8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint8_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint16_t>(const size_t size, const uint16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint16_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint32_t>(const size_t size, const uint32_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint32_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint64_t>(const size_t size, const uint64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint64_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int8_t>(const size_t size, const int8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int8_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int16_t>(const size_t size, const int16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int16_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int>(const size_t size, const int *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int64_t>(const size_t size, const int64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int64_t *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<half>(const size_t size, const half *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, half *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<float>(const size_t size, const float *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, float *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<double>(const size_t size, const double *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, double *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<Complex<float>>(const size_t size, const Complex<float> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<float> *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<Complex<double>>(const size_t size, const Complex<double> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<double> *output, const uint32_t &device_id, hipStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<bool>(const size_t size, const bool *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, bool *output, const uint32_t &device_id, hipStream_t cuda_stream);
484a5ebbc338241b051dbe731a5110618d835940.cu
/** * Copyright 2022 Huawei Technologies Co., Ltd * * 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 <complex.h> #include "tril_triu_impl.cuh" #include "plugin/device/gpu/kernel/cuda_impl/cuda_ops/complex.h" template <typename R> using Complex = mindspore::utils::Complex<R>; template <typename T> __global__ void Tril(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; output[pos] = row + diagonal >= col ? input[pos] : static_cast<T>(0.0); } return; } template <typename T> __global__ void Triu(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; output[pos] = row + diagonal <= col ? input[pos] : static_cast<T>(0.0); } return; } template <> __global__ void Triu(const size_t size, const Complex<float> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<float> *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; float rs_real = row + diagonal <= col ? input[pos].real() : static_cast<float>(0.0); float rs_imag = row + diagonal <= col ? input[pos].imag() : static_cast<float>(0.0); output[pos].real(rs_real); output[pos].imag(rs_imag); } return; } template <> __global__ void Triu(const size_t size, const Complex<double> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<double> *output) { for (size_t pos = blockIdx.x * blockDim.x + threadIdx.x; pos < size; pos += blockDim.x * gridDim.x) { int matrix_size = matrix_row * matrix_col; int row = pos % matrix_size / matrix_col; int col = pos % matrix_size % matrix_col; double rs_real = row + diagonal <= col ? input[pos].real() : static_cast<double>(0.0); double rs_imag = row + diagonal <= col ? input[pos].imag() : static_cast<double>(0.0); output[pos].real(rs_real); output[pos].imag(rs_imag); } return; } template <typename T> void CalTril(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output, const uint32_t &device_id, cudaStream_t cuda_stream) { Tril<<<CUDA_BLOCKS(device_id, size), CUDA_THREADS(device_id), 0, cuda_stream>>>(size, input, diagonal, matrix_row, matrix_col, output); return; } template <typename T> void CalTriu(const size_t size, const T *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, T *output, const uint32_t &device_id, cudaStream_t cuda_stream) { Triu<<<CUDA_BLOCKS(device_id, size), CUDA_THREADS(device_id), 0, cuda_stream>>>(size, input, diagonal, matrix_row, matrix_col, output); return; } template CUDA_LIB_EXPORT void CalTril<uint8_t>(const size_t size, const uint8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint8_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<uint16_t>(const size_t size, const uint16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint16_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<uint32_t>(const size_t size, const uint32_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint32_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<uint64_t>(const size_t size, const uint64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint64_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int8_t>(const size_t size, const int8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int8_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int16_t>(const size_t size, const int16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int16_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int>(const size_t size, const int *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<int64_t>(const size_t size, const int64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int64_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<half>(const size_t size, const half *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, half *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<float>(const size_t size, const float *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, float *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<double>(const size_t size, const double *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, double *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTril<bool>(const size_t size, const bool *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, bool *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint8_t>(const size_t size, const uint8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint8_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint16_t>(const size_t size, const uint16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint16_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint32_t>(const size_t size, const uint32_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint32_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<uint64_t>(const size_t size, const uint64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, uint64_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int8_t>(const size_t size, const int8_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int8_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int16_t>(const size_t size, const int16_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int16_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int>(const size_t size, const int *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<int64_t>(const size_t size, const int64_t *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, int64_t *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<half>(const size_t size, const half *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, half *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<float>(const size_t size, const float *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, float *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<double>(const size_t size, const double *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, double *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<Complex<float>>(const size_t size, const Complex<float> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<float> *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<Complex<double>>(const size_t size, const Complex<double> *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, Complex<double> *output, const uint32_t &device_id, cudaStream_t cuda_stream); template CUDA_LIB_EXPORT void CalTriu<bool>(const size_t size, const bool *input, const int diagonal, const int64_t matrix_row, const int64_t matrix_col, bool *output, const uint32_t &device_id, cudaStream_t cuda_stream);
d44548cd0ff0fbad02dc1b18a50c73897d5de5ef.hip
// !!! This is a file automatically generated by hipify!!! #include "hip/hip_runtime.h" #include "includes.h" /* we need these includes for CUDA's random number stuff */ using namespace std; #define MAX 26 //int a[1000]; //array of all possible password characters int b[1000]; //array of attempted password cracks unsigned long long tries = 0; char alphabet[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; size_t result = 1000 * sizeof(float); int *a = (int *) malloc(result); __global__ void parallel_passwordCrack(int length,int*d_output,int *a) { int idx = blockIdx.x * blockDim.x + threadIdx.x; bool cracked = false; char alphabetTable[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; int newB[1000]; __shared__ int nIter; __shared__ int idT; __shared__ long totalAttempt; do{ if(idx == 0){ nIter = 0; totalAttempt = 0; } newB[0]++; for(int i =0; i<length; i++){ if (newB[i] >= 26 + alphabetTable[i]){ newB[i] -= 26; newB[i+1]++; }else break; } cracked=true; for(int k=0; k<length; k++) { if(newB[k]!=a[k]){ cracked=false; break; }else { cracked = true; } } if(cracked && nIter == 0){ idT = idx; break; } else if(nIter){ break; } totalAttempt++; }while(!cracked || !nIter); if(idx == idT){ for(int i = 0; i< length; i++){ d_output[i] = newB[i]; } } }
d44548cd0ff0fbad02dc1b18a50c73897d5de5ef.cu
#include "includes.h" /* we need these includes for CUDA's random number stuff */ using namespace std; #define MAX 26 //int a[1000]; //array of all possible password characters int b[1000]; //array of attempted password cracks unsigned long long tries = 0; char alphabet[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; size_t result = 1000 * sizeof(float); int *a = (int *) malloc(result); __global__ void parallel_passwordCrack(int length,int*d_output,int *a) { int idx = blockIdx.x * blockDim.x + threadIdx.x; bool cracked = false; char alphabetTable[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z' }; int newB[1000]; __shared__ int nIter; __shared__ int idT; __shared__ long totalAttempt; do{ if(idx == 0){ nIter = 0; totalAttempt = 0; } newB[0]++; for(int i =0; i<length; i++){ if (newB[i] >= 26 + alphabetTable[i]){ newB[i] -= 26; newB[i+1]++; }else break; } cracked=true; for(int k=0; k<length; k++) { if(newB[k]!=a[k]){ cracked=false; break; }else { cracked = true; } } if(cracked && nIter == 0){ idT = idx; break; } else if(nIter){ break; } totalAttempt++; }while(!cracked || !nIter); if(idx == idT){ for(int i = 0; i< length; i++){ d_output[i] = newB[i]; } } }