Class: BOAST::CKernel
- Includes:
- Rake::DSL
- Defined in:
- lib/BOAST/CKernel.rb
Instance Attribute Summary collapse
-
#binary ⇒ Object
Returns the value of attribute binary.
-
#code ⇒ Object
Returns the value of attribute code.
-
#kernels ⇒ Object
Returns the value of attribute kernels.
-
#lang ⇒ Object
Returns the value of attribute lang.
-
#procedure ⇒ Object
Returns the value of attribute procedure.
Instance Method Summary collapse
- #build(options = {}) ⇒ Object
- #build_opencl(options) ⇒ Object
- #fill_code(source_file) ⇒ Object
- #fill_module(module_file, module_name) ⇒ Object
-
#initialize(options = {}) ⇒ CKernel
constructor
A new instance of CKernel.
- #method_missing(meth, *args, &block) ⇒ Object
- #print ⇒ Object
- #setup_compiler(options = {}) ⇒ Object
- #to_s ⇒ Object
- #to_str ⇒ Object
Constructor Details
#initialize(options = {}) ⇒ CKernel
Returns a new instance of CKernel.
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/BOAST/CKernel.rb', line 27 def initialize(={}) if [:code] then @code = [:code] elsif BOAST::get_chain_code @code = BOAST::get_output @code.seek(0,SEEK_END) else @code = StringIO::new end BOAST::set_output( @code ) if [:kernels] then @kernels = [:kernels] else @kernels = [] end if [:lang] then @lang = [:lang] else @lang = BOAST::get_lang end end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(meth, *args, &block) ⇒ Object
537 538 539 540 541 542 543 544 |
# File 'lib/BOAST/CKernel.rb', line 537 def method_missing(meth, *args, &block) if meth.to_s == "run" then self.build self.run(*args,&block) else super end end |
Instance Attribute Details
#binary ⇒ Object
Returns the value of attribute binary.
24 25 26 |
# File 'lib/BOAST/CKernel.rb', line 24 def binary @binary end |
#code ⇒ Object
Returns the value of attribute code.
21 22 23 |
# File 'lib/BOAST/CKernel.rb', line 21 def code @code end |
#kernels ⇒ Object
Returns the value of attribute kernels.
25 26 27 |
# File 'lib/BOAST/CKernel.rb', line 25 def kernels @kernels end |
#lang ⇒ Object
Returns the value of attribute lang.
23 24 25 |
# File 'lib/BOAST/CKernel.rb', line 23 def lang @lang end |
#procedure ⇒ Object
Returns the value of attribute procedure.
22 23 24 |
# File 'lib/BOAST/CKernel.rb', line 22 def procedure @procedure end |
Instance Method Details
#build(options = {}) ⇒ Object
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 |
# File 'lib/BOAST/CKernel.rb', line 246 def build( = {}) return build_opencl() if @lang == BOAST::CL ldflags = self.setup_compiler() extension = ".c" if @lang == BOAST::C extension = ".cu" if @lang == BOAST::CUDA extension = ".f90" if @lang == BOAST::FORTRAN #temporary c_compiler = [:CC] c_compiler = "cc" if not c_compiler linker = [:LD] linker = c_compiler if not linker #end temporary source_file = Tempfile::new([@procedure.name,extension]) path = source_file.path target = path.chomp(File::extname(path))+".o" fill_code(source_file) source_file.close previous_lang = BOAST::get_lang previous_output = BOAST::get_output BOAST::set_lang(BOAST::C) module_file_name = File::split(path.chomp(File::extname(path)))[0] + "/Mod_" + File::split(path.chomp(File::extname(path)))[1].gsub("-","_") + ".c" module_name = File::split(module_file_name.chomp(File::extname(module_file_name)))[1] module_file = File::open(module_file_name,"w+") BOAST::set_output(module_file) fill_module(module_file, module_name) module_file.rewind # puts module_file.read module_file.close BOAST::set_lang(previous_lang) BOAST::set_output(previous_output) module_target = module_file_name.chomp(File::extname(module_file_name))+".o" module_final = module_file_name.chomp(File::extname(module_file_name))+".so" kernel_files = [] @kernels.each { |kernel| kernel_file = Tempfile::new([kernel.procedure.name,".o"]) kernel.binary.rewind kernel_file.write( kernel.binary.read ) kernel_file.close kernel_files.push(kernel_file) } file module_final => [module_target, target] do #puts "#{linker} -shared -o #{module_final} #{module_target} #{target} #{kernel_files.join(" ")} -Wl,-Bsymbolic-functions -Wl,-z,relro -rdynamic -Wl,-export-dynamic #{ldflags}" sh "#{linker} -shared -o #{module_final} #{module_target} #{target} #{(kernel_files.collect {|f| f.path}).join(" ")} -Wl,-Bsymbolic-functions -Wl,-z,relro -rdynamic -Wl,-export-dynamic #{ldflags}" end Rake::Task[module_final].invoke require(module_final) eval "self.extend(#{module_name})" f = File::open(target,"rb") @binary = StringIO::new @binary.write( f.read ) f.close File.unlink(target) File.unlink(module_target) File.unlink(module_file_name) File.unlink(module_final) kernel_files.each { |f| f.unlink } return self end |
#build_opencl(options) ⇒ Object
149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 |
# File 'lib/BOAST/CKernel.rb', line 149 def build_opencl() require 'opencl_ruby_ffi' platform = nil platforms = OpenCL::get_platforms if [:platform_vendor] then platforms.each{ |p| platform = p if p.vendor.match([:platform_vendor]) } else platform = platforms.first end device = nil type = [:device_type] ? [:device_type] : OpenCL::Device::Type::ALL devices = platform.devices(type) if [:device_name] then devices.each{ |d| device = d if d.name.match([:device_name]) } else device = devices.first end @context = OpenCL::create_context([device]) program = @context.create_program_with_source([@code.string]) opts = [:CLFLAGS] program.build(:options => [:CLFLAGS]) if [:verbose] then program.build_log.each {|dev,log| STDERR.puts "#{device.name}: #{log}" } end @queue = @context.create_command_queue(device, :properties => OpenCL::CommandQueue::PROFILING_ENABLE) @kernel = program.create_kernel(@procedure.name) run_method = <<EOF def self.run(*args) raise "Wrong number of arguments \#{args.length} for #{@procedure.parameters.length}" if args.length > #{@procedure.parameters.length+1} or args.length < #{@procedure.parameters.length} params = [] opts = {} opts = args.pop if args.length == #{@procedure.parameters.length+1} @procedure.parameters.each_index { |i| if @procedure.parameters[i].dimension then if @procedure.parameters[i].direction == :in and @procedure.parameters[i].direction == :out then params[i] = @context.create_buffer( args[i].size * args[i].element_size ) @queue.enqueue_write_buffer( params[i], args[i], :blocking => true ) elsif @procedure.parameters[i].direction == :in then params[i] = @context.create_buffer( args[i].size * args[i].element_size, :flags => OpenCL::Mem::Flags::READ_ONLY ) @queue.enqueue_write_buffer( params[i], args[i], :blocking => true ) elsif @procedure.parameters[i].direction == :out then params[i] = @context.create_buffer( args[i].size * args[i].element_size, :flags => OpenCL::Mem::Flags::WRITE_ONLY ) else params[i] = @context.create_buffer( args[i].size * args[i].element_size ) end else if @procedure.parameters[i].type.is_a?(Real) then params[i] = OpenCL::Half::new(args[i]) if @procedure.parameters[i].type.size == 2 params[i] = OpenCL::Float::new(args[i]) if @procedure.parameters[i].type.size == 4 params[i] = OpenCL::Double::new(args[i]) if @procedure.parameters[i].type.size == 8 elsif @procedure.parameters[i].type.is_a?(Int) then if @procedure.parameters[i].type.signed params[i] = OpenCL::Char::new(args[i]) if @procedure.parameters[i].type.size == 1 params[i] = OpenCL::Short::new(args[i]) if @procedure.parameters[i].type.size == 2 params[i] = OpenCL::Int::new(args[i]) if @procedure.parameters[i].type.size == 4 params[i] = OpenCL::Long::new(args[i]) if @procedure.parameters[i].type.size == 8 else params[i] = OpenCL::UChar::new(args[i]) if @procedure.parameters[i].type.size == 1 params[i] = OpenCL::UShort::new(args[i]) if @procedure.parameters[i].type.size == 2 params[i] = OpenCL::UInt::new(args[i]) if @procedure.parameters[i].type.size == 4 params[i] = OpenCL::ULong::new(args[i]) if @procedure.parameters[i].type.size == 8 end else params[i] = args[i] end end } params.each_index{ |i| @kernel.set_arg(i, params[i]) } event = @queue.enqueue_NDrange_kernel(@kernel, opts[:global_work_size], :local_work_size => opts[:local_work_size]) @procedure.parameters.each_index { |i| if @procedure.parameters[i].dimension then if @procedure.parameters[i].direction == :in and @procedure.parameters[i].direction == :out then @queue.enqueue_read_buffer( params[i], args[i], :blocking => true ) elsif @procedure.parameters[i].direction == :out then @queue.enqueue_read_buffer( params[i], args[i], :blocking => true ) end end } result = {} result[:start] = event.profiling_command_start result[:end] = event.profiling_command_end result[:duration] = (result[:end] - result[:start])/1000000000.0 return result end EOF eval run_method return self end |
#fill_code(source_file) ⇒ Object
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/BOAST/CKernel.rb', line 308 def fill_code(source_file) @code.rewind source_file.puts "#include <inttypes.h>" if @lang == BOAST::C or @lang == BOAST::CUDA source_file.puts "#include <cuda.h>" if @lang == BOAST::CUDA source_file.write @code.read if @lang == BOAST::CUDA then source_file.write <<EOF extern "C" { #{@procedure.header(BOAST::CUDA,false)}{ dim3 dimBlock(block_size[0], block_size[1], block_size[2]); dim3 dimGrid(block_number[0], block_number[1], block_number[2]); cudaEvent_t __start, __stop; float __time; cudaEventCreate(&__start); cudaEventCreate(&__stop); cudaEventRecord(__start, 0); #{@procedure.name}<<<dimGrid,dimBlock>>>(#{@procedure.parameters.join(", ")}); cudaEventRecord(__stop, 0); cudaEventSynchronize(__stop); cudaEventElapsedTime(&__time, __start, __stop); return (unsigned long long int)((double)__time*(double)1e6); } } EOF end @code.rewind end |
#fill_module(module_file, module_name) ⇒ Object
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 |
# File 'lib/BOAST/CKernel.rb', line 336 def fill_module(module_file, module_name) module_file.write <<EOF #include "ruby.h" #include <inttypes.h> #include <time.h> #ifdef HAVE_NARRAY_H #include "narray.h" #endif EOF if( @lang == BOAST::CUDA ) then module_file.print "#include <cuda_runtime.h>\n" end module_file.print @procedure.header(@lang) module_file.write <<EOF VALUE #{module_name} = Qnil; void Init_#{module_name}(); VALUE method_run(int argc, VALUE *argv, VALUE self); void Init_#{module_name}() { #{module_name} = rb_define_module("#{module_name}"); rb_define_method(#{module_name}, "run", method_run, -1); } VALUE method_run(int argc, VALUE *argv, VALUE self) { EOF if( @lang == BOAST::CUDA ) then module_file.write <<EOF if( argc < #{@procedure.parameters.length} || argc > #{@procedure.parameters.length + 1} ) rb_raise(rb_eArgError, "wrong number of arguments for #{@procedure.name} (%d for #{@procedure.parameters.length})", argc); VALUE rb_opts; VALUE rb_ptr; size_t block_size[3] = {1,1,1}; size_t block_number[3] = {1,1,1}; EOF else module_file.write <<EOF if( argc != #{@procedure.parameters.length} ) rb_raise(rb_eArgError, "wrong number of arguments for #{@procedure.name} (%d for #{@procedure.parameters.length})", argc); VALUE rb_ptr; EOF end argc = @procedure.parameters.length argv = Variable::new("argv",Real,{:dimension => [ Dimension::new(0,argc-1) ] }) rb_ptr = Variable::new("rb_ptr",Int) @procedure.parameters.each { |param| param_copy = param.copy param_copy.constant = nil param_copy.direction = nil param_copy.decl } @procedure.parameters.each_index do |i| param = @procedure.parameters[i] if not param.dimension then case param.type when Int (param === FuncCall::new("NUM2INT", argv[i])).print if param.type.size == 4 (param === FuncCall::new("NUM2LONG", argv[i])).print if param.type.size == 8 when Real (param === FuncCall::new("NUM2DBL", argv[i])).print end else (rb_ptr === argv[i]).print if @lang == BOAST::CUDA then module_file.print <<EOF if ( IsNArray(rb_ptr) ) { struct NARRAY *n_ary; size_t array_size; Data_Get_Struct(rb_ptr, struct NARRAY, n_ary); array_size = n_ary->total * na_sizeof[n_ary->type]; cudaMalloc( (void **) &#{param.name}, array_size); EOF if param.direction == :in then module_file.print <<EOF cudaMemcpy(#{param.name}, (void *) n_ary->ptr, array_size, cudaMemcpyHostToDevice); EOF end module_file.print <<EOF } else rb_raise(rb_eArgError, "wrong type of argument %d", #{i}); EOF else module_file.print <<EOF if (TYPE(rb_ptr) == T_STRING) { #{param.name} = (void *) RSTRING_PTR(rb_ptr); } else if ( IsNArray(rb_ptr) ) { struct NARRAY *n_ary; Data_Get_Struct(rb_ptr, struct NARRAY, n_ary); #{param.name} = (void *) n_ary->ptr; } else rb_raise(rb_eArgError, "wrong type of argument %d", #{i}); EOF end end end if @lang == BOAST::CUDA then module_file.write <<EOF if( argc == #{@procedure.parameters.length + 1} ) { rb_opts = argv[argc -1]; if ( rb_opts != Qnil ) { VALUE rb_array_data = Qnil; int i; if (TYPE(rb_opts) != T_HASH) rb_raise(rb_eArgError, "Cuda options should be passed as a hash"); rb_ptr = rb_hash_aref(rb_opts, ID2SYM(rb_intern("block_size"))); if( rb_ptr != Qnil ) { if (TYPE(rb_ptr) != T_ARRAY) rb_raise(rb_eArgError, "Cuda option block_size should be an array"); for(i=0; i<3; i++) { rb_array_data = rb_ary_entry(rb_ptr, i); if( rb_array_data != Qnil ) block_size[i] = (size_t) NUM2LONG( rb_array_data ); } } rb_ptr = rb_hash_aref(rb_opts, ID2SYM(rb_intern("block_number"))); if( rb_ptr != Qnil ) { if (TYPE(rb_ptr) != T_ARRAY) rb_raise(rb_eArgError, "Cuda option block_number should be an array"); for(i=0; i<3; i++) { rb_array_data = rb_ary_entry(rb_ptr, i); if( rb_array_data != Qnil ) block_number[i] = (size_t) NUM2LONG( rb_array_data ); } } } } EOF end module_file.print " #{@procedure.properties[:return].type.decl} ret;\n" if @procedure.properties[:return] module_file.print " VALUE stats = rb_hash_new();\n" module_file.print " struct timespec start, stop;\n" module_file.print " unsigned long long int duration;\n" module_file.print " clock_gettime(CLOCK_REALTIME, &start);\n" if @lang == BOAST::CUDA then module_file.print " duration = " elsif @procedure.properties[:return] then module_file.print " ret = " end module_file.print " #{@procedure.name}" module_file.print "_" if @lang == BOAST::FORTRAN module_file.print "_wrapper" if @lang == BOAST::CUDA module_file.print "(" if(@lang == BOAST::FORTRAN) then params = [] @procedure.parameters.each { |param| if param.dimension then params.push( param.name ) else params.push( "&"+param.name ) end } module_file.print params.join(", ") else module_file.print @procedure.parameters.join(", ") end if @lang == BOAST::CUDA then module_file.print ", " if @procedure.parameters.length > 0 module_file.print "block_number, block_size" end module_file.print " );\n" module_file.print " clock_gettime(CLOCK_REALTIME, &stop);\n" if @lang == BOAST::CUDA then @procedure.parameters.each_index do |i| param = @procedure.parameters[i] if param.dimension then (rb_ptr === argv[i]).print module_file.print <<EOF if ( IsNArray(rb_ptr) ) { EOF if param.direction == :out then module_file.print <<EOF struct NARRAY *n_ary; size_t array_size; Data_Get_Struct(rb_ptr, struct NARRAY, n_ary); array_size = n_ary->total * na_sizeof[n_ary->type]; cudaMemcpy(#{param.name}, (void *) n_ary->ptr, array_size, cudaMemcpyDeviceToHost); EOF end module_file.print <<EOF cudaFree( (void *) #{param.name}); } else rb_raise(rb_eArgError, "wrong type of argument %d", #{i}); EOF end end end if @lang != BOAST::CUDA then module_file.print " duration = (unsigned long long int)stop.tv_sec * (unsigned long long int)1000000000 + stop.tv_nsec;\n" module_file.print " duration -= (unsigned long long int)start.tv_sec * (unsigned long long int)1000000000 + start.tv_nsec;\n" end module_file.print " rb_hash_aset(stats,ID2SYM(rb_intern(\"duration\")),rb_float_new((double)duration*(double)1e-9));\n" if @procedure.properties[:return] then type_ret = @procedure.properties[:return].type module_file.print " rb_hash_aset(stats,ID2SYM(rb_intern(\"return\")),rb_int_new((long long)ret));\n" if type_ret.kind_of?(Int) and type_ret.signed module_file.print " rb_hash_aset(stats,ID2SYM(rb_intern(\"return\")),rb_int_new((unsigned long long)ret));\n" if type_ret.kind_of?(Int) and not type_ret.signed module_file.print " rb_hash_aset(stats,ID2SYM(rb_intern(\"return\")),rb_float_new((double)ret));\n" if type_ret.kind_of?(Real) end module_file.print " return stats;\n" module_file.print "}" end |
#print ⇒ Object
49 50 51 52 |
# File 'lib/BOAST/CKernel.rb', line 49 def print @code.rewind puts @code.read end |
#setup_compiler(options = {}) ⇒ Object
64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 |
# File 'lib/BOAST/CKernel.rb', line 64 def setup_compiler( = {}) Rake::Task::clear verbose = [:verbose] verbose = BOAST::get_verbose if not verbose Rake::verbose(verbose) Rake::FileUtilsExt.verbose_flag=verbose f_compiler = [:FC] f_compiler = "gfortran" if not f_compiler c_compiler = [:CC] c_compiler = "cc" if not c_compiler cxx_compiler = [:CXX] cxx_compiler = "g++" if not cxx_compiler cuda_compiler = [:NVCC] cuda_compiler = "nvcc"if not cuda_compiler f_flags = [:FCFLAGS] f_flags = "-O2 -Wall" if not f_flags f_flags += " -fPIC" f_flags += " -fno-second-underscore" if f_compiler == 'g95' ld_flags = [:LDFLAGS] ld_flags = "" if not ld_flags cuda_flags = [:NVCCFLAGS] cuda_flags = "-O2" if not cuda_flags cuda_flags += " --compiler-options '-fPIC'" includes = "-I#{RbConfig::CONFIG["archdir"]}" includes += " -I#{RbConfig::CONFIG["rubyhdrdir"]} -I#{RbConfig::CONFIG["rubyhdrdir"]}/#{RbConfig::CONFIG["arch"]}" includes += " -I#{RbConfig::CONFIG["rubyarchhdrdir"]}" if RbConfig::CONFIG["rubyarchhdrdir"] ld_flags += " -L#{RbConfig::CONFIG["libdir"]} #{RbConfig::CONFIG["LIBRUBYARG"]} -lrt" ld_flags += " -lcudart" if @lang == BOAST::CUDA narray_path = nil begin spec = Gem::Specification::find_by_name('narray') narray_path = spec.full_gem_path rescue Gem::LoadError => e rescue NoMethodError => e spec = Gem::available?('narray') if spec then require 'narray' narray_path = Gem.loaded_specs['narray'].full_gem_path end end includes += " -I#{narray_path}" if narray_path cflags = "-O2 -Wall -fPIC #{includes}" cxxflags = String::new(cflags) cflags += " -DHAVE_NARRAY_H" if narray_path cflags += [:CFLAGS] if [:CFLAGS] fcflags = f_flags cudaflags = cuda_flags runner = lambda { |t, call_string| if verbose then sh call_string else status, stdout, stderr = systemu call_string if not status.success? then puts stderr fail "#{t.source}: compilation failed" end status.success? end } rule '.o' => '.c' do |t| c_call_string = "#{c_compiler} #{cflags} -c -o #{t.name} #{t.source}" runner.call(t, c_call_string) end rule '.o' => '.f90' do |t| f_call_string = "#{f_compiler} #{fcflags} -c -o #{t.name} #{t.source}" runner.call(t, f_call_string) end rule '.o' => '.cpp' do |t| cxx_call_string = "#{cxx_compiler} #{cxxflags} -c -o #{t.name} #{t.source}" runner.call(t, cxx_call_string) end rule '.o' => '.cu' do |t| cuda_call_string = "#{cuda_compiler} #{cudaflags} -c -o #{t.name} #{t.source}" runner.call(t, cuda_call_string) end return ld_flags end |
#to_s ⇒ Object
59 60 61 62 |
# File 'lib/BOAST/CKernel.rb', line 59 def to_s @code.rewind return code.read end |
#to_str ⇒ Object
54 55 56 57 |
# File 'lib/BOAST/CKernel.rb', line 54 def to_str @code.rewind return code.read end |