Permalink
Switch branches/tags
Nothing to show
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
8542 lines (7369 sloc) 386 KB
#ifndef MARVIN_HPP
#define MARVIN_HPP
/*
* ----------------------------------------------------------------------------
* Marvin: A Minimalist GPU-only N-Dimensional ConvNets Framework
* Copyright (C) 2016 AutoX, Inc.
* ----------------------------------------------------------------------------
*/
#if DATATYPE==0
#pragma message "Compiling using StorageT=half ComputeT=float"
#define StorageT half
#define ComputeT float
#define sizeofStorageT 2
#define sizeofComputeT 4
#define CUDNNStorageT CUDNN_DATA_HALF
#define CUDNNConvComputeT CUDNN_DATA_FLOAT
#define CPUStorage2ComputeT(x) (marvin::cpu_half2float(x))
#define CPUCompute2StorageT(x) (marvin::cpu_float2half(x))
#define GPUStorage2ComputeT(x) (__half2float(x))
#define GPUCompute2StorageT(x) (__float2half(x))
#define GPUgemm Hgemm
#define GPUasum Hasum
#define ISNAN(x) (ishnan(x))
#define ComputeT_MIN FLT_MIN
#include <cuda_fp16.h>
#elif DATATYPE==1
#pragma message "Compiling using StorageT=float ComputeT=float"
#define StorageT float
#define ComputeT float
#define sizeofStorageT 4
#define sizeofComputeT 4
#define CUDNNStorageT CUDNN_DATA_FLOAT
#define CUDNNConvComputeT CUDNN_DATA_FLOAT
#define CPUStorage2ComputeT(x) (x)
#define CPUCompute2StorageT(x) (x)
#define GPUStorage2ComputeT(x) (x)
#define GPUCompute2StorageT(x) (x)
#define GPUgemm cublasSgemm
#define GPUasum cublasSasum
#define ISNAN(x) (std::isnan(x))
#define ComputeT_MIN FLT_MIN
#elif DATATYPE==2
#pragma message "Compiling using StorageT=double ComputeT=double"
#define StorageT double
#define ComputeT double
#define sizeofStorageT 8
#define sizeofComputeT 8
#define CUDNNStorageT CUDNN_DATA_DOUBLE
#define CUDNNConvComputeT CUDNN_DATA_DOUBLE
#define CPUStorage2ComputeT(x) (x)
#define CPUCompute2StorageT(x) (x)
#define GPUStorage2ComputeT(x) (x)
#define GPUCompute2StorageT(x) (x)
#define GPUgemm cublasDgemm
#define GPUasum cublasDasum
#define ISNAN(x) (std::isnan(x))
#define ComputeT_MIN DBL_MIN
#endif
#if CUDA_VERSION >= 8000
#define CUBLAS_DATA_HALF CUDA_R_16F
#endif
//////////////////////////////////////////////////////////////////////////////////////////////////
// Includes
//////////////////////////////////////////////////////////////////////////////////////////////////
#include <cstdlib>
#include <cstdio>
#include <cstdarg>
#include <cmath>
#include <cfloat>
#include <iostream>
#include <fstream>
#include <sstream>
#include <random>
#include <algorithm>
#include <map>
#include <vector>
#include <string>
#include <typeinfo>
#include <typeindex>
#include <thread>
#include <chrono>
#include <future>
#include <cuda.h>
#include <cublas_v2.h>
#include <curand.h>
#include <cudnn.h>
#include <sys/time.h>
#define USE_OPENCV 0
#if USE_OPENCV
#include "opencv2/highgui/highgui.hpp"
#include "opencv2/imgproc/imgproc.hpp"
#endif
namespace marvin {
//////////////////////////////////////////////////////////////////////////////////////////////////
// Type definition
//////////////////////////////////////////////////////////////////////////////////////////////////
enum Filler { Xavier, Gaussian, Constant };
enum Pool { Max, Average, Sum };
enum LossObjective { MultinomialLogistic_StableSoftmax, MultinomialLogistic, SmoothL1, Contrastive, EuclideanSSE, HingeL1, HingeL2, SigmoidCrossEntropy, Infogain };
enum Phase { Training, Testing, TrainingTesting };
enum LRPolicy { LR_fixed, LR_step, LR_exp, LR_inv, LR_multistep, LR_poly, LR_sigmoid, LR_cyclical };
enum SolverAlgorithm { SGD, AdaDelta, AdaGrad, Adam, NAG, RMSprop};
enum Regularizer { L2, L1 };
enum LRN { CrossChannel, DivisiveNormalization };
enum ElementWiseOp { ElementWise_EQL, ElementWise_MUL, ElementWise_SUM, ElementWise_MIN, ElementWise_MAX };
ComputeT anyval;
ComputeT oneval = 1;
ComputeT zeroval = 0;
const void* one = static_cast<void *>(&oneval);
const void* zero = static_cast<void *>(&zeroval);
const ComputeT* oneComputeT = &oneval;
const ComputeT* zeroComputeT = &zeroval;
//////////////////////////////////////////////////////////////////////////////////////////////////
// Debugging utility
//////////////////////////////////////////////////////////////////////////////////////////////////
void FatalError(const int lineNumber=0) {
std::cerr << "FatalError";
if (lineNumber!=0) std::cerr<<" at LINE "<<lineNumber;
std::cerr << ". Program Terminated." << std::endl;
cudaDeviceReset();
exit(EXIT_FAILURE);
}
void checkCUDA(const int lineNumber, cudaError_t error_code) {
if (error_code != cudaSuccess) {
std::cerr << "CUDA failure at LINE " << lineNumber << ": cudaError code " << error_code << ": ";
std::string msg;
switch(error_code){
case cudaSuccess: //0
msg = "The API call returned with no errors. In the case of query calls, this can also mean that the operation being queried is complete (see ::cudaEventQuery() and ::cudaStreamQuery())."; break;
case cudaErrorMissingConfiguration: //1
msg = "The device function being invoked (usually via ::cudaLaunchKernel()) was not previously configured via the ::cudaConfigureCall() function."; break;
case cudaErrorMemoryAllocation: //2
msg = "The API call failed because it was unable to allocate enough memory to perform the requested operation."; break;
case cudaErrorInitializationError: //3
msg = "The API call failed because the CUDA driver and runtime could not be initialized."; break;
case cudaErrorLaunchFailure: //4,
msg = "An exception occurred on the device while executing a kernel. Common causes include dereferencing an invalid device pointer and accessing out of bounds shared memory. The device cannot be used until ::cudaThreadExit() is called. All existing device memory allocations are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorPriorLaunchFailure : //5,
msg = "This indicated that a previous kernel launch failed. This was previously used for device emulation of kernel launches. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorLaunchTimeout: //6,
msg = "This indicates that the device kernel took too long to execute. This can only occur if timeouts are enabled - see the device property \ref ::cudaDeviceProp::kernelExecTimeoutEnabled kernelExecTimeoutEnabled for more information. The device cannot be used until ::cudaThreadExit() is called. All existing device memory allocations are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorLaunchOutOfResources: //7,
msg = "This indicates that a launch did not occur because it did not have appropriate resources. Although this error is similar to ::cudaErrorInvalidConfiguration, this error usually indicates that the user has attempted to pass too many arguments to the device kernel, or the kernel launch specifies too many threads for the kernel's register count."; break;
case cudaErrorInvalidDeviceFunction : // 8,
msg = "The requested device function does not exist or is not compiled for the proper device architecture."; break;
case cudaErrorInvalidConfiguration: //9,
msg = "This indicates that a kernel launch is requesting resources that can never be satisfied by the current device. Requesting more shared memory per block than the device supports will trigger this error, as will requesting too many threads or blocks. See ::cudaDeviceProp for more device limitations."; break;
case cudaErrorInvalidDevice : // 10,
msg = "This indicates that the device ordinal supplied by the user does not correspond to a valid CUDA device."; break;
case cudaErrorInvalidValue : // 11,
msg = "This indicates that one or more of the parameters passed to the API call is not within an acceptable range of values."; break;
case cudaErrorInvalidPitchValue : // 12,
msg = "This indicates that one or more of the pitch-related parameters passed to the API call is not within the acceptable range for pitch."; break;
case cudaErrorInvalidSymbol : // 13,
msg = "This indicates that the symbol name/identifier passed to the API call is not a valid name or identifier."; break;
case cudaErrorMapBufferObjectFailed : // 14,
msg = "This indicates that the buffer object could not be mapped."; break;
case cudaErrorUnmapBufferObjectFailed : // 15,
msg = "This indicates that the buffer object could not be unmapped."; break;
case cudaErrorInvalidHostPointer : // 16,
msg = "This indicates that at least one host pointer passed to the API call is not a valid host pointer."; break;
case cudaErrorInvalidDevicePointer : // 17,
msg = "This indicates that at least one device pointer passed to the API call is not a valid device pointer."; break;
case cudaErrorInvalidTexture : // 18,
msg = "This indicates that the texture passed to the API call is not a valid texture."; break;
case cudaErrorInvalidTextureBinding : // 19,
msg = "This indicates that the texture binding is not valid. This occurs if you call ::cudaGetTextureAlignmentOffset() with an unbound texture."; break;
case cudaErrorInvalidChannelDescriptor : // 20,
msg = "This indicates that the channel descriptor passed to the API call is not valid. This occurs if the format is not one of the formats specified by ::cudaChannelFormatKind, or if one of the dimensions is invalid."; break;
case cudaErrorInvalidMemcpyDirection : // 21,
msg = "This indicates that the direction of the memcpy passed to the API call is not one of the types specified by ::cudaMemcpyKind."; break;
case cudaErrorAddressOfConstant : // 22,
msg = "This indicated that the user has taken the address of a constant variable, which was forbidden up until the CUDA 3.1 release. [deprecated] This error return is deprecated as of CUDA 3.1. Variables in constant memory may now have their address taken by the runtime via ::cudaGetSymbolAddress()."; break;
case cudaErrorTextureFetchFailed : // 23,
msg = "This indicated that a texture fetch was not able to be performed. This was previously used for device emulation of texture operations. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorTextureNotBound : // 24,
msg = "This indicated that a texture was not bound for access. This was previously used for device emulation of texture operations. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorSynchronizationError : // 25,
msg = "This indicated that a synchronization operation had failed. This was previously used for some device emulation functions. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorInvalidFilterSetting : // 26,
msg = "This indicates that a non-float texture was being accessed with linear filtering. This is not supported by CUDA."; break;
case cudaErrorInvalidNormSetting : // 27,
msg = "This indicates that an attempt was made to read a non-float texture as a normalized float. This is not supported by CUDA."; break;
case cudaErrorMixedDeviceExecution : // 28,
msg = "Mixing of device and device emulation code was not allowed. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorCudartUnloading : // 29,
msg = "This indicates that a CUDA Runtime API call cannot be executed because it is being called during process shut down, at a point in time after CUDA driver has been unloaded."; break;
case cudaErrorUnknown : // 30,
msg = "This indicates that an unknown internal error has occurred."; break;
case cudaErrorNotYetImplemented : // 31,
msg = "This indicates that the API call is not yet implemented. Production releases of CUDA will never return this error. [deprecated] This error return is deprecated as of CUDA 4.1."; break;
case cudaErrorMemoryValueTooLarge : // 32,
msg = "his indicated that an emulated device pointer exceeded the 32-bit address range. [deprecated] This error return is deprecated as of CUDA 3.1. Device emulation mode was removed with the CUDA 3.1 release."; break;
case cudaErrorInvalidResourceHandle : // 33,
msg = "This indicates that a resource handle passed to the API call was not valid. Resource handles are opaque types like ::cudaStream_t and ::cudaEvent_t."; break;
case cudaErrorNotReady : // 34,
msg = "This indicates that asynchronous operations issued previously have not completed yet. This result is not actually an error, but must be indicated differently than ::cudaSuccess (which indicates completion). Calls that may return this value include ::cudaEventQuery() and ::cudaStreamQuery()."; break;
case cudaErrorInsufficientDriver : // 35,
msg = "This indicates that the installed NVIDIA CUDA driver is older than the CUDA runtime library. This is not a supported configuration. Users should install an updated NVIDIA display driver to allow the application to run."; break;
case cudaErrorSetOnActiveProcess : // 36,
msg = "This indicates that the user has called ::cudaSetValidDevices(), ::cudaSetDeviceFlags(), ::cudaD3D9SetDirect3DDevice(), ::cudaD3D10SetDirect3DDevice, ::cudaD3D11SetDirect3DDevice(), or ::cudaVDPAUSetVDPAUDevice() after initializing the CUDA runtime by calling non-device management operations (allocating memory and launching kernels are examples of non-device management operations). This error can also be returned if using runtime/driver interoperability and there is an existing ::CUcontext active on the host thread."; break;
case cudaErrorInvalidSurface : // 37,
msg = "This indicates that the surface passed to the API call is not a valid surface."; break;
case cudaErrorNoDevice : // 38,
msg = "This indicates that no CUDA-capable devices were detected by the installed CUDA driver."; break;
case cudaErrorECCUncorrectable : // 39,
msg = "This indicates that an uncorrectable ECC error was detected during execution."; break;
case cudaErrorSharedObjectSymbolNotFound : // 40,
msg = "This indicates that a link to a shared object failed to resolve."; break;
case cudaErrorSharedObjectInitFailed : // 41,
msg = "This indicates that initialization of a shared object failed."; break;
case cudaErrorUnsupportedLimit : // 42,
msg = "This indicates that the ::cudaLimit passed to the API call is not supported by the active device."; break;
case cudaErrorDuplicateVariableName : // 43,
msg = "This indicates that multiple global or constant variables (across separate CUDA source files in the application) share the same string name."; break;
case cudaErrorDuplicateTextureName : // 44,
msg = "This indicates that multiple textures (across separate CUDA source files in the application) share the same string name."; break;
case cudaErrorDuplicateSurfaceName : // 45,
msg = "This indicates that multiple surfaces (across separate CUDA source files in the application) share the same string name."; break;
case cudaErrorDevicesUnavailable : // 46,
msg = "This indicates that all CUDA devices are busy or unavailable at the current time. Devices are often busy/unavailable due to use of ::cudaComputeModeExclusive, ::cudaComputeModeProhibited or when long running CUDA kernels have filled up the GPU and are blocking new work from starting. They can also be unavailable due to memory constraints on a device that already has active CUDA work being performed."; break;
case cudaErrorInvalidKernelImage : // 47,
msg = "This indicates that the device kernel image is invalid."; break;
case cudaErrorNoKernelImageForDevice : // 48,
msg = "there is no kernel image available that is suitable for the device. This can occur when a user specifies code generation options for a particular CUDA source file that do not include the corresponding device configuration."; break;
case cudaErrorIncompatibleDriverContext: // 49,
msg = "the current context is not compatible with this the CUDA Runtime. This can only occur if you are using CUDA Runtime/Driver interoperability and have created an existing Driver context using the driver API. The Driver context may be incompatible either because the Driver context was created using an older version of the API, because the Runtime API call expects a primary driver context and the Driver context is not primary, or because the Driver context has been destroyed. Please see ref CUDART_DRIVER Interactions with the CUDA Driver API for more information."; break;
case cudaErrorPeerAccessAlreadyEnabled : // 50,
msg = "a call to ::cudaDeviceEnablePeerAccess() is trying to re-enable peer addressing on from a context which has already had peer addressing enabled."; break;
case cudaErrorPeerAccessNotEnabled : // 51,
msg = "::cudaDeviceDisablePeerAccess() is trying to disable peer addressing which has not been enabled yet via ::cudaDeviceEnablePeerAccess()."; break;
case cudaErrorDeviceAlreadyInUse : // 54,
msg = "a call tried to access an exclusive-thread device that is already in use by a different thread."; break;
case cudaErrorProfilerDisabled : // 55,
msg = "This indicates profiler is not initialized for this run. This can happen when the application is running with external profiling tools like visual profiler."; break;
case cudaErrorProfilerNotInitialized : // 56,
msg = "[deprecated] This error return is deprecated as of CUDA 5.0. It is no longer an error to attempt to enable/disable the profiling via ::cudaProfilerStart or ::cudaProfilerStop without initialization."; break;
case cudaErrorProfilerAlreadyStarted : // 57,
msg = "[deprecated] This error return is deprecated as of CUDA 5.0. It is no longer an error to call cudaProfilerStart() when profiling is already enabled."; break;
case cudaErrorProfilerAlreadyStopped : //58,
msg = "[deprecated] This error return is deprecated as of CUDA 5.0. It is no longer an error to call cudaProfilerStop() when profiling is already disabled."; break;
case cudaErrorAssert : //59,
msg = "An assert triggered in device code during kernel execution. The device cannot be used again until ::cudaThreadExit() is called. All existing allocations are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorTooManyPeers : // 60,
msg = "the hardware resources required to enable peer access have been exhausted for one or more of the devices passed to ::cudaEnablePeerAccess()."; break;
case cudaErrorHostMemoryAlreadyRegistered: // 61,
msg = "the memory range passed to ::cudaHostRegister() has already been registered."; break;
case cudaErrorHostMemoryNotRegistered : // 62,
msg = "the pointer passed to ::cudaHostUnregister() does not correspond to any currently registered memory region."; break;
case cudaErrorOperatingSystem : // 63,
msg = "an OS call failed."; break;
case cudaErrorPeerAccessUnsupported : // 64,
msg = "P2P access is not supported across the given devices."; break;
case cudaErrorLaunchMaxDepthExceeded : // 65,
msg = "a device runtime grid launch did not occur because the depth of the child grid would exceed the maximum supported number of nested grid launches."; break;
case cudaErrorLaunchFileScopedTex : // 66,
msg = "a grid launch did not occur because the kernel uses file-scoped textures which are unsupported by the device runtime. Kernels launched via the device runtime only support textures created with the Texture Object API's."; break;
case cudaErrorLaunchFileScopedSurf : // 67,
msg = "a grid launch did not occur because the kernel uses file-scoped surfaces which are unsupported by the device runtime. Kernels launched via the device runtime only support surfaces created with the Surface Object API's."; break;
case cudaErrorSyncDepthExceeded : // 68,
msg = "a call to ::cudaDeviceSynchronize made from the device runtime failed because the call was made at grid depth greater than than either the default (2 levels of grids) or user specified device limit ::cudaLimitDevRuntimeSyncDepth. To be able to synchronize on launched grids at a greater depth successfully, the maximum nested depth at which ::cudaDeviceSynchronize will be called must be specified with the ::cudaLimitDevRuntimeSyncDepth limit to the ::cudaDeviceSetLimit api before the host-side launch of a kernel using the device runtime. Keep in mind that additional levels of sync depth require the runtime to reserve large amounts of device memory that cannot be used for user allocations."; break;
case cudaErrorLaunchPendingCountExceeded : // 69,
msg = "a device runtime grid launch failed because the launch would exceed the limit ::cudaLimitDevRuntimePendingLaunchCount. For this launch to proceed successfully, ::cudaDeviceSetLimit must be called to set the ::cudaLimitDevRuntimePendingLaunchCount to be higher than the upper bound of outstanding launches that can be issued to the device runtime. Keep in mind that raising the limit of pending device runtime launches will require the runtime to reserve device memory that cannot be used for user allocations."; break;
case cudaErrorNotPermitted : // 70,
msg = "This error indicates the attempted operation is not permitted."; break;
case cudaErrorNotSupported : // 71,
msg = "This error indicates the attempted operation is not supported on the current system or device."; break;
case cudaErrorHardwareStackError : // 72,
msg = "Device encountered an error in the call stack during kernel execution, possibly due to stack corruption or exceeding the stack size limit. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorIllegalInstruction : // 73,
msg = "The device encountered an illegal instruction during kernel execution The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorMisalignedAddress : // 74,
msg = "The device encountered a load or store instruction on a memory address which is not aligned. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorInvalidAddressSpace : // 75,
msg = "While executing a kernel, the device encountered an instruction which can only operate on memory locations in certain address spaces (global, shared, or local), but was supplied a memory address not belonging to an allowed address space. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorInvalidPc : // 76,
msg = "The device encountered an invalid program counter. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorIllegalAddress : // 77,
msg = "The device encountered a load or store instruction on an invalid memory address. The context cannot be used, so it must be destroyed (and a new one should be created). All existing device memory allocations from this context are invalid and must be reconstructed if the program is to continue using CUDA."; break;
case cudaErrorInvalidPtx : // 78,
msg = "A PTX compilation failed. The runtime may fall back to compiling PTX if an application does not contain a suitable binary for the current device."; break;
case cudaErrorInvalidGraphicsContext : // 79,
msg = "This indicates an error with the OpenGL or DirectX context."; break;
case cudaErrorStartupFailure : // 0x7f,
msg = "This indicates an internal startup failure in the CUDA runtime."; break;
case cudaErrorApiFailureBase : // 10000
msg = "Any unhandled CUDA driver error is added to this value and returned via the runtime. Production releases of CUDA should not return such errors. [deprecated] This error return is deprecated as of CUDA 4.1."; break;
}
std::cerr << msg << std::endl;
FatalError();
}
}
void checkCUDNN(const int lineNumber, cudnnStatus_t status) {
if (status != CUDNN_STATUS_SUCCESS) {
std::cerr << "CUDNN failure at LINE " << lineNumber << ": ";
switch (status) {
case CUDNN_STATUS_SUCCESS: std::cerr << "CUDNN_STATUS_SUCCESS" << std::endl; break;
case CUDNN_STATUS_NOT_INITIALIZED: std::cerr << "CUDNN_STATUS_NOT_INITIALIZED" << std::endl; break;
case CUDNN_STATUS_ALLOC_FAILED: std::cerr << "CUDNN_STATUS_ALLOC_FAILED" << std::endl; break;
case CUDNN_STATUS_BAD_PARAM: std::cerr << "CUDNN_STATUS_BAD_PARAM" << std::endl; break;
case CUDNN_STATUS_INTERNAL_ERROR: std::cerr << "CUDNN_STATUS_INTERNAL_ERROR" << std::endl; break;
case CUDNN_STATUS_INVALID_VALUE: std::cerr << "CUDNN_STATUS_INVALID_VALUE" << std::endl; break;
case CUDNN_STATUS_ARCH_MISMATCH: std::cerr << "CUDNN_STATUS_ARCH_MISMATCH" << std::endl; break;
case CUDNN_STATUS_MAPPING_ERROR: std::cerr << "CUDNN_STATUS_MAPPING_ERROR" << std::endl; break;
case CUDNN_STATUS_EXECUTION_FAILED: std::cerr << "CUDNN_STATUS_EXECUTION_FAILED" << std::endl; break;
case CUDNN_STATUS_NOT_SUPPORTED: std::cerr << "CUDNN_STATUS_NOT_SUPPORTED" << std::endl; break;
case CUDNN_STATUS_LICENSE_ERROR: std::cerr << "CUDNN_STATUS_LICENSE_ERROR" << std::endl; break;
}
FatalError();
}
checkCUDA(lineNumber,cudaGetLastError());
}
void checkCUBLAS(const int lineNumber, cublasStatus_t status) {
if (status != CUBLAS_STATUS_SUCCESS) {
std::cerr << "CUBLAS failure at LINE " << lineNumber << ": ";
switch (status) {
case CUBLAS_STATUS_SUCCESS: std::cerr << "CUBLAS_STATUS_SUCCESS" << std::endl; break;
case CUBLAS_STATUS_NOT_INITIALIZED: std::cerr << "CUBLAS_STATUS_NOT_INITIALIZED" << std::endl; break;
case CUBLAS_STATUS_ALLOC_FAILED: std::cerr << "CUBLAS_STATUS_ALLOC_FAILED" << std::endl; break;
case CUBLAS_STATUS_INVALID_VALUE: std::cerr << "CUBLAS_STATUS_INVALID_VALUE" << std::endl; break;
case CUBLAS_STATUS_ARCH_MISMATCH: std::cerr << "CUBLAS_STATUS_ARCH_MISMATCH" << std::endl; break;
case CUBLAS_STATUS_MAPPING_ERROR: std::cerr << "CUBLAS_STATUS_MAPPING_ERROR" << std::endl; break;
case CUBLAS_STATUS_EXECUTION_FAILED: std::cerr << "CUBLAS_STATUS_EXECUTION_FAILED" << std::endl; break;
case CUBLAS_STATUS_INTERNAL_ERROR: std::cerr << "CUBLAS_STATUS_INTERNAL_ERROR" << std::endl; break;
case CUBLAS_STATUS_NOT_SUPPORTED: std::cerr << "CUBLAS_STATUS_NOT_SUPPORTED" << std::endl; break;
case CUBLAS_STATUS_LICENSE_ERROR: std::cerr << "CUBLAS_STATUS_LICENSE_ERROR" << std::endl; break;
}
FatalError();
}
checkCUDA(lineNumber,cudaGetLastError());
}
unsigned long long get_timestamp() {
struct timeval now;
gettimeofday (&now, NULL);
return now.tv_usec + (unsigned long long)now.tv_sec * 1000000;
}
unsigned long long ticBegin;
unsigned long long tic() {
ticBegin = get_timestamp();
return ticBegin;
}
unsigned long long toc() {
unsigned long long ticEnd = get_timestamp();
unsigned long long delta = ticEnd - ticBegin;
std::cout << "Time passes " << delta << " microseconds" <<std::endl;
ticBegin = ticEnd;
return delta;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// HALF computation ultility
//////////////////////////////////////////////////////////////////////////////////////////////////
static __inline__ __device__ __host__ int ishnan(half h) {
// When input is NaN, exponent is all ones and mantissa is non-zero.
return (h.x & 0x7c00U) == 0x7c00U && (h.x & 0x03ffU) != 0;
}
half cpu_float2half(float f) {
half ret;
unsigned x = *((int*)(void*)(&f));
unsigned u = (x & 0x7fffffff), remainder, shift, lsb, lsb_s1, lsb_m1;
unsigned sign, exponent, mantissa;
// Get rid of +NaN/-NaN case first.
if (u > 0x7f800000) {
ret.x = 0x7fffU;
return ret;
}
sign = ((x >> 16) & 0x8000);
// Get rid of +Inf/-Inf, +0/-0.
if (u > 0x477fefff) {
ret.x = sign | 0x7c00U;
return ret;
}
if (u < 0x33000001) {
ret.x = (sign | 0x0000);
return ret;
}
exponent = ((u >> 23) & 0xff);
mantissa = (u & 0x7fffff);
if (exponent > 0x70) {
shift = 13;
exponent -= 0x70;
} else {
shift = 0x7e - exponent;
exponent = 0;
mantissa |= 0x800000;
}
lsb = (1 << shift);
lsb_s1 = (lsb >> 1);
lsb_m1 = (lsb - 1);
// Round to nearest even.
remainder = (mantissa & lsb_m1);
mantissa >>= shift;
if (remainder > lsb_s1 || (remainder == lsb_s1 && (mantissa & 0x1))) {
++mantissa;
if (!(mantissa & 0x3ff)) {
++exponent;
mantissa = 0;
}
}
ret.x = (sign | (exponent << 10) | mantissa);
return ret;
}
float cpu_half2float(half h) {
unsigned sign = ((h.x >> 15) & 1);
unsigned exponent = ((h.x >> 10) & 0x1f);
unsigned mantissa = ((h.x & 0x3ff) << 13);
if (exponent == 0x1f) { /* NaN or Inf */
mantissa = (mantissa ? (sign = 0, 0x7fffff) : 0);
exponent = 0xff;
} else if (!exponent) { /* Denorm or Zero */
if (mantissa) {
unsigned int msb;
exponent = 0x71;
do {
msb = (mantissa & 0x400000);
mantissa <<= 1; /* normalize */
--exponent;
} while (!msb);
mantissa &= 0x7fffff; /* 1.mantissa is implicit */
}
} else {
exponent += 0x70;
}
int temp = ((sign << 31) | (exponent << 23) | mantissa);
return *((float*)((void*)&temp));
}
bool operator <(const half& x, const half& y) {
return cpu_half2float(x) < cpu_half2float(y);
}
std::ostream& operator<< (std::ostream& stream, const half& x) {
stream << cpu_half2float(x);
return stream;
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// JSON parser
//////////////////////////////////////////////////////////////////////////////////////////////////
enum JSONType { JSON_String, JSON_Bool, JSON_Null, JSON_Number, JSON_Object, JSON_ObjectArray};
// plain object
class JSON{
public:
JSONType type;
std::vector<void*> array;
std::map<std::string, JSON*> member;
~JSON(){
for (int i=0;i<array.size();++i){
if (array[i]!=NULL){
switch(type){
case JSON_String:
delete ((std::string*)(array[i]));
break;
case JSON_Bool:
delete ((bool*)(array[i]));
break;
case JSON_Null:
break;
case JSON_Number:
delete ((ComputeT*)(array[i]));
break;
case JSON_Object:
break;
case JSON_ObjectArray:
delete ((JSON*)(array[i]));
break;
}
}
}
for (std::map<std::string, JSON*>::iterator it = member.begin(); it != member.end(); it++ ){
if (it->second != NULL)
delete it->second;
}
};
std::string returnString(){
if (type!=JSON_String) FatalError(__LINE__);
return *((std::string*)(array[0]));
};
bool returnBool(){
if (type!=JSON_Bool) FatalError(__LINE__);
return *((bool*)(array[0]));
};
ComputeT returnReal(){
if (type!=JSON_Number) FatalError(__LINE__);
return *((ComputeT*)(array[0]));
};
std::vector<int> returnIntVector(){
if (type!=JSON_Number) FatalError(__LINE__);
std::vector<int> v(array.size());
for (int i=0;i<array.size();++i){
v[i] = (int)(*((ComputeT*)(array[i])));
}
return v;
};
std::vector<ComputeT> returnRealVector(){
if (type!=JSON_Number) FatalError(__LINE__);
std::vector<ComputeT> v(array.size());
for (int i=0;i<array.size();++i){
v[i] = (ComputeT)(*((ComputeT*)(array[i])));
}
return v;
};
std::vector<std::string> returnStringVector(){
if (type!=JSON_String) FatalError(__LINE__);
std::vector<std::string> v(array.size());
for (int i=0;i<array.size();++i){
v[i] = *((std::string*)(array[i]));
}
return v;
};
void setOrDie(std::string name, unsigned int &variable){
if (this->member.find(name) == this->member.end()){
FatalError(__LINE__);
}
else variable = (unsigned int)this->member[name]->returnReal();
};
void setOrDie(std::string name, bool &variable){
if (this->member.find(name) == this->member.end()){
FatalError(__LINE__);
}
else variable = this->member[name]->returnBool();
};
void setOrDie(std::string name, std::vector<ComputeT> &variable){
if (this->member.find(name) == this->member.end())
FatalError(__LINE__);
else variable = this->member[name]->returnRealVector();
};
void set(std::string name, bool &variable, bool default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnBool();
};
void set(std::string name, ComputeT &variable, ComputeT default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (ComputeT)(this->member[name]->returnReal());
};
void setOrDie(std::string name, ComputeT &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = (ComputeT)(this->member[name]->returnReal());
};
void set(std::string name, int &variable, int default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (int)(this->member[name]->returnReal());
};
void set(std::string name, double &variable, double default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (double)(this->member[name]->returnReal());
};
void set(std::string name, unsigned int &variable, unsigned int default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = (unsigned int)(this->member[name]->returnReal());
};
void setOrDie(std::string name, int &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = (int)(this->member[name]->returnReal());
};
void set(std::string name, std::vector<int> &variable, std::vector<int> default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnIntVector();
};
void set(std::string name, std::vector<ComputeT> &variable, std::vector<ComputeT> default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnRealVector();
};
void set(std::string name, std::vector<std::string> &variable, std::vector<std::string> default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnStringVector();
};
void setOrDie(std::string name, std::vector<std::string> &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = this->member[name]->returnStringVector();
};
void setOrDie(std::string name, std::vector<int> &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = this->member[name]->returnIntVector();
};
void set(std::string name, std::string &variable, std::string default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else variable = this->member[name]->returnString();
};
void setOrDie(std::string name, std::string &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else variable = this->member[name]->returnString();
};
void setOrDie(std::string name, ElementWiseOp &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else if (0 == this->member[name]->returnString().compare("ElementWise_EQL")) variable = ElementWise_EQL;
else if (0 == this->member[name]->returnString().compare("ElementWise_MUL")) variable = ElementWise_MUL;
else if (0 == this->member[name]->returnString().compare("ElementWise_SUM")) variable = ElementWise_SUM;
else if (0 == this->member[name]->returnString().compare("ElementWise_MIN")) variable = ElementWise_MIN;
else if (0 == this->member[name]->returnString().compare("ElementWise_MAX")) variable = ElementWise_MAX;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Filler &variable, Filler default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Xavier")) variable = Xavier;
else if (0 == this->member[name]->returnString().compare("Gaussian")) variable = Gaussian;
else if (0 == this->member[name]->returnString().compare("Constant")) variable = Constant;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Pool &variable, Pool default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Max")) variable = Max;
else if (0 == this->member[name]->returnString().compare("Average")) variable = Average;
else if (0 == this->member[name]->returnString().compare("Sum")) variable = Sum;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void setOrDie(std::string name, LossObjective &variable){
if (this->member.find(name) == this->member.end()) FatalError(__LINE__);
else if (0 == this->member[name]->returnString().compare("MultinomialLogistic_StableSoftmax")) variable = MultinomialLogistic_StableSoftmax;
else if (0 == this->member[name]->returnString().compare("MultinomialLogistic")) variable = MultinomialLogistic;
else if (0 == this->member[name]->returnString().compare("SmoothL1")) variable = SmoothL1;
else if (0 == this->member[name]->returnString().compare("Contrastive")) variable = Contrastive;
else if (0 == this->member[name]->returnString().compare("EuclideanSSE")) variable = EuclideanSSE;
else if (0 == this->member[name]->returnString().compare("HingeL1")) variable = HingeL1;
else if (0 == this->member[name]->returnString().compare("HingeL2")) variable = HingeL2;
else if (0 == this->member[name]->returnString().compare("SigmoidCrossEntropy")) variable = SigmoidCrossEntropy;
else if (0 == this->member[name]->returnString().compare("Infogain")) variable = Infogain;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Phase &variable, Phase default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Training")) variable = Training;
else if (0 == this->member[name]->returnString().compare("Testing")) variable = Testing;
else if (0 == this->member[name]->returnString().compare("TrainingTesting")) variable = TrainingTesting;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, LRPolicy &variable, LRPolicy default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("LR_fixed")) variable = LR_fixed;
else if (0 == this->member[name]->returnString().compare("LR_step")) variable = LR_step;
else if (0 == this->member[name]->returnString().compare("LR_exp")) variable = LR_exp;
else if (0 == this->member[name]->returnString().compare("LR_inv")) variable = LR_inv;
else if (0 == this->member[name]->returnString().compare("LR_multistep")) variable = LR_multistep;
else if (0 == this->member[name]->returnString().compare("LR_poly")) variable = LR_poly;
else if (0 == this->member[name]->returnString().compare("LR_sigmoid")) variable = LR_sigmoid;
else if (0 == this->member[name]->returnString().compare("LR_cyclical")) variable = LR_cyclical;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, SolverAlgorithm &variable, SolverAlgorithm default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("SGD")) variable = SGD;
else if (0 == this->member[name]->returnString().compare("AdaDelta")) variable = AdaDelta;
else if (0 == this->member[name]->returnString().compare("AdaGrad")) variable = AdaGrad;
else if (0 == this->member[name]->returnString().compare("Adam")) variable = Adam;
else if (0 == this->member[name]->returnString().compare("NAG")) variable = NAG;
else if (0 == this->member[name]->returnString().compare("RMSprop")) variable = RMSprop;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, Regularizer &variable, Regularizer default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("L2")) variable = L2;
else if (0 == this->member[name]->returnString().compare("L1")) variable = L1;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, LRN &variable, LRN default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("CrossChannel")) variable = CrossChannel;
else if (0 == this->member[name]->returnString().compare("DivisiveNormalization")) variable = DivisiveNormalization;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnBatchNormMode_t &variable, cudnnBatchNormMode_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Spatial")) variable = CUDNN_BATCHNORM_SPATIAL;
else if (0 == this->member[name]->returnString().compare("PerActivation")) variable = CUDNN_BATCHNORM_PER_ACTIVATION;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnPoolingMode_t &variable, cudnnPoolingMode_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("max")) variable = CUDNN_POOLING_MAX;
else if (0 == this->member[name]->returnString().compare("average_include")) variable = CUDNN_POOLING_AVERAGE_COUNT_INCLUDE_PADDING;
else if (0 == this->member[name]->returnString().compare("average_exclude")) variable = CUDNN_POOLING_AVERAGE_COUNT_EXCLUDE_PADDING;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnActivationMode_t &variable, cudnnActivationMode_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("Sigmoid")) variable = CUDNN_ACTIVATION_SIGMOID;
else if (0 == this->member[name]->returnString().compare("ReLU")) variable = CUDNN_ACTIVATION_RELU;
else if (0 == this->member[name]->returnString().compare("TanH")) variable = CUDNN_ACTIVATION_TANH;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnConvolutionFwdAlgo_t &variable, cudnnConvolutionFwdAlgo_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("implicit_gemm")) variable = CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_GEMM;
else if (0 == this->member[name]->returnString().compare("implicit_precomp_gemm")) variable = CUDNN_CONVOLUTION_FWD_ALGO_IMPLICIT_PRECOMP_GEMM;
else if (0 == this->member[name]->returnString().compare("gemm")) variable = CUDNN_CONVOLUTION_FWD_ALGO_GEMM;
else if (0 == this->member[name]->returnString().compare("direct")) variable = CUDNN_CONVOLUTION_FWD_ALGO_DIRECT;
else if (0 == this->member[name]->returnString().compare("fft")) variable = CUDNN_CONVOLUTION_FWD_ALGO_FFT;
else if (0 == this->member[name]->returnString().compare("fft_tiling")) variable = CUDNN_CONVOLUTION_FWD_ALGO_FFT_TILING;
else if (0 == this->member[name]->returnString().compare("winograd")) variable = CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD;
else if (0 == this->member[name]->returnString().compare("winograd_nonfused")) variable = CUDNN_CONVOLUTION_FWD_ALGO_WINOGRAD_NONFUSED;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnConvolutionBwdDataAlgo_t &variable, cudnnConvolutionBwdDataAlgo_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("0")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_0;
else if (0 == this->member[name]->returnString().compare("1")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_1;
else if (0 == this->member[name]->returnString().compare("fft")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT;
else if (0 == this->member[name]->returnString().compare("fft_tiling")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_FFT_TILING;
else if (0 == this->member[name]->returnString().compare("winograd")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD;
else if (0 == this->member[name]->returnString().compare("winograd_nonfused")) variable = CUDNN_CONVOLUTION_BWD_DATA_ALGO_WINOGRAD_NONFUSED;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void set(std::string name, cudnnConvolutionBwdFilterAlgo_t &variable, cudnnConvolutionBwdFilterAlgo_t default_value){
if (this->member.find(name) == this->member.end()) variable = default_value;
else if (0 == this->member[name]->returnString().compare("0")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_0;
else if (0 == this->member[name]->returnString().compare("1")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_1;
else if (0 == this->member[name]->returnString().compare("fft")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_FFT;
else if (0 == this->member[name]->returnString().compare("3")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_3;
else if (0 == this->member[name]->returnString().compare("winograd_nonfused")) variable = CUDNN_CONVOLUTION_BWD_FILTER_ALGO_WINOGRAD_NONFUSED;
else{ std::cout<<"Unsupported "<<name<<" = "<<this->member[name]->returnString()<<std::endl; FatalError(__LINE__); }
};
void print(){
switch(type){
case JSON_String:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << "\"" << *((std::string*)(array[i])) << "\"" ;
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Bool:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << ((*((bool*)(array[i])))? "true": "false");
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Null:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << "null";
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Number:
if (array.size()>1) std::cout<<"[";
for (int i=0;i<array.size();++i){
if (i>0) std::cout<< ",";
std::cout << *((ComputeT*)(array[i]));
}
if (array.size()>1) std::cout<<"]";
std::cout<<std::endl;
break;
case JSON_Object:
std::cout<<"{"<<std::endl;
for (std::map<std::string, JSON*>::iterator it = member.begin(); it != member.end(); it++ ){
std::cout << "\t" << it->first << ": ";
it->second->print();
}
std::cout<<"}";
break;
case JSON_ObjectArray:
std::cout<<"["<<std::endl;
for (int i=0;i<array.size();++i){
JSON* p = (JSON*)(array[i]);
p->print();
if (i<array.size()-1) std::cout<<","<<std::endl;
}
std::cout<<"]"<<std::endl;
break;
}
};
void parseNumberOrTextArray(std::string input){
while (input.size()>0){
int e = input.find(",");
if (e==std::string::npos){
e = input.size();
}
std::string first = input.substr(0,e);
if (first[0]=='\"'){
type = JSON_String;
std::string* p = new std::string(first.substr(1,first.size()-2));
array.push_back((void*)p);
}else if (first[0]=='t'){
type = JSON_Bool;
bool* p = new bool(true);
array.push_back((void*)p);
}else if (first[0]=='f'){
type = JSON_Bool;
bool* p = new bool(false);
array.push_back((void*)p);
}else if (first[0]=='n'){
type = JSON_Null;
void* p = NULL;
array.push_back((void*)p);
}else{
type = JSON_Number;
ComputeT* p = new ComputeT(stof(first));
array.push_back((void*)p);
}
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
};
void parseObject(std::string input){
type = JSON_Object;
int b,m,e;
JSON* p;
b = input.find("{");
e = input.find("}");
input = input.substr(b+1,e-b-1);
while (true){
m= input.find(":");
if (std::string::npos==m) break;
std::string name = input.substr(0,m);
name = name.substr(1,m-2);
input = input.substr(m+1);
if (input[0]=='\"'){
e=input.find("\"",1);
p = new JSON;
p->parseNumberOrTextArray(input.substr(0,e+1));
this->member[name] = p;
if (e+2<input.size())
input = input.substr(e+2);
else
break;
}else if (input[0]=='['){
// assume no nested array
input = input.substr(1);
e = input.find("]");
p = new JSON;
p->parseNumberOrTextArray(input.substr(0,e));
this->member[name] = p;
if (e+1<input.size())
input = input.substr(e+2);
else
break;
}else if (input[0]=='f' || input[0]=='t' || input[0]=='.' || input[0]=='-' || ('0'<=input[0] && input[0]<='9')){
e=input.find(",");
if (e==std::string::npos){
e = input.size();
}
p = new JSON;
p->parseNumberOrTextArray(input.substr(0,e));
this->member[name] = p;
if (e+1<input.size())
input = input.substr(e+1);
else
break;
}else{
FatalError(__LINE__);
}
}
};
void parseObjectArray(std::string input){
type = JSON_ObjectArray;
input = input.substr(1,input.size()-2);
while (input.size()>0){
int e = input.find("}")+1;
if (e==std::string::npos){
e = input.size();
}
std::string first = input.substr(0,e);
JSON* pObj = new JSON;
pObj->parseObject(first);
array.push_back((void*)pObj);
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
};
};
#define SetValue(obj,attribute,value) obj->set(#attribute,attribute,value);
#define SetOrDie(obj,attribute) obj->setOrDie(#attribute,attribute);
void parseNetworkJSON(std::string filename, JSON* train_obj, JSON* test_obj, JSON* architecture_obj){
std::ifstream t(filename);
std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>());
str.erase(remove_if(str.begin(), str.end(), (int(*)(int))isspace), str.end());
std::string input = str;
int b,e;
b = input.find("\"train\"");
std::string train_str = input.substr(b+7);
b = train_str.find("{");
e = train_str.find("}");
train_str=train_str.substr(b,e-b+1);
if (train_obj!=NULL) train_obj->parseObject(train_str);
b = input.find("\"test\"");
std::string test_str = input.substr(b+6);
b = test_str.find("{");
e = test_str.find("}");
test_str=test_str.substr(b,e-b+1);
if (test_obj!=NULL) test_obj->parseObject(test_str);
b=input.find("\"layers\"");
input = input.substr(b+9);
e=input.find("}]");
if (architecture_obj!=NULL) architecture_obj->parseObjectArray(input);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Utility
//////////////////////////////////////////////////////////////////////////////////////////////////
bool is_file_exist(const std::string& fileName){
std::ifstream infile(fileName);
return infile.good();
}
void memorySizePrint(size_t bytes){
if (bytes<512){
std::cout<<bytes<<" Bytes";
}else if (bytes<512.0*1024){
std::cout<<(bytes/1024.0)<<" KB";
}else if (bytes<512.0*1024*1024){
std::cout<<(bytes/(1024.0*1024.0))<<" MB";
}else if (bytes<512.0*1024*1024*1024){
std::cout<<(bytes/(1024.0*1024.0*1024.0))<<" GB";
}else if (bytes<512.0*1024*1024*1024*1024){
std::cout<<(bytes/(1024.0*1024.0*1024.0*1024.0))<<" TB";
}else{
std::cout<<(bytes/(1024.0*1024.0*1024.0*1024.0*1024.0))<<" PB";
}
}
void veciPrint(const std::vector<int>& v){
std::cout<<"["<<v.size()<<"]={";
if (v.size()>0) std::cout<<v[0];
if (v.size()>1){
for (int i=1;i<v.size();++i){
std::cout<<","<<v[i];
}
}
std::cout<<"}";
}
void vecfPrint(const std::vector<ComputeT>& v){
std::cout<<"[";
if (v.size()>0) std::cout<<v[0];
if (v.size()>1){
for (int i=1;i<v.size();++i){
std::cout<<","<<v[i];
}
}
std::cout<<"]";
}
std::vector<int> veci(int n, ...){
std::vector<int> v;
if (n==0) return v;
va_list ap;
va_start(ap, n);
for(int i = 0; i < n; i++) {
v.push_back(va_arg(ap, int));
}
va_end(ap);
return v;
}
std::vector<std::string> vecs(int n, ...){
std::vector<std::string> v;
if (n==0) return v;
va_list ap;
va_start(ap, n);
for(int i = 0; i < n; i++) {
v.push_back(std::string(va_arg(ap, char*)));
}
va_end(ap);
return v;
}
std::vector<std::string> getStringVector(std::string input){
std::vector<std::string> ret;
while (input.size()>0){
int e = input.find(",");
if (e==std::string::npos){
e = input.size();
}
std::string first = input.substr(0,e);
ret.push_back(first);
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
return ret;
}
std::vector<std::vector<int> > getIntVectorVector(std::string input){
//remove all space
input.erase(remove_if(input.begin(), input.end(), (int(*)(int))isspace), input.end());
std::vector<std::vector<int> > ret;
while (input.size()>0){
int e;
if (input[0]=='['){
ret.resize(ret.size()+1);
e=0;
}else if (input[0]==','){
e=0;
}else if (input[0]==']'){
e=0;
}else{
e = input.find(",");
if (e==std::string::npos){
e = input.size();
}
int f = input.find("]");
if (f==std::string::npos){
f = input.size();
}
e = min(e,f);
std::string first = input.substr(0,e);
ret[ret.size()-1].push_back(stoi(first));
}
if(e+1<input.size())
input=input.substr(e+1);
else
break;
}
return ret;
}
size_t numel(const std::vector<int>& dim){
size_t res = 1;
for (int i=0;i<dim.size();++i) res *= (size_t)(dim[i]);
return res;
}
size_t sizeofitem(const std::vector<int>& dim){
size_t res = 1;
for (int i=1;i<dim.size();++i) res *= (size_t)(dim[i]);
return res;
}
size_t numspel(const std::vector<int>& dim){
size_t res = 1;
for (int i=2;i<dim.size();++i) res *= (size_t)(dim[i]);
return res;
}
bool same_dim(const std::vector<int>& dimA, const std::vector<int>& dimB){
if (dimA.size()!=dimB.size()) return false;
for (int i=0;i<dimA.size();++i){
if (dimA[i]!=dimB[i]) return false;
}
return true;
}
bool same_dim_EC(const std::vector<int>& dimA, const std::vector<int>& dimB){
if (dimA.size()!=dimB.size()) return false;
if (dimA[0]!=dimB[0]) return false;
for (int i=2;i<dimA.size();++i)
if (dimA[i]!=dimB[i])
return false;
return true;
}
size_t checkNaN(StorageT* dataGPU, size_t n){
StorageT* CPUmem = new StorageT[n];
cudaMemcpy(CPUmem, dataGPU, n*sizeofStorageT, cudaMemcpyDeviceToHost);
size_t countNaN = 0;
for (size_t i=0;i<n;++i) if (ISNAN(CPUmem[i])) ++countNaN;
if (countNaN>0){
std::cout<<" checkNaN result: "<<countNaN<<" out of "<<n<<" ("<< 100*ComputeT(countNaN)/n<< "\045) values are NaN, "<<n-countNaN<<" are not NaN."; //<<std::endl;
}
delete [] CPUmem;
return countNaN;
}
std::vector<size_t> randperm(size_t n, std::mt19937& rng){
std::vector<size_t> v(n);
for (size_t i=0;i<n;++i) v[i]=i;
shuffle ( v.begin(), v.end(), rng );
return v;
}
template <typename T>
std::vector<size_t> sort_indexes(const std::vector<T> &v) {
// initialize original index locations
std::vector<size_t> idx(v.size());
for (size_t i = 0; i != idx.size(); ++i) idx[i] = i;
// sort indexes based on comparing values in v
std::sort(idx.begin(), idx.end(), [&v](size_t i1, size_t i2) {return v[i1] < v[i2];});
return idx;
}
std::string int_to_str(const int i) {
std::ostringstream s;
s << i;
return s.str();
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// CUDA kernels
//////////////////////////////////////////////////////////////////////////////////////////////////
#define CUDA_NUM_THREADS 512
#define MAX_NUM_BLOCKS 2880
inline int CUDA_GET_BLOCKS(const size_t N) {
return min(MAX_NUM_BLOCKS, int((N + size_t(CUDA_NUM_THREADS) - 1) / CUDA_NUM_THREADS));
}
inline size_t CUDA_GET_LOOPS(const size_t N) {
size_t total_threads = CUDA_GET_BLOCKS(N)*CUDA_NUM_THREADS;
return (N + total_threads -1)/ total_threads;
}
__global__ void Accuracy_MultinomialLogistic(
size_t CUDA_NUM_LOOPS, size_t N, int C, int M, size_t wN,
const StorageT *pred, const StorageT *label, const StorageT *weight,
const StorageT *weightTensor, StorageT *loss) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
int l = int(GPUStorage2ComputeT(label[idx]));
int baseID = (idx / M) * C * M + idx % M;
int elementID = baseID + l * M;
ComputeT prob = GPUStorage2ComputeT(pred[elementID]);
loss[idx] = GPUCompute2StorageT(1);
for (int d = 0; d < C; ++d) {
if (GPUStorage2ComputeT(pred[baseID + d * M]) > prob) {
loss[idx] = GPUCompute2StorageT(0);
}
}
if (weight != NULL) {
loss[idx] = GPUCompute2StorageT(GPUStorage2ComputeT(loss[idx]) *
GPUStorage2ComputeT(weight[l]));
}
if (weightTensor != NULL) {
loss[idx] = GPUCompute2StorageT(GPUStorage2ComputeT(loss[idx]) *
GPUStorage2ComputeT(
weightTensor[idx % wN]));
}
}
}
__global__ void Loss_MultinomialLogistic(
size_t CUDA_NUM_LOOPS, size_t N, int C, int M, size_t wN,
const StorageT* pred, const StorageT* label, const StorageT* weight,
const StorageT *weightTensor, StorageT *loss) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
int l = int(GPUStorage2ComputeT(label[idx]));
int offset = l * M + (idx % M);
int elementID = (idx / M) * C * M + offset;
ComputeT prob = max(GPUStorage2ComputeT(pred[elementID]), ComputeT_MIN);
ComputeT res = log(prob);
if (weight != NULL) res *= GPUStorage2ComputeT(weight[l]);
if (weightTensor != NULL)
res *= GPUStorage2ComputeT(weightTensor[elementID % wN]);
loss[idx] = GPUCompute2StorageT(res);
}
}
__global__ void LossGrad_MultinomialLogistic(
size_t CUDA_NUM_LOOPS, size_t N, int C, int M, size_t wN, ComputeT scale,
const StorageT *pred, const StorageT *label, const StorageT *weight,
const StorageT *weightTensor, StorageT *diff) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
int l = int(GPUStorage2ComputeT(label[idx]));
int offset = l * M + (idx % M);
int elementID = (idx / M) * C * M + offset;
ComputeT prob = max(GPUStorage2ComputeT(pred[elementID]), ComputeT_MIN);
if (weight != NULL) scale *= GPUStorage2ComputeT(weight[l]);
if (weightTensor != NULL)
scale *= GPUStorage2ComputeT(weightTensor[elementID % wN]);
diff[elementID] = GPUCompute2StorageT(
GPUStorage2ComputeT(diff[elementID]) + scale / prob);
}
}
// for numerical stability: http://freemind.pluskid.org/machine-learning/softmax-vs-softmax-loss-numerical-stability/
__global__ void LossGrad_MultinomialLogistic_StableSoftmax(
size_t CUDA_NUM_LOOPS, size_t N, int C, int M, size_t wN, ComputeT scale,
const StorageT *pred, const StorageT *label, const StorageT *weight,
const StorageT *weightTensor, StorageT *diff) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
int l = int(GPUStorage2ComputeT(label[idx]));
int modM = idx % M;
int baseID = (idx / M) * C * M + modM;
int elementID = baseID + l * M;
if (weight != NULL) {
scale *= GPUStorage2ComputeT(weight[l]);
}
if (weightTensor == NULL) {
for (int d = 0; d < C; ++d) {
int k = baseID + d * M;
diff[k] = GPUCompute2StorageT(GPUStorage2ComputeT(diff[k]) +
scale *
GPUStorage2ComputeT(pred[k]));
}
diff[elementID] = GPUCompute2StorageT(
GPUStorage2ComputeT(diff[elementID]) - scale);
} else {
for (int d = 0; d < C; ++d) {
int k = baseID + d * M;
diff[k] = GPUCompute2StorageT(GPUStorage2ComputeT(diff[k]) +
scale *
GPUStorage2ComputeT(pred[k]) *
GPUStorage2ComputeT(
weightTensor[k % wN]));
}
diff[elementID] = GPUCompute2StorageT(
GPUStorage2ComputeT(diff[elementID]) -
scale * GPUStorage2ComputeT(weightTensor[elementID % wN]));
}
}
}
__global__ void Loss_SmoothL1(size_t CUDA_NUM_LOOPS, size_t N,
const StorageT *pred, const StorageT *target,
const StorageT *weight, StorageT *loss) {
// diff = f( weight * (pred - target) )
// f(x) = 0.5 * x^2 if |x| < 1
// |x| - 0.5 otherwise
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
ComputeT val =
GPUStorage2ComputeT(pred[idx]) - GPUStorage2ComputeT(target[idx]);
if (weight != NULL) val *= GPUStorage2ComputeT(weight[idx]);
ComputeT abs_val = abs(val);
if (abs_val < 1) {
loss[idx] = GPUCompute2StorageT(0.5 * val * val);
} else {
loss[idx] = GPUCompute2StorageT(abs_val - 0.5);
}
}
}
__global__ void Loss_EuclideanSSE(size_t CUDA_NUM_LOOPS, size_t N,
const StorageT *pred, const StorageT *target,
const StorageT *weight, StorageT *loss) {
// diff = f( weight * (pred - target) )
// f(x) = 0.5 * x^2
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
ComputeT val =
GPUStorage2ComputeT(pred[idx]) - GPUStorage2ComputeT(target[idx]);
if (weight != NULL) val *= GPUStorage2ComputeT(weight[idx]);
loss[idx] = GPUCompute2StorageT(0.5 * val * val);
}
}
__global__ void LossGrad_SmoothL1(
size_t CUDA_NUM_LOOPS, size_t N, ComputeT scale, const StorageT *pred,
const StorageT *target, const StorageT *weight, StorageT *diff) {
// diff = scale * f'( weight * (pred - target) )
// f'(x) = x if |x| < 1
// = sign(x) otherwise
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
ComputeT val =
GPUStorage2ComputeT(pred[idx]) - GPUStorage2ComputeT(target[idx]);
if (weight != NULL) val *= GPUStorage2ComputeT(weight[idx]);
ComputeT abs_val = abs(val);
if (abs_val < 1) {
diff[idx] = GPUCompute2StorageT(
GPUStorage2ComputeT(diff[idx]) + scale * val);
} else {
diff[idx] = GPUCompute2StorageT(GPUStorage2ComputeT(diff[idx]) +
scale * ((ComputeT(0) < val) -
(val < ComputeT(0))));
}
}
}
__global__ void LossGrad_EuclideanSSE(
size_t CUDA_NUM_LOOPS, size_t N, ComputeT scale, const StorageT *pred,
const StorageT *target, const StorageT *weight, StorageT *diff) {
// diff = scale * f'( weight * (pred - target) )
// f'(x) = x
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
ComputeT val =
GPUStorage2ComputeT(pred[idx]) - GPUStorage2ComputeT(target[idx]);
if (weight != NULL) val *= GPUStorage2ComputeT(weight[idx]);
diff[idx] = GPUCompute2StorageT(GPUStorage2ComputeT(diff[idx]) + scale * val);
}
}
__global__ void Loss_Contrastive(
size_t CUDA_NUM_LOOPS, size_t N, int C, ComputeT margin, const StorageT *a,
const StorageT *b, const StorageT *y, StorageT *loss) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
ComputeT d = 0.0;
for (int c = 0; c < C; ++c) {
int i = idx * C + c;
ComputeT d_i =
GPUStorage2ComputeT(a[i]) - GPUStorage2ComputeT(b[i]);
d += d_i * d_i;
}
ComputeT y_n = GPUStorage2ComputeT(y[idx]);
ComputeT p = max(margin - sqrt(d), ComputeT(0));
loss[idx] = GPUCompute2StorageT(
ComputeT(0.5) * (y_n * d + (ComputeT(1) - y_n) * p * p));
}
}
__global__ void LossGrad_Contrastive(
size_t CUDA_NUM_LOOPS, size_t N, int C, ComputeT margin, ComputeT scale,
const StorageT *a, const StorageT *b, const StorageT *y, StorageT *a_diff,
StorageT *b_diff) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) *
(size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) +
size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N, idxBase + CUDA_NUM_LOOPS); ++idx) {
if ((int) (GPUStorage2ComputeT(y[idx]))) {
for (int c = 0; c < C; ++c) {
int i = idx * C + c;
ComputeT diff_i =
GPUStorage2ComputeT(a[i]) - GPUStorage2ComputeT(b[i]);
ComputeT beta = scale * diff_i;
a_diff[i] = GPUCompute2StorageT(
GPUStorage2ComputeT(a_diff[i]) + beta);
b_diff[i] = GPUCompute2StorageT(
GPUStorage2ComputeT(b_diff[i]) - beta);
}
} else {
ComputeT dist_sq = 0.0;
for (int c = 0; c < C; ++c) {
int i = idx * C + c;
ComputeT diff_i =
GPUStorage2ComputeT(a[i]) - GPUStorage2ComputeT(b[i]);
dist_sq += diff_i * diff_i;
}
ComputeT dist = sqrt(dist_sq);
ComputeT mdist = margin - dist;
if (mdist > 0.0) {
for (int c = 0; c < C; ++c) {
int i = idx * C + c;
ComputeT diff_i =
GPUStorage2ComputeT(a[i]) - GPUStorage2ComputeT(b[i]);
ComputeT beta =
-scale * mdist / (dist + ComputeT(1e-4)) * diff_i;
a_diff[i] = GPUCompute2StorageT(
GPUStorage2ComputeT(a_diff[i]) + beta);
b_diff[i] = GPUCompute2StorageT(
GPUStorage2ComputeT(b_diff[i]) - beta);
}
}
}
}
}
__global__ void Kernel_OpenCV_BGR_image_to_Marvin(size_t CUDA_NUM_LOOPS, size_t N, size_t channels, size_t height, size_t width, const uint8_t* pIn, uint8_t* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
size_t chn = 2 - (idx % 3);
size_t col = (idx/3)%width;
size_t row = (idx/(3*width));
pOut[(chn*height+row)*width+col] = pIn[idx];
}
}
void OpenCV_BGR_image_to_Marvin(size_t channels, size_t height, size_t width, const uint8_t* pIn, uint8_t* pOut){
size_t N = channels * height * width;
Kernel_OpenCV_BGR_image_to_Marvin<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS >>>(CUDA_GET_LOOPS(N), N, channels, height, width, pIn, pOut);
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const half* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(__half2float(pIn[idx])) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(__half2float(pIn[idx])) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const float* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const double* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const uint8_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const uint16_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const uint32_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const uint64_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const int8_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const int16_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const int32_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const int64_t* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const char* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_convert_to_StorageT_subtract(size_t CUDA_NUM_LOOPS, size_t N, size_t sizeofitem, const bool* pIn, const StorageT* pMean, StorageT* pOut) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x)); if (idxBase >= N) return;
if (pMean==NULL) for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) );
else for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ) pOut[idx] = GPUCompute2StorageT( ComputeT(pIn[idx]) - GPUStorage2ComputeT(pMean[idx % sizeofitem]) );
}
__global__ void Kernel_set_one_hot(size_t CUDA_NUM_LOOPS, size_t N, StorageT* GPUdst, size_t idx2hot){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
GPUdst[idx] = GPUCompute2StorageT( ComputeT(idx == idx2hot) );
}
}
void GPU_set_one_hot(size_t N, StorageT* GPUdst, size_t idx2hot){
Kernel_set_one_hot<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,GPUdst,idx2hot);
checkCUDA(__LINE__,cudaGetLastError());
}
__global__ void Kernel_set_value(size_t CUDA_NUM_LOOPS, size_t N, StorageT* GPUdst, StorageT value){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
GPUdst[idx] = value;
}
}
void GPU_set_value(size_t N, StorageT* GPUdst, StorageT value){
Kernel_set_value<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,GPUdst,value);
checkCUDA(__LINE__,cudaGetLastError());
}
void GPU_set_ones(size_t N, StorageT* GPUdst){
GPU_set_value(N, GPUdst, CPUCompute2StorageT(1));
}
void GPU_set_zeros(size_t N, StorageT* GPUdst){
GPU_set_value(N, GPUdst, CPUCompute2StorageT(0));
}
__global__ void Kernel_elementwise_multiplication(size_t CUDA_NUM_LOOPS, size_t N, StorageT* GPUdst, const StorageT* GPUsrcA, const StorageT* GPUsrcB){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
GPUdst[idx] = GPUCompute2StorageT( GPUStorage2ComputeT(GPUsrcA[idx]) * GPUStorage2ComputeT(GPUsrcB[idx]));
}
}
void GPU_elementwise_multiplication(size_t N, StorageT* GPUdst, const StorageT* GPUsrcA, const StorageT* GPUsrcB){
Kernel_elementwise_multiplication<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,GPUdst,GPUsrcA,GPUsrcB);
checkCUDA(__LINE__,cudaGetLastError());
}
__global__ void Kernel_elementwise_comparison(size_t CUDA_NUM_LOOPS, size_t N, StorageT* GPUdst, const StorageT* GPUsrcA, const StorageT* GPUsrcB){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
GPUdst[idx] = GPUCompute2StorageT(ComputeT(bool(GPUStorage2ComputeT(GPUdst[idx])) && (GPUStorage2ComputeT(GPUsrcA[idx]) == GPUStorage2ComputeT(GPUsrcB[idx]))));
}
}
void GPU_elementwise_comparison(size_t N, StorageT* GPUdst, const StorageT* GPUsrcA, const StorageT* GPUsrcB){
Kernel_elementwise_comparison<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,GPUdst,GPUsrcA,GPUsrcB);
//checkCUDA(__LINE__,cudaGetLastError());
}
__global__ void Kernel_copyGPUforward(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* in, StorageT* out, int sizeofitem_in, int sizeofitem_out, int offset){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
int out_base = idx*sizeofitem_out+offset;
int in_base = idx*sizeofitem_in;
for(int i=0;i<sizeofitem_in; ++i){
out[out_base + i] = in[in_base + i];
}
}
}
void copyGPUforward(size_t N, const StorageT* in, StorageT* out, int sizeofitem_in, int sizeofitem_out, int offset){
Kernel_copyGPUforward<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,in,out,sizeofitem_in,sizeofitem_out,offset);
}
__global__ void Kernel_copyGPUbackward(size_t CUDA_NUM_LOOPS, size_t N, StorageT* in, const StorageT* out, int sizeofitem_in, int sizeofitem_out, int offset){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
int in_base = idx*sizeofitem_in;
int out_base = idx*sizeofitem_out+offset;
for(int i=0;i<sizeofitem_in; ++i){
in[in_base + i] = GPUCompute2StorageT( GPUStorage2ComputeT(in[in_base + i]) + GPUStorage2ComputeT(out[out_base + i]) );
}
}
}
void copyGPUbackward(size_t N, StorageT* in, const StorageT* out, int sizeofitem_in, int sizeofitem_out, int offset){
Kernel_copyGPUbackward<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,in,out,sizeofitem_in,sizeofitem_out,offset);
}
__global__ void Kernel_elementwise_acc(size_t CUDA_NUM_LOOPS, size_t N, StorageT* GPUdst, const StorageT* GPUsrc){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
GPUdst[idx] = GPUCompute2StorageT( GPUStorage2ComputeT(GPUdst[idx]) + GPUStorage2ComputeT(GPUsrc[idx]) );
}
}
__global__ void Kernel_ROIforward_2D(size_t CUDA_NUM_LOOPS, size_t N, StorageT* out, const StorageT* in, const StorageT* start, int od1, int od2, int od3, int id1, int id2, int id3){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t o = idxBase; o < min(N,idxBase+CUDA_NUM_LOOPS); ++o ){
int n = (o / (od1*od2*od3));
int o1 = (o / ( od2*od3)) % od1;
int o2 = (o / od3 ) % od2;
int o3 = (o ) % od3;
int i1 = o1 + ((int)(GPUStorage2ComputeT(start[n*3+0])));
int i2 = o2 + ((int)(GPUStorage2ComputeT(start[n*3+1])));
int i3 = o3 + ((int)(GPUStorage2ComputeT(start[n*3+2])));
int i = i3 + ( i2 + ( i1 + n * id1 ) * id2 ) * id3;
out[o] = in[i];
}
}
__global__ void Kernel_ROIforward_3D(size_t CUDA_NUM_LOOPS, size_t N, StorageT* out, const StorageT* in, const StorageT* start, int od1, int od2, int od3, int od4, int id1, int id2, int id3, int id4){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t o = idxBase; o < min(N,idxBase+CUDA_NUM_LOOPS); ++o ){
int n = (o / (od1*od2*od3*od4));
int o1 = (o / ( od2*od3*od4)) % od1;
int o2 = (o / ( od3*od4)) % od2;
int o3 = (o / ( od4)) % od3;
int o4 = (o ) % od4;
int i1 = o1 + ((int)(GPUStorage2ComputeT(start[n*4+0])));
int i2 = o2 + ((int)(GPUStorage2ComputeT(start[n*4+1])));
int i3 = o3 + ((int)(GPUStorage2ComputeT(start[n*4+2])));
int i4 = o4 + ((int)(GPUStorage2ComputeT(start[n*4+3])));
int i = i4 + (i3 + ( i2 + ( i1 + n * id1 ) * id2 ) * id3 ) * id4;
out[o] = in[i];
}
}
__global__ void Kernel_ROIforward_4D(size_t CUDA_NUM_LOOPS, size_t N, StorageT* out, const StorageT* in, const StorageT* start, int od1, int od2, int od3, int od4, int od5, int id1, int id2, int id3, int id4, int id5){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t o = idxBase; o < min(N,idxBase+CUDA_NUM_LOOPS); ++o ){
int n = (o / (od1*od2*od3*od4*od5));
int o1 = (o / ( od2*od3*od4*od5)) % od1;
int o2 = (o / ( od3*od4*od5)) % od2;
int o3 = (o / ( od4*od5)) % od3;
int o4 = (o / ( od5)) % od4;
int o5 = (o ) % od5;
int i1 = o1 + ((int)(GPUStorage2ComputeT(start[n*5+0])));
int i2 = o2 + ((int)(GPUStorage2ComputeT(start[n*5+1])));
int i3 = o3 + ((int)(GPUStorage2ComputeT(start[n*5+2])));
int i4 = o4 + ((int)(GPUStorage2ComputeT(start[n*5+3])));
int i5 = o5 + ((int)(GPUStorage2ComputeT(start[n*5+4])));
int i = i5 + (i4 + (i3 + ( i2 + ( i1 + n * id1 ) * id2 ) * id3 ) * id4) * id5;
out[o] = in[i];
}
}
__global__ void Kernel_ROIbackward_2D(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* out, StorageT* in, const StorageT* start, int od1, int od2, int od3, int id1, int id2, int id3){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t o = idxBase; o < min(N,idxBase+CUDA_NUM_LOOPS); ++o ){
int n = (o / (od1*od2*od3));
int o1 = (o / ( od2*od3)) % od1;
int o2 = (o / od3 ) % od2;
int o3 = (o ) % od3;
int i1 = o1 + ((int)(GPUStorage2ComputeT(start[n*3+0])));
int i2 = o2 + ((int)(GPUStorage2ComputeT(start[n*3+1])));
int i3 = o3 + ((int)(GPUStorage2ComputeT(start[n*3+2])));
int i = i3 + ( i2 + ( i1 + n * id1 ) * id2 ) * id3;
in[i] = GPUCompute2StorageT( GPUStorage2ComputeT(in[i]) + GPUStorage2ComputeT(out[o]) );
}
}
__global__ void Kernel_ROIbackward_3D(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* out, StorageT* in, const StorageT* start, int od1, int od2, int od3, int od4, int id1, int id2, int id3, int id4){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t o = idxBase; o < min(N,idxBase+CUDA_NUM_LOOPS); ++o ){
int n = (o / (od1*od2*od3*od4));
int o1 = (o / ( od2*od3*od4)) % od1;
int o2 = (o / ( od3*od4)) % od2;
int o3 = (o / ( od4)) % od3;
int o4 = (o ) % od4;
int i1 = o1 + ((int)(GPUStorage2ComputeT(start[n*4+0])));
int i2 = o2 + ((int)(GPUStorage2ComputeT(start[n*4+1])));
int i3 = o3 + ((int)(GPUStorage2ComputeT(start[n*4+2])));
int i4 = o4 + ((int)(GPUStorage2ComputeT(start[n*4+3])));
int i = i4 + (i3 + ( i2 + ( i1 + n * id1 ) * id2 ) * id3 ) * id4;
in[i] = GPUCompute2StorageT( GPUStorage2ComputeT(in[i]) + GPUStorage2ComputeT(out[o]) );
}
}
__global__ void Kernel_ROIbackward_4D(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* out, StorageT* in, const StorageT* start, int od1, int od2, int od3, int od4, int od5, int id1, int id2, int id3, int id4, int id5){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t o = idxBase; o < min(N,idxBase+CUDA_NUM_LOOPS); ++o ){
int n = (o / (od1*od2*od3*od4*od5));
int o1 = (o / ( od2*od3*od4*od5)) % od1;
int o2 = (o / ( od3*od4*od5)) % od2;
int o3 = (o / ( od4*od5)) % od3;
int o4 = (o / ( od5)) % od4;
int o5 = (o ) % od5;
int i1 = o1 + ((int)(GPUStorage2ComputeT(start[n*5+0])));
int i2 = o2 + ((int)(GPUStorage2ComputeT(start[n*5+1])));
int i3 = o3 + ((int)(GPUStorage2ComputeT(start[n*5+2])));
int i4 = o4 + ((int)(GPUStorage2ComputeT(start[n*5+3])));
int i5 = o5 + ((int)(GPUStorage2ComputeT(start[n*5+4])));
int i = i5 + (i4 + (i3 + ( i2 + ( i1 + n * id1 ) * id2 ) * id3 ) * id4) * id5;
in[i] = GPUCompute2StorageT( GPUStorage2ComputeT(in[i]) + GPUStorage2ComputeT(out[o]) );
}
}
__global__ void CoeffElementWiseSumReplace(size_t CUDA_NUM_LOOPS, size_t N, const ComputeT coeff, const StorageT* coeff_data, const size_t num_offset, const size_t dim, const StorageT* in, StorageT* out) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
const ComputeT final_coeff = coeff_data ? ( GPUStorage2ComputeT(coeff_data[num_offset + idx / dim]) * coeff) : coeff;
out[idx] = GPUCompute2StorageT( GPUStorage2ComputeT(in[idx]) * final_coeff );
}
}
__global__ void CoeffElementWiseSumAccumulate(size_t CUDA_NUM_LOOPS, size_t N, const ComputeT coeff, const StorageT* coeff_data, const size_t num_offset, const size_t dim, const StorageT* in, StorageT* out) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
const ComputeT final_coeff = coeff_data ? ( GPUStorage2ComputeT(coeff_data[num_offset + idx / dim]) * coeff) : coeff;
out[idx] = GPUCompute2StorageT(GPUStorage2ComputeT(out[idx]) + GPUStorage2ComputeT(in[idx]) * final_coeff );
}
}
/* ----------------------------------------------------------------------------
* The following four functions are inspired by Ross Girshick's Fast-RCNN code,
* which is copyrighted by Microsoft under an MIT License.
*
* Project page: https://github.com/rbgirshick/fast-rcnn
* License page: https://github.com/rbgirshick/fast-rcnn/blob/master/LICENSE
* ----------------------------------------------------------------------------
*/
__global__ void Kernel_ROIPoolForward_2D(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* in_data, const StorageT* in_rois, StorageT* out_data, size_t* argmax_data, const ComputeT spatial_scale, const int channels, const int height, const int width, const int pooled_height, const int pooled_width){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t index = idxBase; index < min(N,idxBase+CUDA_NUM_LOOPS); ++index ){
// (n, c, ph, pw) is an element in the pooled output
int pw = (index) % pooled_width;
int ph = (index / pooled_width) % pooled_height;
int c = (index / pooled_width / pooled_height) % channels;
int n = (index / pooled_width / pooled_height / channels);
int roi_5n = n*5;
int roi_batch_ind = GPUStorage2ComputeT(in_rois[roi_5n+0]);
int roi_start_h = ::round(GPUStorage2ComputeT(in_rois[roi_5n+1]) * spatial_scale);
int roi_end_h = ::round(GPUStorage2ComputeT(in_rois[roi_5n+2]) * spatial_scale);
int roi_start_w = ::round(GPUStorage2ComputeT(in_rois[roi_5n+3]) * spatial_scale);
int roi_end_w = ::round(GPUStorage2ComputeT(in_rois[roi_5n+4]) * spatial_scale);
// Force malformed ROIs to be 1x1
int roi_width = max(roi_end_w - roi_start_w + 1, 1);
int roi_height = max(roi_end_h - roi_start_h + 1, 1);
ComputeT bin_size_h = static_cast<ComputeT>(roi_height) / static_cast<ComputeT>(pooled_height);
ComputeT bin_size_w = static_cast<ComputeT>(roi_width) / static_cast<ComputeT>(pooled_width);
int hstart = static_cast<int>(floor(static_cast<ComputeT>(ph) * bin_size_h));
int wstart = static_cast<int>(floor(static_cast<ComputeT>(pw) * bin_size_w));
int hend = static_cast<int>(ceil(static_cast<ComputeT>(ph + 1) * bin_size_h));
int wend = static_cast<int>(ceil(static_cast<ComputeT>(pw + 1) * bin_size_w));
// Add roi offsets and clip to input boundaries
hstart = min(max(hstart + roi_start_h, 0), height);
hend = min(max(hend + roi_start_h, 0), height);
wstart = min(max(wstart + roi_start_w, 0), width);
wend = min(max(wend + roi_start_w, 0), width);
bool is_empty = (hend <= hstart) || (wend <= wstart);
// Define an empty pooling region to be zero
ComputeT maxval = is_empty ? 0 : -FLT_MAX;
// If nothing is pooled, argmax = -1 causes nothing to be backprop'd
size_t maxidx = SIZE_MAX;
size_t in_offset = (roi_batch_ind * channels + c) * height * width;
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
size_t in_index = in_offset + h * width + w;
ComputeT v = GPUStorage2ComputeT(in_data[in_index]);
if (v > maxval) {
maxval = v;
maxidx = in_index;
}
}
}
out_data[index] = GPUCompute2StorageT(maxval);
if (argmax_data!=NULL) argmax_data[index] = maxidx;
}
}
__global__ void Kernel_ROIPoolForward_3D(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* in_data, const StorageT* in_rois, StorageT* out_data, size_t* argmax_data, const ComputeT spatial_scale, const int channels, const int depth, const int height, const int width, const int pooled_depth, const int pooled_height, const int pooled_width){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t index = idxBase; index < min(N,idxBase+CUDA_NUM_LOOPS); ++index ){
// (n, c, pd, ph, pw) is an element in the pooled output
int pw = (index) % pooled_width;
int ph = (index / pooled_width) % pooled_height;
int pd = (index / pooled_width / pooled_height) % pooled_depth;
int c = (index / pooled_width / pooled_height / pooled_depth ) % channels;
int n = (index / pooled_width / pooled_height / pooled_depth / channels);
int roi_7n = n * 7;
int roi_batch_ind = GPUStorage2ComputeT(in_rois[roi_7n+0]);
int roi_start_d = ::round(GPUStorage2ComputeT(in_rois[roi_7n+1]) * spatial_scale);
int roi_end_d = ::round(GPUStorage2ComputeT(in_rois[roi_7n+2]) * spatial_scale);
int roi_start_h = ::round(GPUStorage2ComputeT(in_rois[roi_7n+3]) * spatial_scale);
int roi_end_h = ::round(GPUStorage2ComputeT(in_rois[roi_7n+4]) * spatial_scale);
int roi_start_w = ::round(GPUStorage2ComputeT(in_rois[roi_7n+5]) * spatial_scale);
int roi_end_w = ::round(GPUStorage2ComputeT(in_rois[roi_7n+6]) * spatial_scale);
// Force malformed ROIs to be 1x1
int roi_depth = max(roi_end_d - roi_start_d + 1, 1);
int roi_width = max(roi_end_w - roi_start_w + 1, 1);
int roi_height = max(roi_end_h - roi_start_h + 1, 1);
ComputeT bin_size_d = static_cast<ComputeT>(roi_depth) / static_cast<ComputeT>(pooled_depth);
ComputeT bin_size_h = static_cast<ComputeT>(roi_height) / static_cast<ComputeT>(pooled_height);
ComputeT bin_size_w = static_cast<ComputeT>(roi_width) / static_cast<ComputeT>(pooled_width);
int dstart = static_cast<int>(floor(static_cast<ComputeT>(pd) * bin_size_d));
int hstart = static_cast<int>(floor(static_cast<ComputeT>(ph) * bin_size_h));
int wstart = static_cast<int>(floor(static_cast<ComputeT>(pw) * bin_size_w));
int dend = static_cast<int>(ceil(static_cast<ComputeT>(pd + 1) * bin_size_d));
int hend = static_cast<int>(ceil(static_cast<ComputeT>(ph + 1) * bin_size_h));
int wend = static_cast<int>(ceil(static_cast<ComputeT>(pw + 1) * bin_size_w));
// Add roi offsets and clip to input boundaries
dstart = min(max(dstart + roi_start_d, 0), depth);
dend = min(max(dend + roi_start_d, 0), depth);
hstart = min(max(hstart + roi_start_h, 0), height);
hend = min(max(hend + roi_start_h, 0), height);
wstart = min(max(wstart + roi_start_w, 0), width);
wend = min(max(wend + roi_start_w, 0), width);
bool is_empty = (dend <= dstart) || (hend <= hstart) || (wend <= wstart);
// Define an empty pooling region to be zero
ComputeT maxval = is_empty ? 0 : -FLT_MAX;
// If nothing is pooled, argmax = -1 causes nothing to be backprop'd
size_t maxidx = SIZE_MAX;
size_t in_offset = (roi_batch_ind * channels + c) * depth * height * width;
for (int d = dstart; d < dend; ++d) {
for (int h = hstart; h < hend; ++h) {
for (int w = wstart; w < wend; ++w) {
size_t in_index = in_offset + d * height * width + h * width + w;
ComputeT v = GPUStorage2ComputeT(in_data[in_index]);
if (v > maxval) {
maxval = v;
maxidx = in_index;
}
}
}
}
out_data[index] = GPUCompute2StorageT(maxval);
if (argmax_data!=NULL) argmax_data[index] = maxidx;
}
}
__global__ void Kernel_ROIPoolBackward_2D(size_t CUDA_NUM_LOOPS, size_t N, StorageT* in_diff, const StorageT* in_rois, const StorageT* out_diff, const size_t* argmax_data, const ComputeT spatial_scale, const int num_rois, const int channels, const int height, const int width, const int pooled_height, const int pooled_width) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t index = idxBase; index < min(N,idxBase+CUDA_NUM_LOOPS); ++index ){
// (n, c, h, w) coords in in data
int w = index % width;
int h = (index / width) % height;
int c = (index / width / height) % channels;
int n = index / width / height / channels;
ComputeT gradient = GPUStorage2ComputeT(in_diff[index]);
// Accumulate gradient over all ROIs that pooled this element
for (int roi_n = 0; roi_n < num_rois; ++roi_n) {
int roi_5n = roi_n*5;
int roi_batch_ind = (int)(GPUStorage2ComputeT(in_rois[roi_5n+0]));
// Skip if ROI's batch index doesn't match n
if (n != roi_batch_ind) {
continue;
}
int roi_start_h = ::round(GPUStorage2ComputeT(in_rois[roi_5n+1]) * spatial_scale);
int roi_end_h = ::round(GPUStorage2ComputeT(in_rois[roi_5n+2]) * spatial_scale);
int roi_start_w = ::round(GPUStorage2ComputeT(in_rois[roi_5n+3]) * spatial_scale);
int roi_end_w = ::round(GPUStorage2ComputeT(in_rois[roi_5n+4]) * spatial_scale);
// Skip if ROI doesn't include (h, w)
const bool in_roi = (w >= roi_start_w && w <= roi_end_w && h >= roi_start_h && h <= roi_end_h);
if (!in_roi) {
continue;
}
size_t offset = (roi_n * channels + c) * pooled_height * pooled_width;
// Compute feasible set of pooled units that could have pooled
// this in unit
// Force malformed ROIs to be 1x1
int roi_width = max(roi_end_w - roi_start_w + 1, 1);
int roi_height = max(roi_end_h - roi_start_h + 1, 1);
ComputeT bin_size_h = static_cast<ComputeT>(roi_height) / static_cast<ComputeT>(pooled_height);
ComputeT bin_size_w = static_cast<ComputeT>(roi_width) / static_cast<ComputeT>(pooled_width);
int phstart = floor(static_cast<ComputeT>(h - roi_start_h) / bin_size_h);
int phend = ceil(static_cast<ComputeT>(h - roi_start_h + 1) / bin_size_h);
int pwstart = floor(static_cast<ComputeT>(w - roi_start_w) / bin_size_w);
int pwend = ceil(static_cast<ComputeT>(w - roi_start_w + 1) / bin_size_w);
phstart = min(max(phstart, 0), pooled_height);
phend = min(max(phend, 0), pooled_height);
pwstart = min(max(pwstart, 0), pooled_width);
pwend = min(max(pwend, 0), pooled_width);
for (int ph = phstart; ph < phend; ++ph) {
for (int pw = pwstart; pw < pwend; ++pw) {
size_t out_index = ph * pooled_width + pw;
if (argmax_data[offset + out_index] == (h * width + w)) {
gradient += GPUStorage2ComputeT(out_diff[offset + out_index]);
}
}
}
}
in_diff[index] = GPUCompute2StorageT(gradient);
}
}
__global__ void Kernel_ROIPoolBackward_3D(size_t CUDA_NUM_LOOPS, size_t N, StorageT* in_diff, const StorageT* in_rois, const StorageT* out_diff, const size_t* argmax_data, const ComputeT spatial_scale, const int num_rois, const int channels, const int depth, const int height, const int width, const int pooled_depth, const int pooled_height, const int pooled_width) {
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t index = idxBase; index < min(N,idxBase+CUDA_NUM_LOOPS); ++index ){
// (n, c, h, w) coords in in data
int w = index % width;
int h = (index / width) % height;
int d = (index / width / height) % depth;
int c = (index / width / height / depth) % channels;
int n = index / width / height / depth / channels;
ComputeT gradient = GPUStorage2ComputeT(in_diff[index]);
// Accumulate gradient over all ROIs that pooled this element
for (int roi_n = 0; roi_n < num_rois; ++roi_n) {
int roi_7n = roi_n*7;
int roi_batch_ind = (int)(GPUStorage2ComputeT(in_rois[roi_7n+0]));
// Skip if ROI's batch index doesn't match n
if (n != roi_batch_ind) {
continue;
}
int roi_start_d = ::round(GPUStorage2ComputeT(in_rois[roi_7n+1]) * spatial_scale);
int roi_end_d = ::round(GPUStorage2ComputeT(in_rois[roi_7n+2]) * spatial_scale);
int roi_start_h = ::round(GPUStorage2ComputeT(in_rois[roi_7n+3]) * spatial_scale);
int roi_end_h = ::round(GPUStorage2ComputeT(in_rois[roi_7n+4]) * spatial_scale);
int roi_start_w = ::round(GPUStorage2ComputeT(in_rois[roi_7n+5]) * spatial_scale);
int roi_end_w = ::round(GPUStorage2ComputeT(in_rois[roi_7n+6]) * spatial_scale);
// Skip if ROI doesn't include (h, w)
const bool in_roi = (w >= roi_start_w && w <= roi_end_w && h >= roi_start_h && h <= roi_end_h && d >= roi_start_d && d <= roi_end_d);
if (!in_roi) {
continue;
}
size_t offset = (roi_n * channels + c) * pooled_depth * pooled_height * pooled_width;
// Compute feasible set of pooled units that could have pooled
// this in unit
// Force malformed ROIs to be 1x1
int roi_width = max(roi_end_w - roi_start_w + 1, 1);
int roi_height = max(roi_end_h - roi_start_h + 1, 1);
int roi_depth = max(roi_end_d - roi_start_d + 1, 1);
ComputeT bin_size_d = static_cast<ComputeT>(roi_depth) / static_cast<ComputeT>(pooled_depth);
ComputeT bin_size_h = static_cast<ComputeT>(roi_height) / static_cast<ComputeT>(pooled_height);
ComputeT bin_size_w = static_cast<ComputeT>(roi_width) / static_cast<ComputeT>(pooled_width);
int pdstart = floor(static_cast<ComputeT>(d - roi_start_d) / bin_size_d);
int pdend = ceil(static_cast<ComputeT>(d - roi_start_d + 1) / bin_size_d);
int phstart = floor(static_cast<ComputeT>(h - roi_start_h) / bin_size_h);
int phend = ceil(static_cast<ComputeT>(h - roi_start_h + 1) / bin_size_h);
int pwstart = floor(static_cast<ComputeT>(w - roi_start_w) / bin_size_w);
int pwend = ceil(static_cast<ComputeT>(w - roi_start_w + 1) / bin_size_w);
pdstart = min(max(pdstart, 0), pooled_depth);
pdend = min(max(pdend, 0), pooled_depth);
phstart = min(max(phstart, 0), pooled_height);
phend = min(max(phend, 0), pooled_height);
pwstart = min(max(pwstart, 0), pooled_width);
pwend = min(max(pwend, 0), pooled_width);
for (int pd = pdstart; pd < pdend; ++pd) {
for (int ph = phstart; ph < phend; ++ph) {
for (int pw = pwstart; pw < pwend; ++pw) {
size_t out_index = (pd * pooled_height + ph) * pooled_width + pw;
if (argmax_data[offset + out_index] == ((d * height + h) * width + w)) {
gradient += GPUStorage2ComputeT(out_diff[offset+out_index]);
}
}
}
}
}
in_diff[index] = GPUCompute2StorageT(gradient);
}
}
__global__ void Kernel_bsa2b(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* a, StorageT* b){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
b[idx] = GPUCompute2StorageT(GPUStorage2ComputeT(b[idx]) - GPUStorage2ComputeT(a[idx]));
}
}
void bsa2b(size_t N, const StorageT* a, StorageT* b){
Kernel_bsa2b<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,a,b);
}
__global__ void Kernel_update_SGDL1(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
ComputeT h = GPUStorage2ComputeT(gradients[idx]);
ComputeT g;
if (w>0) g = decay;
else if (w<0) g = -decay;
else g = 0;
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
gradients[idx] = GPUCompute2StorageT(momentum * h + lr * g);
}
}
__global__ void Kernel_update_SGDL2(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
ComputeT h = GPUStorage2ComputeT(gradients[idx]);
ComputeT g = decay * w; // L2 regularization
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
gradients[idx] = GPUCompute2StorageT(momentum * h + lr * g);
}
}
__global__ void Kernel_update_AdaDeltaL1(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
size_t h2_idx = N*(nNets+2)+idx;
ComputeT h2 = GPUStorage2ComputeT(gradients[h2_idx]);
ComputeT g;
if (w>0) g = decay;
else if (w<0) g = -decay;
else g = 0;
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = momentum * h + (1-momentum)*g*g;
g = g * sqrt( (delta+h2) / (delta+h) );
h2= momentum * h2+ (1-momentum)*g*g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[h2_idx] = GPUCompute2StorageT(h2);
gradients[idx] = GPUCompute2StorageT(lr * g);
}
}
__global__ void Kernel_update_AdaDeltaL2(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
size_t h2_idx = N*(nNets+2)+idx;
ComputeT h2 = GPUStorage2ComputeT(gradients[h2_idx]);
ComputeT g = decay * w; // L2 regularization
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = momentum * h + (1-momentum)*g*g;
g = g * sqrt( (delta+h2) / (delta+h) );
h2= momentum * h2+ (1-momentum)*g*g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[h2_idx] = GPUCompute2StorageT(h2);
gradients[idx] = GPUCompute2StorageT(lr * g);
}
}
__global__ void Kernel_update_AdaGradL1(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
ComputeT u = GPUStorage2ComputeT(gradients[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
ComputeT g;
if (w>0) g = decay;
else if (w<0) g = -decay;
else g = 0;
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = g * g + h;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[idx] = GPUCompute2StorageT(momentum * u + lr * g / (sqrt(h) + delta));
}
}
__global__ void Kernel_update_AdaGradL2(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
ComputeT u = GPUStorage2ComputeT(gradients[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
ComputeT g = decay * w; // L2 regularization
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = g * g + h;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[idx] = GPUCompute2StorageT(momentum * u + lr * g / (sqrt(h) + delta));
}
}
__global__ void Kernel_update_AdamL1(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT momentum2, ComputeT delta, int iter, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
size_t h2_idx = N*(nNets+2)+idx;
ComputeT h2 = GPUStorage2ComputeT(gradients[h2_idx]);
ComputeT g;
if (w>0) g = decay;
else if (w<0) g = -decay;
else g = 0;
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = momentum * h + (1-momentum )*g;
h2= momentum2* h2+ (1-momentum2)*g*g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[h2_idx] = GPUCompute2StorageT(h2);
gradients[idx] = GPUCompute2StorageT(lr * sqrt(1-pow(momentum2,iter)) / (1-pow(momentum,iter)) * h/ (sqrt(h2) + delta));
}
}
__global__ void Kernel_update_AdamL2(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT momentum2, ComputeT delta, int iter, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
size_t h2_idx = N*(nNets+2)+idx;
ComputeT h2 = GPUStorage2ComputeT(gradients[h2_idx]);
ComputeT g = decay * w; // L2 regularization
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = momentum * h + (1-momentum )*g;
h2= momentum2* h2+ (1-momentum2)*g*g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[h2_idx] = GPUCompute2StorageT(h2);
gradients[idx] = GPUCompute2StorageT(lr * sqrt(1-pow(momentum2,iter)) / (1-pow(momentum,iter)) * h/ (sqrt(h2) + delta));
}
}
__global__ void Kernel_update_NAGL1(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
ComputeT g;
if (w>0) g = decay;
else if (w<0) g = -decay;
else g = 0;
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
ComputeT t = h;
h = momentum * h + lr * g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[idx] = GPUCompute2StorageT((1+momentum) * h - momentum * t);
}
}
__global__ void Kernel_update_NAGL2(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
ComputeT g = decay * w; // L2 regularization
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
ComputeT t = h;
h = momentum * h + lr * g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[idx] = GPUCompute2StorageT((1+momentum) * h - momentum * t);
}
}
__global__ void Kernel_update_RMSpropL1(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT rms_decay, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
ComputeT g;
if (w>0) g = decay;
else if (w<0) g = -decay;
else g = 0;
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = rms_decay * h + (1-rms_decay) * g * g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[idx] = GPUCompute2StorageT(lr * g / (sqrt(h) + delta));
}
}
__global__ void Kernel_update_RMSpropL2(size_t CUDA_NUM_LOOPS, size_t N, int nNets, ComputeT decay, ComputeT rms_decay, ComputeT delta, ComputeT lr, const StorageT* weights, StorageT* gradients){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
ComputeT w = GPUStorage2ComputeT(weights[idx]);
size_t h_idx = N*(nNets+1)+idx;
ComputeT h = GPUStorage2ComputeT(gradients[h_idx]);
ComputeT g = decay * w; // L2 regularization
for (int k=1; k<nNets+1; ++k) g += GPUStorage2ComputeT(gradients[N*k+idx]);
h = rms_decay * h + (1-rms_decay) * g * g;
gradients[h_idx] = GPUCompute2StorageT(h);
gradients[idx] = GPUCompute2StorageT(lr * g / (sqrt(h) + delta));
}
}
void update_solver(SolverAlgorithm solver, Regularizer regularizer, int iter, size_t N, int nNets, ComputeT decay, ComputeT momentum, ComputeT momentum2, ComputeT delta, ComputeT rms_decay, ComputeT lr, const StorageT* weights, StorageT* gradients){
switch (solver){
case SGD:
if (regularizer==L1)
Kernel_update_SGDL1<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,lr,weights,gradients);
else
Kernel_update_SGDL2<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,lr,weights,gradients);
break;
case AdaDelta:
if (regularizer==L1)
Kernel_update_AdaDeltaL1<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,delta,lr,weights,gradients);
else
Kernel_update_AdaDeltaL2<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,delta,lr,weights,gradients);
break;
case AdaGrad:
if (regularizer==L1)
Kernel_update_AdaGradL1<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,delta,lr,weights,gradients);
else
Kernel_update_AdaGradL2<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,delta,lr,weights,gradients);
break;
case Adam:
if (regularizer==L1)
Kernel_update_AdamL1<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,momentum2,delta,iter+1,lr,weights,gradients);
else
Kernel_update_AdamL2<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,momentum2,delta,iter+1,lr,weights,gradients);
break;
case NAG:
if (regularizer==L1)
Kernel_update_NAGL1<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,delta,lr,weights,gradients);
else
Kernel_update_NAGL2<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,momentum,delta,lr,weights,gradients);
break;
case RMSprop:
if (regularizer==L1)
Kernel_update_RMSpropL1<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,rms_decay,delta,lr,weights,gradients);
else
Kernel_update_RMSpropL2<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,nNets,decay,rms_decay,delta,lr,weights,gradients);
break;
}
checkCUDA(__LINE__,cudaGetLastError());
}
__global__ void Kernel_xpy(size_t CUDA_NUM_LOOPS, size_t N, const StorageT* x, StorageT* y){
const size_t idxBase = size_t(CUDA_NUM_LOOPS) * (size_t(CUDA_NUM_THREADS) * size_t(blockIdx.x) + size_t(threadIdx.x));
if (idxBase >= N) return;
for (size_t idx = idxBase; idx < min(N,idxBase+CUDA_NUM_LOOPS); ++idx ){
y[idx] = GPUCompute2StorageT( GPUStorage2ComputeT(y[idx]) + GPUStorage2ComputeT(x[idx]));
}
}
void xpy(size_t N, const StorageT* x, StorageT* y){
Kernel_xpy<<<CUDA_GET_BLOCKS(N), CUDA_NUM_THREADS>>>(CUDA_GET_LOOPS(N),N,x,y);
checkCUDA(__LINE__,cudaGetLastError());
}
__global__ void Kernel_maxElement(size_t N, const StorageT *x, size_t* pMaxID, ComputeT* pMaxValue){
const size_t idx = CUDA_NUM_THREADS * blockIdx.x + threadIdx.x;
if (idx > 0) return;
//printf("%d %f\n", 0, GPUStorage2ComputeT(x[0]) );
ComputeT maxValue = GPUStorage2ComputeT(x[0]);
size_t maxID = 0;
for (size_t i=1;i<N;++i){
if (GPUStorage2ComputeT(x[i])>maxValue){
maxValue = GPUStorage2ComputeT(x[i]);
maxID = i;
}
//printf("%d %f %d\n", i, GPUStorage2ComputeT(x[i]), maxID);
}
if (pMaxID!=NULL) *pMaxID = maxID;
if (pMaxValue!=NULL) *pMaxValue = maxValue;
}
void GPU_maxElement(size_t N, const StorageT *x, size_t* cpuMaxID, ComputeT* cpuMaxValue){
size_t* gpuMaxID; cudaMalloc(&gpuMaxID, sizeof(size_t));
ComputeT* gpuMaxValue; cudaMalloc(&gpuMaxValue, sizeof(ComputeT));
Kernel_maxElement<<<1,1>>>(N, x, gpuMaxID, gpuMaxValue);
cudaMemcpy(cpuMaxID, gpuMaxID, sizeof(size_t), cudaMemcpyDeviceToHost); cudaFree(gpuMaxID);
cudaMemcpy(cpuMaxValue, gpuMaxValue, sizeof(ComputeT), cudaMemcpyDeviceToHost); cudaFree(gpuMaxValue);
}
__global__ void Kernel_Hasum(size_t N, const half *x, int incx, float *result){
const int i = CUDA_NUM_THREADS * blockIdx.x + threadIdx.x;
if (i > 0) return;
float r = 0;
for (int i=0;i<N;++i){
r += fabsf( __half2float(x[i*incx]) );
}
*result = r;
}
cublasStatus_t Hasum(cublasHandle_t handle, int n, const half *x, int incx, float *result){
float* answer;
cudaMalloc(&answer, sizeof(float));
Kernel_Hasum<<<1,1>>>(n, x, incx, answer);
cudaMemcpy(result, answer, sizeof(float), cudaMemcpyDeviceToHost);
cudaFree(answer);
return CUBLAS_STATUS_SUCCESS;
}
cublasStatus_t Hgemm(cublasHandle_t handle, cublasOperation_t transa, cublasOperation_t transb, int m, int n, int k, const float *alpha, const half *A, int lda, const half *B, int ldb, const float *beta, half *C, int ldc){
#if CUDA_VERSION >= 8000
return cublasSgemmEx(handle, transa, transb, m, n, k, alpha, A, CUDA_R_16F, lda, B, CUDA_R_16F, ldb, beta, C, CUDA_R_16F, ldc);
#else
return cublasSgemmEx(handle, transa, transb, m, n, k, alpha, A, CUBLAS_DATA_HALF, lda, B, CUBLAS_DATA_HALF, ldb, beta, C, CUBLAS_DATA_HALF, ldc);
#endif
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// File format
//////////////////////////////////////////////////////////////////////////////////////////////////
uint8_t typeID(std::type_index t){
if (t==typeid(half)) return uint8_t(0);
if (t==typeid(float)) return uint8_t(1);
if (t==typeid(double)) return uint8_t(2);
if (t==typeid(uint8_t)) return uint8_t(3);
if (t==typeid(uint16_t)) return uint8_t(4);
if (t==typeid(uint32_t)) return uint8_t(5);
if (t==typeid(uint64_t)) return uint8_t(6);
if (t==typeid(int8_t)) return uint8_t(7);
if (t==typeid(int16_t)) return uint8_t(8);
if (t==typeid(int32_t)) return uint8_t(9);
if (t==typeid(int64_t)) return uint8_t(10);
if (t==typeid(char)) return uint8_t(11);
if (t==typeid(bool)) return uint8_t(12);
FatalError(__LINE__); return uint8_t(255);
}
uint8_t readTypeID(std::string filename){
FILE* fp = fopen(filename.c_str(),"rb");
while (fp==NULL) {
std::cerr<<"readTypeID: fail to open file "<<filename<<". Please provide it first. Will retry after 5 seconds."<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
fp = fopen(filename.c_str(),"rb");
}
size_t read_cnt;
uint8_t fpTypeid; read_cnt = fread((void*)(&fpTypeid), sizeof(uint8_t), 1, fp); if (read_cnt!=1) { std::cerr<<"Error at readTypeID: no data type. "<<std::endl; FatalError(__LINE__); }
fclose(fp);
return fpTypeid;
}
template <class T>
class Tensor{
public:
std::vector<int> dim;
T* CPUmem;
std::string name;
// compile will check if your time is not correct for writeGPU and readGPU
void writeGPU(T* GPUmem){
cudaMemcpy(GPUmem, CPUmem, numel()*sizeof(T), cudaMemcpyHostToDevice);
};
void readGPU(T* GPUmem){
cudaMemcpy(CPUmem, GPUmem, numel()*sizeof(T), cudaMemcpyDeviceToHost);
};
Tensor(): CPUmem(NULL){};
size_t numel(){ return marvin::numel(dim); };
size_t numBytes(){ return sizeof(T)*numel(); };
int numofitems(){ return dim[0]; };
size_t sizeofitem(){ return marvin::sizeofitem(dim); };
~Tensor(){
if (CPUmem!=NULL) delete[] CPUmem;
};
void initialize(T val){
for (size_t i=0;i<numel();++i){
CPUmem[i]=val;
}
};
size_t readHeader(FILE* fp){
size_t read_cnt;
uint8_t myTypeid = typeID(typeid(T));
uint32_t myTypesizeof = uint32_t(sizeof(T));
uint8_t fpTypeid; read_cnt = fread((void*)(&fpTypeid), sizeof(uint8_t), 1, fp); if (read_cnt!=1) { std::cerr<<"Error at Tensor::readHeader: no data type. "<<std::endl; FatalError(__LINE__); }
uint32_t fpTypesizeof; read_cnt = fread((void*)(&fpTypesizeof), sizeof(uint32_t), 1, fp); if (read_cnt!=1) { std::cerr<<"Error at Tensor::readHeader: no data size. "<<std::endl; FatalError(__LINE__); }
int lenName;
read_cnt = fread((void*)(&lenName), sizeof(int), 1, fp);
if (read_cnt!=1) { std::cerr<<"Error at Tensor::readHeader: wrong data type. "<<std::endl; FatalError(__LINE__); }
name.resize(lenName);
if (lenName>0){
read_cnt = fread((void*)(name.data()), sizeof(char), lenName, fp);
if (read_cnt!=lenName) { std::cerr<<"Error at Tensor::readHeader: wrong data type. "<<std::endl; FatalError(__LINE__); }
}
int nbDims;
read_cnt = fread((void*)(&nbDims), sizeof(int), 1, fp);
if (read_cnt!=1) { std::cerr<<"Error at Tensor::readHeader: wrong data type. "<<std::endl; FatalError(__LINE__); }
dim.resize(nbDims);
if (nbDims>0){
read_cnt = fread((void*)(&dim[0]), sizeof(int), nbDims, fp);
if (read_cnt!=nbDims) { std::cerr<<"Error at Tensor::readHeader: wrong data type. "<<std::endl; FatalError(__LINE__); }
}
size_t headerBytes = sizeof(uint8_t) + sizeof(uint32_t) + sizeof(int) + lenName*sizeof(char) + sizeof(int) + nbDims*sizeof(int);
if (myTypeid!=fpTypeid || myTypesizeof!=fpTypesizeof){
std::cerr<<"Error at Tensor::readHeader: wrong data type. "<<std::endl; FatalError(__LINE__);
}
return headerBytes;
};
//support continuous read across many NdTensors
T* read(FILE* fp,int batch_size=1){
if (CPUmem!=NULL){
delete[] CPUmem;
CPUmem = NULL;
}
size_t read_cnt;
uint8_t myTypeid = typeID(typeid(T));
uint32_t myTypesizeof = uint32_t(sizeof(T));
uint8_t fpTypeid; read_cnt = fread((void*)(&fpTypeid), sizeof(uint8_t), 1, fp); if (read_cnt!=1) return NULL;
uint32_t fpTypesizeof; read_cnt = fread((void*)(&fpTypesizeof), sizeof(uint32_t), 1, fp); if (read_cnt!=1) return NULL;
if (myTypeid!=fpTypeid || myTypesizeof!=fpTypesizeof){
if (myTypeid==fpTypeid && myTypesizeof!=fpTypesizeof){ std::cerr<<"Tensor read error: same type but different sizeof, maybe different computer architecture. "<<std::endl; FatalError(__LINE__);}
//if (myTypeid!=fpTypeid){ std::cerr<<"Tensor read error: different types. "<<std::endl; FatalError(__LINE__); }
if (myTypeid==typeID(typeid(half)) && fpTypeid==typeID(typeid(float))){
//std::cout<<std::endl<<"converting from float to half"<<std::endl;
fseek(fp, -(sizeof(uint8_t)+sizeof(uint32_t)), SEEK_CUR);
Tensor<float>* floatTensor = new Tensor<float>(fp);
this->dim = floatTensor->dim ;
this->name = floatTensor->name;
Malloc(batch_size);
for(size_t i=0; i<numel(); ++i){
half v = cpu_float2half(floatTensor->CPUmem[i]);
memcpy(((half*)(CPUmem))+i,&v,sizeof(half));
}
delete floatTensor;
}else if (myTypeid==typeID(typeid(float)) && fpTypeid==typeID(typeid(half))){
fseek(fp, -(sizeof(uint8_t)+sizeof(uint32_t)), SEEK_CUR);
Tensor<half>* halfTensor = new Tensor<half>(fp);
this->dim = halfTensor->dim ;
this->name = halfTensor->name;
Malloc(batch_size);
for(size_t i=0; i<numel(); ++i){
float v = cpu_half2float(halfTensor->CPUmem[i]);
memcpy(((float*)(CPUmem))+i,&v,sizeof(float));
}
delete halfTensor;
}else if (myTypeid==typeID(typeid(double)) && fpTypeid==typeID(typeid(float))){
fseek(fp, -(sizeof(uint8_t)+sizeof(uint32_t)), SEEK_CUR);
Tensor<float>* floatTensor = new Tensor<float>(fp);
this->dim = floatTensor->dim ;
this->name = floatTensor->name;
Malloc(batch_size);
for(size_t i=0; i<numel(); ++i){
double v = double(floatTensor->CPUmem[i]);
memcpy(((double*)(CPUmem))+i,&v,sizeof(double));
}
delete floatTensor;
}else if (myTypeid==typeID(typeid(float)) && fpTypeid==typeID(typeid(double))){
fseek(fp, -(sizeof(uint8_t)+sizeof(uint32_t)), SEEK_CUR);
Tensor<double>* doubleTensor = new Tensor<double>(fp);
this->dim = doubleTensor->dim ;
this->name = doubleTensor->name;
Malloc(batch_size);
for(size_t i=0; i<numel(); ++i){
float v = float(doubleTensor->CPUmem[i]);
memcpy(((float*)(CPUmem))+i,&v,sizeof(float));
}
delete doubleTensor;
}else if (myTypeid==typeID(typeid(half)) && fpTypeid==typeID(typeid(double))){
fseek(fp, -(sizeof(uint8_t)+sizeof(uint32_t)), SEEK_CUR);
Tensor<double>* doubleTensor = new Tensor<double>(fp);
this->dim = doubleTensor->dim ;
this->name = doubleTensor->name;
Malloc(batch_size);
for(size_t i=0; i<numel(); ++i){
half v = cpu_float2half(float(doubleTensor->CPUmem[i]));
memcpy(((half*)(CPUmem))+i,&v,sizeof(half));
}
delete doubleTensor;
}else if (myTypeid==typeID(typeid(float)) && fpTypeid==typeID(typeid(half))){
fseek(fp, -(sizeof(uint8_t)+sizeof(uint32_t)), SEEK_CUR);
Tensor<half>* halfTensor = new Tensor<half>(fp);
this->dim = halfTensor->dim ;
this->name = halfTensor->name;
Malloc(batch_size);
for(size_t i=0; i<numel(); ++i){
double v = double(cpu_half2float(halfTensor->CPUmem[i]));
memcpy(((double*)(CPUmem))+i,&v,sizeof(double));
}
delete halfTensor;
}else{
std::cerr<<"Tensor conversion is not supported: from Type "<<fpTypeid<<" to Type "<<myTypeid<<std::endl;
FatalError(__LINE__);
}
}else{
int lenName;
read_cnt = fread((void*)(&lenName), sizeof(int), 1, fp);
if (read_cnt!=1) return NULL;
name.resize(lenName);
if (lenName>0){
read_cnt = fread((void*)(name.data()), sizeof(char), lenName, fp);
if (read_cnt!=lenName) return NULL;
}
int nbDims;
read_cnt = fread((void*)(&nbDims), sizeof(int), 1, fp);
if (read_cnt!=1) return NULL;
dim.resize(nbDims);
if (nbDims>0){
read_cnt = fread((void*)(&dim[0]), sizeof(int), nbDims, fp);
if (read_cnt!=nbDims) return NULL;
}
size_t n = numel();
Malloc(batch_size);
read_cnt = fread((void*)(CPUmem), sizeof(T), n, fp);
if (read_cnt!=n){
delete [] CPUmem;
CPUmem = NULL;
return NULL;
}
}
return CPUmem;
};
void Malloc(int batch_size){
size_t n = numel();
std::cout<<" "; memorySizePrint(n*sizeof(T)); std::cout<<std::endl;
if (batch_size==1 || dim[0]%batch_size ==0){
CPUmem = new T [n];
}else{
int dim0 = (dim[0]/batch_size + 1) * batch_size;
size_t oversize = n/dim[0] * dim0;
CPUmem = new T [oversize];
memset((void*)(CPUmem+n),0, (oversize-n)*sizeof(T));
}
};
T* read(std::string filename,int batch_size=1){
FILE* fp = fopen(filename.c_str(),"rb");
while (fp==NULL) {
std::cerr<<"Tensor:read: fail to open file "<<filename<<". Please provide it first. Will retry after 5 seconds."<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
fp = fopen(filename.c_str(),"rb");
}
read(fp,batch_size);
fclose(fp);
return CPUmem;
};
//write without header
void writeHeader(FILE* fp, std::vector<int> dim2write){
uint8_t myTypeid = typeID(typeid(T));
fwrite((void*)(&myTypeid), sizeof(uint8_t), 1, fp);
uint32_t typesizeof = uint32_t(sizeof(T));
fwrite((void*)(&typesizeof), sizeof(uint32_t), 1, fp);
int lenName = name.size();
fwrite((void*)(&lenName), sizeof(int), 1, fp);
if (lenName>0) fwrite((void*)(name.data()), sizeof(char), lenName, fp);
int nbDims = dim2write.size();
fwrite((void*)(&nbDims), sizeof(int), 1, fp);
if (nbDims>0) fwrite((void*)(&dim2write[0]), sizeof(int), nbDims, fp);
if (ferror (fp)){
std::cerr << "disk writing failed"<<std::endl;
FatalError();
}
};
void writeData(FILE* fp, size_t max_size = 0){
size_t n = numel();
if (max_size !=0 ) n = min(n,max_size);
if (n>0){
fwrite((void*)(CPUmem), sizeof(T), n, fp);
if (ferror (fp)){
std::cerr << "disk writing failed" << std::endl;
FatalError();
}
}
};
//support continuous write across many NdTensors
//write with header
void write(FILE* fp){
writeHeader(fp,dim);
writeData(fp);
};
void write(std::string filename){
FILE* fp = fopen(filename.c_str(),"wb");
while (fp==NULL) {
std::cerr<<"Tensor::write: fail to open file "<<filename<<". Will retry after 5 seconds."<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
fp = fopen(filename.c_str(),"wb");
}
write(fp);
fclose(fp);
return;
};
Tensor(std::string filename, int batch_size=1): CPUmem(NULL){ read(filename,batch_size); };
Tensor(FILE* fp): CPUmem(NULL){ read(fp); };
Tensor(std::vector<int> dim_): dim(dim_){ CPUmem = new T [numel()]; };
Tensor(std::vector<int> dim_, T* ptr_data): dim(dim_){ CPUmem = ptr_data; };
Tensor(std::vector<int> dim_, T initValue): dim(dim_){
int n = numel();
CPUmem = new T [n];
if (initValue == T(0))
memset(CPUmem, 0, n*sizeof(T));
else
for (int i=0;i<n;++i) CPUmem[i] = initValue;
};
Tensor(std::string name_, std::vector<int> dim_): name(name_),dim(dim_){
CPUmem = new T [numel()];
};
void permute(std::vector<size_t> v){
size_t nbItems = numofitems();
size_t sizeofitem_ = sizeofitem();
size_t nbBytes = sizeofitem_ * sizeof(T);
T* CPUmemNew = new T[numel()];
memcpy(CPUmemNew, CPUmem, nbItems * nbBytes);
for (size_t i=0;i<nbItems;++i){
memcpy(CPUmem+i*sizeofitem_, CPUmemNew+v[i]*sizeofitem_, nbBytes);
}
delete [] CPUmemNew;
};
void printRange(){
int n = numel();
if (n==0){
std::cout<<"Emtpy tensor"<<std::endl;
return;
}
T maxValue = CPUmem[0];
T minValue = CPUmem[0];
for (int i=0;i<n;++i){
if (maxValue<CPUmem[i]) maxValue=CPUmem[i];
if (CPUmem[i]<minValue) minValue=CPUmem[i];
}
std::cout<< "Value Range ["<<minValue<<", "<<maxValue<<"]"<<std::endl;
};
void print(std::vector<int> display_dim){
std::cout<<" name:"<<name<<" dim"; veciPrint(dim); std::cout<<std::endl;
switch (display_dim.size()){
case 1:
for (int i=0;i<min((size_t)(display_dim[0]),numel());++i)
std::cout<<CPUmem[i]<<" ";
std::cout<<std::endl;
break;
case 2:
for (int i=0;i<display_dim[0];++i){
for (int j=0;j<display_dim[1];++j){
std::cout<<(CPUmem[i*dim[display_dim.size()-1]+j])<<" ";
}
std::cout<<std::endl;
}
break;
case 3:
for (int i=0;i<display_dim[0];++i){
for (int j=0;j<display_dim[1];++j){
for (int k=0;k<display_dim[2];++k){
std::cout<<CPUmem[i*dim[dim.size()-2]*dim[dim.size()-1]+j*dim[dim.size()-1]+k]<<" ";
}
std::cout<<std::endl;
}
std::cout<<std::endl;
}
break;
}
};
};
template <class T>
std::vector<Tensor<T>*> readTensors(std::string filename, size_t max_count = SIZE_MAX){
FILE* fp = fopen(filename.c_str(),"rb");
while (fp==NULL) {
std::cerr<<"readTensors: fail to open file "<<filename<<". Please provide it first. Will retry after 5 seconds."<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
fp = fopen(filename.c_str(),"rb");
}
std::vector<Tensor<T>*> tensors;
size_t count = 0;
while (feof(fp)==0) {
tensors.push_back(new Tensor<T>(fp));
count++;
if (count>=max_count) break;
int c = getc(fp);
ungetc(c, fp);
}
fclose(fp);
return tensors;
}
template <class T>
void writeTensors(std::string filename, std::vector<Tensor<T>*> tensors){
FILE* fp = fopen(filename.c_str(),"wb");
while (fp==NULL) {
std::cerr<<"writeTensors: fail to open file "<<filename<<". Disk full? Will retry after 5 seconds."<<std::endl;
std::this_thread::sleep_for(std::chrono::seconds(5));
fp = fopen(filename.c_str(),"wb");
}
for(int i=0;i<tensors.size();++i){
tensors[i]->write(fp);
}
fclose(fp);
}
//////////////////////////////////////////////////////////////////////////////////////////////////
// Response and Layer
//////////////////////////////////////////////////////////////////////////////////////////////////
class Response{
public:
std::string name;
cudnnTensorDescriptor_t desc;
cublasHandle_t cublasHandle;
std::vector<cudnnTensorDescriptor_t> desc_group;
std::vector<int> number_group;
bool isProxy;
StorageT* dataGPU;
StorageT* diffGPU;
bool need_diff;
std::vector<int> dim;
std::vector<int> stride;
std::vector<ComputeT> receptive_field;
std::vector<ComputeT> receptive_gap;
std::vector<ComputeT> receptive_offset;
size_t sizeofitem(){ return marvin::sizeofitem(dim); };
size_t numBytes(){ return sizeofStorageT*(marvin::numel(dim)); };
Response(std::string name_, bool need_diff_=false): name(name_), dataGPU(NULL), diffGPU(NULL), need_diff(need_diff_), isProxy(false){
checkCUDNN(__LINE__,cudnnCreateTensorDescriptor(&desc));
};
size_t Malloc(std::vector<int> dim_, StorageT* dataGPUexisting=NULL, StorageT* diffGPUexisting=NULL){
size_t memoryBytes = 0;
if (dataGPU==NULL){ // two layers (one for training, one for testing) may output to the same response and Malloc twice, ignore the second time
dim = dim_;
stride.resize(dim.size());
stride[dim.size()-1] = 1;
for (int d=dim.size()-2;d>=0;--d){
stride[d] = stride[d+1] * dim[d+1];
}
checkCUDNN(__LINE__,cudnnSetTensorNdDescriptor(desc,
CUDNNStorageT,
dim.size(),
&dim[0],
&stride[0]) );
std::cout<<" ";
std::cout<< (need_diff? "* " : " ");
std::cout<<name; veciPrint(dim);
if (!receptive_field.empty()) { std::cout<<" RF"; vecfPrint(receptive_field); }
if (!receptive_gap.empty()) { std::cout<<" GP"; vecfPrint(receptive_gap); }
if (!receptive_offset.empty()) { std::cout<<" OF"; vecfPrint(receptive_offset); }
std::cout<<std::endl;
if (dataGPUexisting==NULL){
checkCUDA(__LINE__, cudaMalloc(&dataGPU, numel(dim) * sizeofStorageT) );
memoryBytes += numel(dim) * sizeofStorageT;
}else{
dataGPU = dataGPUexisting;
isProxy = true;
}
if (need_diff){
if (diffGPUexisting==NULL){
checkCUDA(__LINE__, cudaMalloc(&diffGPU, numel(dim) * sizeofStorageT) );
memoryBytes += numel(dim) * sizeofStorageT;
}else{
diffGPU = diffGPUexisting;
isProxy = true;
}
}
}else{
if (!same_dim(dim, dim_)){
std::cerr<<std::endl<<"Response["<< name <<"] Malloc dimension mis-matched: ";
veciPrint(dim);
std::cerr<<" vs ";
veciPrint(dim_);
std::cerr<<std::endl;
if (numel(dim)!=numel(dim_)) FatalError(__LINE__);
}
}
return memoryBytes;
};
cudnnTensorDescriptor_t getDesc(int group=1){ // must be called after malloc
if (group==1){
return desc;
}else{
for(int i=0;i<number_group.size();++i){
if (number_group[i]==group){
return desc_group[i];
}
}
}
number_group.push_back(group);
cudnnTensorDescriptor_t desc_new;
checkCUDNN(__LINE__,cudnnCreateTensorDescriptor(&desc_new));
std::vector<int> dim_new = dim;
dim_new[1] = dim[1]/group;
checkCUDNN(__LINE__,cudnnSetTensorNdDescriptor(desc_new,
CUDNNStorageT,
dim_new.size(),
&dim_new[0],
&stride[0]) );
desc_group.push_back(desc_new);
return desc_new;
}
~Response(){
checkCUDNN(__LINE__,cudnnDestroyTensorDescriptor(desc));
for (int i=0; i<desc_group.size();++i){
checkCUDNN(__LINE__,cudnnDestroyTensorDescriptor(desc_group[i]));
}
if (dataGPU!=NULL && !isProxy) checkCUDA(__LINE__, cudaFree(dataGPU));
if (diffGPU!=NULL && !isProxy) checkCUDA(__LINE__, cudaFree(diffGPU));
};
void clearDiff(){
if (diffGPU!=NULL && !isProxy){
checkCUDA(__LINE__, cudaMemset(diffGPU, 0, sizeofStorageT * numel(dim)));
}
};
void print(std::vector<int> display_dim, bool printData=true){
if (!printData && diffGPU==NULL) return;
Tensor<StorageT>* feature = new Tensor<StorageT>(dim);
feature->readGPU((printData? dataGPU: diffGPU));
feature->print(display_dim);
delete feature;
};
int checkNaN(){
return marvin::checkNaN(dataGPU, numel(dim));
};
int checkNaNdiff(){
return marvin::checkNaN(diffGPU, numel(dim));
};
ComputeT ameanData(){
if (dataGPU!=NULL){
ComputeT result;
size_t n = numel(dim);
//std::cout<<"n="<<n<<std::endl;
//std::cout<<"cublasHandle="<<cublasHandle<<std::endl;
//std::cout<<"dataGPU="<<dataGPU<<std::endl;
checkCUBLAS(__LINE__, GPUasum(cublasHandle, n, dataGPU, 1, &result));
result /= ComputeT(n);
return result;
}else{
return -1;
}
};
ComputeT ameanDiff(){
if (diffGPU!=NULL){
ComputeT result;
size_t n = numel(dim);
checkCUBLAS(__LINE__, GPUasum(cublasHandle, n, diffGPU, 1, &result));
result /= ComputeT(n);
return result;
}else{
return -1;
}
};
};
class Layer {
public:
StorageT *weight_dataGPU;
StorageT *weight_diffGPU;
StorageT *weight_histGPU;
StorageT *bias_dataGPU;
StorageT *bias_diffGPU;
StorageT *bias_histGPU;
std::vector<Response *> in;
std::vector<Response *> out;
std::mt19937 rng;
cudnnHandle_t cudnnHandle;
cublasHandle_t cublasHandle;
// parameters:
int GPU;
std::string name;
Phase phase;
bool train_me; // user specify whether they want to tune this layer
ComputeT weight_lr_mult;
Filler weight_filler;
ComputeT weight_filler_param;
std::vector<int> weight_dim;
size_t weight_numel;
ComputeT weight_decay_mult;
ComputeT bias_lr_mult;
Filler bias_filler;
ComputeT bias_filler_param;
std::vector<int> bias_dim;
size_t bias_numel;
ComputeT bias_decay_mult;
std::vector<Layer*> sub_layers;
Layer() : phase(TrainingTesting), train_me(false), weight_dataGPU(NULL),
weight_diffGPU(NULL), weight_histGPU(NULL), bias_dataGPU(NULL),
bias_diffGPU(NULL), bias_histGPU(NULL), weight_numel(0),
bias_numel(0), weight_decay_mult(ComputeT(1)),
bias_decay_mult(ComputeT(1)) {
checkCUDNN(__LINE__, cudnnCreate(&cudnnHandle));
checkCUBLAS(__LINE__, cublasCreate(&cublasHandle));
std::random_device rd;
rng.seed(rd());
};
Layer(std::string name_) : name(name_), phase(TrainingTesting),
train_me(false), weight_dataGPU(NULL),
weight_diffGPU(NULL), weight_histGPU(NULL),
bias_dataGPU(NULL), bias_diffGPU(NULL),
bias_histGPU(NULL), weight_numel(0),
bias_numel(0), weight_decay_mult(ComputeT(1)),
bias_decay_mult(ComputeT(1)) {
checkCUDNN(__LINE__, cudnnCreate(&cudnnHandle));
checkCUBLAS(__LINE__, cublasCreate(&cublasHandle));
std::random_device rd;
rng.seed(rd());
};
virtual ~Layer() {
if (weight_dataGPU != NULL)
checkCUDA(__LINE__, cudaFree(weight_dataGPU));
if (bias_dataGPU != NULL) checkCUDA(__LINE__, cudaFree(bias_dataGPU));
};
ComputeT ameanWeightData() {
if (weight_dataGPU == NULL) return -1;
ComputeT result;
size_t n = numel(weight_dim);
checkCUBLAS(__LINE__,
GPUasum(cublasHandle, n, weight_dataGPU, 1, &result));
result /= ComputeT(n);
return result;
};
ComputeT ameanWeightDiff() {
if (weight_diffGPU == NULL) return -1;
ComputeT result;
size_t n = numel(weight_dim);
checkCUBLAS(__LINE__,
GPUasum(cublasHandle, n, weight_diffGPU, 1, &result));
result /= ComputeT(n);
return result;
};
int checkNaNWeight(){
return marvin::checkNaN(weight_dataGPU, numel(weight_dim));
};
int checkNaNWeightDiff(){
return marvin::checkNaN(weight_diffGPU, numel(weight_dim));
};
ComputeT ameanBiasData() {
if (bias_dataGPU == NULL) return -1;
ComputeT result;
size_t n = numel(bias_dim);
checkCUBLAS(__LINE__,
GPUasum(cublasHandle, n, bias_dataGPU, 1, &result));
result /= ComputeT(n);
return result;
};
ComputeT ameanBiasDiff() {
if (bias_diffGPU == NULL) return -1;
ComputeT result;
size_t n = numel(bias_dim);
checkCUBLAS(__LINE__,
GPUasum(cublasHandle, n, bias_diffGPU, 1, &result));
result /= ComputeT(n);
return result;
};
int checkNaNBias(){
return marvin::checkNaN(bias_dataGPU, numel(bias_dim));
};
int checkNaNBiasDiff(){
return marvin::checkNaN(bias_diffGPU, numel(bias_dim));
};
void addIn(Response *r) { in.push_back(r); };
void addOut(Response *r) { out.push_back(r); };
virtual size_t Malloc(Phase phase_) { // by default, do nothing
std::cout << (train_me ? "* " : " ");
std::cout << name << std::endl;
return 0;
};
virtual void forward(Phase phase_) { }; // by default, do nothing
virtual void backward(Phase phase_) { }; // by default, do nothing
virtual void display() { };
virtual bool isDataLayer() { return false; };
void fillGPU(StorageT *GPUmem, std::vector<int> dim, Filler filler,
ComputeT param = 0) {
int n = numel(dim);
StorageT *CPUbuf = new StorageT[n];
switch (filler) {
case Xavier: {
int fan_in = ComputeT(n / dim[0]);
ComputeT scale = sqrt(ComputeT(3) / fan_in);
//default_random_engine generator;
std::uniform_real_distribution<ComputeT> distribution(-scale,
scale);
for (StorageT *p = CPUbuf; p != CPUbuf + n; ++p) {
*p = CPUCompute2StorageT(distribution(rng));
}
}
break;
case Gaussian: {
std::normal_distribution<ComputeT> distribution(0, param);
for (StorageT *p = CPUbuf; p != CPUbuf + n; ++p) {
*p = CPUCompute2StorageT(distribution(rng));
}
}
break;
case Constant: {
StorageT paramStorageT = CPUCompute2StorageT(param);
for (StorageT *p = CPUbuf; p != CPUbuf + n; ++p) {
*p = paramStorageT;
}
}
break;
}
checkCUDA(__LINE__, cudaMemcpy(GPUmem, CPUbuf, n * sizeofStorageT,
cudaMemcpyHostToDevice));
delete[] CPUbuf;
}
void randInit() {
if (weight_dataGPU != NULL) fillGPU(weight_dataGPU, weight_dim, weight_filler, weight_filler_param);
if (bias_dataGPU != NULL) fillGPU(bias_dataGPU, bias_dim, bias_filler, bias_filler_param);
for(int l=0;l<sub_layers.size();++l) sub_layers[l]->randInit();
};
void clearDiff() {
if (weight_diffGPU != NULL)
checkCUDA(__LINE__, cudaMemset(weight_diffGPU, 0,
sizeofStorageT * weight_numel));
if (bias_diffGPU != NULL)
checkCUDA(__LINE__, cudaMemset(bias_diffGPU, 0,
sizeofStorageT * bias_numel));
for(int l=0;l<sub_layers.size();++l) sub_layers[l]->clearDiff();
};
void clearHist() {
if (weight_diffGPU != NULL)
checkCUDA(__LINE__, cudaMemset(weight_histGPU, 0,
sizeofStorageT * weight_numel));
if (bias_diffGPU != NULL)
checkCUDA(__LINE__, cudaMemset(bias_histGPU, 0,
sizeofStorageT * bias_numel));
for(int l=0;l<sub_layers.size();++l) sub_layers[l]->clearHist();
};
void setWeights(std::vector<Tensor<StorageT> *> weights) {
for (int i = 0; i < weights.size(); ++i) {
if (weight_dataGPU != NULL &&
weights[i]->name == name + ".weight") {
if (numel(weight_dim) == numel(weights[i]->dim)) {
if (!same_dim(weight_dim, weights[i]->dim)) {
std::cout << "[Warning] " << name <<
".weight is loaded with mismatched dimensions ";
std::cout << "need";
veciPrint(weight_dim);
std::cout << " vs. file";
veciPrint(weights[i]->dim);
std::cout << std::endl;
}
std::cout << " " << name << ".weight";
veciPrint(weights[i]->dim);
std::cout << " is set." << std::endl;
weights[i]->writeGPU(weight_dataGPU);
} else {
std::cout << "[Warning] " << name <<
".weight is found but not loaded because the numels are mismatched: ";
std::cout << "need";
veciPrint(weight_dim);
std::cout << " vs. file";
veciPrint(weights[i]->dim);
std::cout << std::endl;
}
}
if (bias_dataGPU != NULL && weights[i]->name == name + ".bias") {
if (numel(bias_dim) == numel(weights[i]->dim)) {
if (!same_dim(bias_dim, weights[i]->dim)) {
std::cout << "[Warning] " << name <<
".bias is loaded with mismatched dimensions ";
std::cout << "need";
veciPrint(bias_dim);
std::cout << " vs. file";
veciPrint(weights[i]->dim);
std::cout << std::endl;
}
std::cout << " " << name << ".bias";
veciPrint(weights[i]->dim);
std::cout << " is set." << std::endl;
weights[i]->writeGPU(bias_dataGPU);
} else {
std::cout << "[Warning] " << name <<
".bias is found but not loaded because the numels are mismatched: ";
std::cout << "need";
veciPrint(bias_dim);
std::cout << " vs. file";
veciPrint(weights[i]->dim);
std::cout << std::endl;
}
}
}
for(int l=0;l<sub_layers.size();++l) sub_layers[l]->setWeights(weights);
};
void saveWeights(FILE *fp) {
if (weight_dataGPU != NULL) {
Tensor <StorageT> *t = new Tensor<StorageT>(
name + ".weight", weight_dim);
t->readGPU(weight_dataGPU);
t->write(fp);
delete t;
}
if (bias_dataGPU != NULL) {
Tensor <StorageT> *t = new Tensor<StorageT>(
name + ".bias", bias_dim);
t->readGPU(bias_dataGPU);
t->write(fp);
delete t;
}
for(int l=0;l<sub_layers.size();++l) sub_layers[l]->saveWeights(fp);
};
void printWeights(std::vector<int> display_weight,
std::vector<int> display_bias) {
if (weight_dataGPU != NULL) {
Tensor <StorageT> *t = new Tensor<StorageT>(
name + ".weight", weight_dim);
t->readGPU(weight_dataGPU);
t->print(display_weight);
delete t;
}
if (bias_dataGPU != NULL) {
Tensor <StorageT> *t = new Tensor<StorageT>(
name + ".bias", bias_dim);
t->readGPU(bias_dataGPU);