我对cuda有一个奇怪的问题,
在下面的片段中,
#include <stdio.h>
#define OUTPUT_SIZE 26
typedef $PRECISION REAL;
extern "C"
{
__global__ void test_coeff ( REAL* results )
{
int id = blockDim.x * blockIdx.x + threadIdx.x;
int out_index = OUTPUT_SIZE * id;
for (int i=0; i<OUTPUT_SIZE; i++)
{
results[out_index+i]=id;
printf("q");
}
}
}
Run Code Online (Sandbox Code Playgroud)
当我编译并运行代码(通过pycuda)时,它按预期工作.当我删除printf时,结果很奇怪 - 大部分数组都是正确填充的,但有些似乎是完全随机的.
这是完整的python代码:
import numpy as np
import string
#pycuda stuff
import pycuda.driver as drv
import pycuda.autoinit
from pycuda.compiler import SourceModule
class MC:
cudacodetemplate = """
#include <stdio.h>
#define OUTPUT_SIZE 26
typedef $PRECISION REAL;
extern "C"
{
__global__ void test_coeff ( REAL* results )
{
int id = blockDim.x * blockIdx.x + threadIdx.x;
int out_index = OUTPUT_SIZE * id;
for (int i=0; i<OUTPUT_SIZE; i++)
{
results[out_index+i]=id;
//printf("q");
}
}
}
"""
def __init__(self, size, prec = np.float32):
#800 meg should be enough . . .
drv.limit.MALLOC_HEAP_SIZE = 1024*1024*800
self.size = size
self.prec = prec
template = string.Template(MC.cudacodetemplate)
self.cudacode = template.substitute( PRECISION = 'float' if prec==np.float32 else 'double')
#self.module = pycuda.compiler.SourceModule(self.cudacode, no_extern_c=True, options=['--ptxas-options=-v'])
self.module = SourceModule(self.cudacode, no_extern_c=True)
def test(self, out_size):
#try to precalc the co-efficients for just the elements of the vector that changes
test = np.zeros( ( 128, out_size*(2**self.size) ), dtype=self.prec )
test2 = np.zeros( ( 128, out_size*(2**self.size) ), dtype=self.prec )
test_coeff = self.module.get_function ('test_coeff')
test_coeff( drv.Out(test), block=(2**self.size,1,1), grid=( 128, 1 ) )
test_coeff( drv.Out(test2), block=(2**self.size,1,1), grid=( 128, 1 ) )
error = (test-test2)
return error
if __name__ == '__main__':
p1 = MC ( 5, np.float64 )
err = p1.test(26)
print err.max()
print err.min()
Run Code Online (Sandbox Code Playgroud)
基本上,使用内核中的printf,错误是0 - 没有它它会打印一些随机错误(在我的机器上大约2452(最大)和-2583(最小))
我不知道为什么.
我用geforce 570在pycuda 2012.2(windows 7 64bit)上运行cuda 4.2.
谢谢.
这很可能是由于编译器优化造成的。您正在将内存块 OUTPUT_SIZE 的长度设置为 id 的循环常量值。根据我的经验,编译器会将其优化为memcpy或whathaveyou,除非循环中发生其他事情——即你的打印语句。此外,如果您不使用该内存块,编译器可能会优化整个循环。尝试调整您的优化级别,看看是否有不同的结果。