when I try to run an example of Matrix multiplication by pycuda.
kernel_code_template = """
__global__ void MatrixMulKernel(float *a,float *b,float *c){
int tx = threadIdx.x;
int ty = threadIdx.y;
float Pvalue = 0;
for(int i=0; i<%(N)s; ++i){
float Aelement = a[ty * %(N)s + i];
float Belement = b[i * %(M)s + tx];
Pvalue += Aelement * Belement;
}
c[ty * %[M]s + tx] = Pvalue;
}
"""
M, N = 2, 3
kernel_code = kernel_code_template % {'M': M, 'N': N}
it reported error like:
kernel_code = kernel_code_template % {'M': M, 'N': N}
TypeError: not enough arguments for format string
I've tried to check if there is anything wrong with "%" mark but got nothing yet.
To directly answer the question, you need to change %[M]s
to %(M)s
in your code, like so:
kernel_code_template = """
__global__ void MatrixMulKernel(float *a,float *b,float *c){
int tx = threadIdx.x;
int ty = threadIdx.y;
float Pvalue = 0;
for(int i=0; i<%(N)s; ++i){
float Aelement = a[ty * %(N)s + i];
float Belement = b[i * %(M)s + tx];
Pvalue += Aelement * Belement;
}
c[ty * %(M)s + tx] = Pvalue;
}
"""
Then it will work as expected. However, I'd strongly recommend you start using f-strings as you indicated you were working with Python 3.7:
kernel_code_template = f"""
__global__ void MatrixMulKernel(float *a,float *b,float *c){{
int tx = threadIdx.x;
int ty = threadIdx.y;
float Pvalue = 0;
for(int i=0; i<{N}; ++i){{
float Aelement = a[ty * {N} + i];
float Belement = b[i * {M} + tx];
Pvalue += Aelement * Belement;
}}
c[ty * {M} + tx] = Pvalue;
}}
"""
I get there are trade-offs, though, namely those {{
and }}
escapes. There is also the .format()
method as @Brandt pointed out. Choose what feels best to you.