Monday, December 28, 2009

My First GPU HelloWorld Program

Finally I got my OpenCL based java programs run on my AMD Phenom-II 965 BE with Radeon HD 5750.



package com.nativelibs4java.opencl.demos;

import static com.nativelibs4java.opencl.JavaCL.createBestContext;
import static com.nativelibs4java.util.NIOUtils.directFloats;

import java.io.IOException;
import java.nio.FloatBuffer;
import java.util.Random;

import com.nativelibs4java.opencl.CLBuildException;
import com.nativelibs4java.opencl.CLContext;
import com.nativelibs4java.opencl.CLEvent;
import com.nativelibs4java.opencl.CLFloatBuffer;
import com.nativelibs4java.opencl.CLKernel;
import com.nativelibs4java.opencl.CLMem;
import com.nativelibs4java.opencl.CLProgram;
import com.nativelibs4java.opencl.CLQueue;
import com.nativelibs4java.opencl.demos.SetupUtils;
import com.nativelibs4java.util.NIOUtils;

/* Derived from
* http://bbboblog.blogspot.com/2009/10/gpgpu-mandelbrot-with-opencl-and-java.html
* http://developer.apple.com/mac/library/samplecode/OpenCL_Hello_World_Example/index.html
*/
public class HelloWorld {
private static final String src = "__kernel void square( \n"
+ " __global float* input, \n"
+ " __global float* output, \n"
+ " const unsigned int count) \n"
+ "{ \n"
+ " int i = get_global_id(0); \n"
+ " if(i < count) \n"
+ " output[i] = input[i] * input[i]; \n"
+ "} \n"
+ "\n";
private static final int DATA_SIZE_ = 32;
private static final int DATA_SIZE = DATA_SIZE_ * DATA_SIZE_;

private static int correct; // number of correct results returned

private static FloatBuffer results_ = NIOUtils.directFloats(DATA_SIZE);
private static FloatBuffer data_ = NIOUtils.directFloats(DATA_SIZE);
private static FloatBuffer output = directFloats(DATA_SIZE);

public static void main(String[] args) {
try {
SetupUtils.failWithDownloadProposalsIfOpenCLNotAvailable();

Random ran = new Random();
for (int i = 0; i < DATA_SIZE; i++)
data_.put(i, ran.nextFloat());

long time = buildAndExecuteKernel(data_, results_, DATA_SIZE, src);
correct = 0;
for (int i = 0; i < DATA_SIZE; i++) {
float v = data_.get(i);
float r = output.get(i);
if (r == v * v) {
correct++;
} else {
System.err.println("ERROR: got:" + r + ", Required-Ans:"+ v);
}
}
System.out.println(DATA_SIZE + " entries are computed in "+ ((time / 1000)) + " microseconds, correct entries:" + correct);
} catch (Exception e) {
System.err.println(e);
e.printStackTrace();
}
}

private static long buildAndExecuteKernel(FloatBuffer data, FloatBuffer results, int dataSize, String src)
throws CLBuildException, IOException {
// Create a context and program using the devices discovered.
CLContext context = createBestContext();
CLQueue queue = context.createDefaultQueue();

long startTime = System.nanoTime();

CLProgram program = context.createProgram(src).build();

CLKernel kernel = program.createKernel("square");
CLFloatBuffer in1 = context.createFloatBuffer(CLMem.Usage.Input, data,false);
CLFloatBuffer out1 = context.createFloatBuffer(CLMem.Usage.Output,results, false);
kernel.setArgs(in1, out1, dataSize);

CLEvent kernelCompletion = kernel.enqueueNDRange(queue,
new int[] { DATA_SIZE }, new int[] { 1 });// null);
kernelCompletion.waitFor();
queue.finish();

// Copy the OpenCL-hosted array back to RAM
out1.read(queue, output, true);

long time = System.nanoTime() - startTime;
return time;
}
}

Wednesday, October 14, 2009

Future project of hacking the DIR-300 DLink router

http://www.dd-wrt.com/wiki/index.php/LaFonera_Info_Hardware-Specifications
http://www.dd-wrt.com/wiki/index.php/LaFonera_Hardware_Serial-Cable-Port http://www.dd-wrt.com/wiki/index.php/LaFonera_Hardware_Serial-Cable-Port#Very_simple_console_adapterhttp://www.dd-wrt.com/phpBB2/viewtopic.php?p=230208&highlight=#230208
http://www.shadowandy.net/2007/09/mini-flashing-guide-for-dir-300.htm http://www.gargoyle-router.com/wiki/doku.php?id=install_guide#d-link_dir-300 http://wiki.openwrt.org/oldwiki/openwrtdocs/hardware/airlink/arxxxw http://www.l200ute.com/misc/dir300/dir300%20TTL.jpg http://sodoityourself.com/max232-serial-level-converter/ http://www.dd-wrt.com/wiki/index.php/DIR300 # another pictureof opened dir-300 not opened in http://www.lan23.ru/forum/showthread.php?t=2133 # search here for dir-300 http://www.shadowandy.net/2008/09/dir-300-faq.htm https://www.la-magra.de/wiki/index.php/Useful_Scripts http://www.dd-wrt.com/routerdb/de/download.php?file=2048

Thursday, September 3, 2009

Scala based automatic resource freeing

Using following scala resource, one freely release resources like(InputStrea, OutputStream, Sockets, JDBC Connection, JDBC ResultSet, JDBC Statements, SSLSocket, ServerSocket)

Source
Example Usage

ResourceTest.scala

object ResourceTest {
import java.sql.{Connection,ResultSet}
val OraPool = ConnPool("orahost152:1521",3, Db ) // some how get oracle jdbc connection

def main ( args : Array[String] ): Unit = {
Resource.use (OraPool.getConnection){ conn =>
val ts = find(conn)
for ( v <- ts ) println(v)
}
}
case class Tab(tname: String, tabtype: String)

def find(conn: Connection): List[Tab] = {
Resource.use(conn.createStatement){st =>
Resource.use (st.executeQuery("select tname,tabtype from tab")){ rs =>
import scala.collection.mutable.ListBuffer
var list = List[Tab]()
while(rs.next()){
list ::= Tab(rs.getString("tname"), rs.getString("tabtype"))
}
list
}
}
}
}

Thursday, February 19, 2009

Find javac tasks in build.xml that does compile without line-number information

Majority of ANT build files for java proje use javac-task for compiling the java files. But if the javac task does not have debug=true or debug=yes, then compiled java-class files does not contain line numbers in stacktraces. Following groovy script will check all build files in given file and check all javac taks that does not have debug-flags setting off


def s1=System.currentTimeMillis()
def f = new File('c:/all_build_files.txt')
def counter=0
def error=0
def noDebug=0
def noJavac=0
def debug=Boolean.getBoolean("debug")
f.eachLine{
try{
def file=it
def project = new XmlSlurper().parse(new File(file))
def tasks = project.target.javac
if( tasks.size() > 0){
noJavac++
if(debug) println "javac tasks: ${tasks.size()}"
def found=true
def nfound=0
tasks.each{
def flag=it.@debug
if (!( flag =~ /yes/ || flag =~ /true/ )) {
nfound++
found=false
}
}
if(!found) {
noDebug++
println "${nfound} : ${file}"
}
}
counter++
}catch(Exception e){
error++
if(debug) println "${it} --> ${e}"
}
}
def s2=System.currentTimeMillis()
def sd=s2-s1
println "Parsed files:${counter}, Errors:${error}, noDebug:${noDebug}, Javac:${noJavac} Time in millis:${sd}"




Run the above script(buildFile.groovy) using:


C:\>groovy -Ddebug=1true buildFile.groovy 2>nul


...
1 : C:\src\nb-src\main\xtest\build.xml
2 : C:\src\nb-src\main\xtest\pes\build.xml
2 : C:\src\nb-src\main\xtest\plugins_src\ide\build.xml
1 : C:\src\nb-src\main\xtest\plugins_src\jvm\build.xml
Parsed files:4866, Errors:29, noDebug:722, Javac:839 Time in millis:11859