I said in this question that I had some problem loading ptx modules in JCuda and after #talonmies's idea, I implemented a JCuda version of his solution to load multiple ptx files and load them as a single module. Here is the related part of the code:
import static jcuda.driver.JCudaDriver.cuLinkAddFile;
import static jcuda.driver.JCudaDriver.cuLinkComplete;
import static jcuda.driver.JCudaDriver.cuLinkCreate;
import static jcuda.driver.JCudaDriver.cuLinkDestroy;
import static jcuda.driver.JCudaDriver.cuModuleGetFunction;
import static jcuda.driver.JCudaDriver.cuModuleLoadData;
import jcuda.driver.CUjitInputType;
import jcuda.driver.JITOptions;
import jcuda.driver.CUlinkState;
import jcuda.driver.CUfunction;
public class JCudaTestJIT{
private CUmodule module;
private CUfunction functionKernel;
public void prepareModule(){
String ptxFileName4 = "file4.ptx";
String ptxFileName3 = "file3.ptx";
String ptxFileName2 = "file2.ptx";
String ptxFileName1 = "file1.ptx";
CUlinkState linkState = new CUlinkState();
JITOptions jitOptions = new JITOptions();
cuLinkCreate(jitOptions, linkState);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName4, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName3, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName2, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName1, jitOptions);
long sizeOut = 32768;
byte[] image = new byte[32768];
Pointer cubinOut = Pointer.to(image);
cuLinkComplete(linkState, cubinOut, (new long[]{sizeOut}));
module = new CUmodule();
// Load the module from the image buffer
cuModuleLoadData(module, cubinOut.getByteBuffer(0, 32768).array());
cuLinkDestroy(linkState);
functionKernel = new CUfunction();
cuModuleGetFunction(functionKernel, module, "kernel");
}
// Other methods
}
But I got the error of CUDA_ERROR_INVALID_IMAGE at calling cuModuleLoadData method. While debugging it, I saw that after calling cuLinkComplete method and pass the image array as the output, the array is still unchanged and clear. Am I passing the output parameter correctly? Is this how one can pass a variable by reference in JCuda?
I had never written a single line of Java code until 30 minutes ago, let alone used JCUDA before, but an almost literal line-by-line translation of the native C++ code I gave you here seems to work perfectly:
import static jcuda.driver.JCudaDriver.*;
import java.io.*;
import jcuda.*;
import jcuda.driver.*;
public class JCudaRuntimeTest
{
public static void main(String args[])
{
JCudaDriver.setExceptionsEnabled(true);
cuInit(0);
CUdevice device = new CUdevice();
cuDeviceGet(device, 0);
CUcontext context = new CUcontext();
cuCtxCreate(context, 0, device);
CUlinkState linkState = new CUlinkState();
JITOptions jitOptions = new JITOptions();
cuLinkCreate(jitOptions, linkState);
String ptxFileName2 = "test_function.ptx";
String ptxFileName1 = "test_kernel.ptx";
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName2, jitOptions);
cuLinkAddFile(linkState, CUjitInputType.CU_JIT_INPUT_PTX, ptxFileName1, jitOptions);
long sz[] = new long[1];
Pointer image = new Pointer();
cuLinkComplete(linkState, image, sz);
System.out.println("Pointer: " + image);
System.out.println("CUBIN size: " + sz[0]);
CUmodule module = new CUmodule();
cuModuleLoadDataEx(module, image, 0, new int[0], Pointer.to(new int[0]));
cuLinkDestroy(linkState);
CUfunction functionKernel = new CUfunction();
String kernelname = "_Z6kernelPfS_S_S_";
cuModuleGetFunction(functionKernel, module, kernelname);
System.out.println("Function: " + functionKernel);
}
}
which works like this:
> nvcc -ptx -arch=sm_21 test_function.cu
test_function.cu
> nvcc -ptx -arch=sm_21 test_kernel.cu
test_kernel.cu
> javac -cp ".;jcuda-0.7.0a.jar" JCudaRuntimeTest.java
> java -cp ".;jcuda-0.7.0a.jar" JCudaRuntimeTest
Pointer: Pointer[nativePointer=0xa5a13a8,byteOffset=0]
CUBIN size: 5924
Function: CUfunction[nativePointer=0xa588160]
The key here seems to be to use cuModuleLoadDataEx, noting that the return values from cuLinkComplete are a system pointer to the linked CUBIN and the size of the image returned as a long[]. As per the C++ code, the pointer is just passed directly to the module data load.
As a final comment, it would have been much simpler and easier if you had posted a proper repro case that could be been directly hacked on, rather than making me learn the rudiments of JCUDA and Java before I could create a useful repro case and get it to work. The documentation for JCUDA is basic, but complete, and against the working C++ example already provided, it only took a couple of minutes of reading to see how to do this.
Related
This question already has answers here:
Java interpreter? [closed]
(10 answers)
Closed 9 years ago.
For debug reasons, I want to be able to run code that is typed in through the console. For example:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
}
PLEASE DON'T ACTUALLY USE THIS
I was under the assumption you wanted to evaluate a string as Java code, not some scripting engine like Javascript, so
I created this on a whim after reading this, using the compiler API mark mentioned. It's probably very bad practice but it (somewhat) works like you wanted it to. I doubt it'll be much use in debugging since it runs the code in the context of a new class. Sample usage is included at the bottom.
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
public class main {
public static void runCode(String s) throws Exception{
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
File jf = new File("test.java"); //create file in current working directory
PrintWriter pw = new PrintWriter(jf);
pw.println("public class test {public static void main(){"+s+"}}");
pw.close();
Iterable fO = sjfm.getJavaFileObjects(jf);
if(!jc.getTask(null,sjfm,null,null,null,fO).call()) { //compile the code
throw new Exception("compilation failed");
}
URL[] urls = new URL[]{new File("").toURI().toURL()}; //use current working directory
URLClassLoader ucl = new URLClassLoader(urls);
Object o= ucl.loadClass("test").newInstance();
o.getClass().getMethod("main").invoke(o);
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
try {
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
//command line
> System.out.println("hello");
hello
> System.out.println(3+2+3+4+5+2);
19
> for(int i = 0; i < 10; i++) {System.out.println(i);}
0
1
2
3
4
5
6
7
8
9
With the SimpleJavaFileObject you could actually avoid using a file, as shown here, but the syntax seems a bit cumbersome so I just opted for a file in the current working directory.
EDIT: Convert String to Code offers a similar approach but it's not fully fleshed out
If the code is in JavaScript then you can run it with JavaScript engine:
Object res = new ScriptEngineManager().getEngineByName("js").eval(str);
JavaScript engine is part of Java SE since 1.6. See this guide http://download.java.net/jdk8/docs/technotes/guides/scripting/programmer_guide/index.html for details
You can use the Java scripting API which is located in the Package javax.script. There you can include several scripting languages like bsh for example.
You can find a programmer's guide on the web page of Oracle.
Rhino, which is some kind of JavaScript is already included with the Oracle JVM.
For this you may want to look into Java Compiler API. I haven't studied much as to how this works, but it allows you to load a java file, compile and load the class in an already running system. Maybe it can be repurposed into accepting input from console.
For a general compiler you could use Janino which will allow you to compile and run Java code. The expression evaluator may help with your example.
If you are just looking to evaluate expressions while debugging then Eclispe has the Display view which allows you to execute expressions. See this question.
I have a problem that I was going to work on arrays in WebAssembly and I wanted to use Java and C ++, and trying to do this, I ran into the following problems and I would like to ask for help:
Java: I'm using JWebAssembly
And we have a class that works on tables
import de.inetsoftware.jwebassembly.api.annotation.Export;
public class Add {
#Export
public static int[] add( int a[], int b ) {
for(int i = 0;i<b-1;i++){
a[i] += b ;
}
return a;
}
}
we convert it to wasm
import de.inetsoftware.jwebassembly.JWebAssembly;
import java.io.File;
import java.net.URL;
public class Wasm {
public static void main(String[] args) {
File wasmFile = new File("testTable.wasm");
JWebAssembly wasm = new JWebAssembly();
Class clazz = Add.class;
URL url = clazz.getResource(
'/' +
clazz.getName().replace('.', '/') +
".class");
wasm.addFile(url);
String txt = wasm.compileToText();
System.out.println(txt);
wasm.compileToBinary(wasmFile);
}
}
and such an error comes out
Exception in thread "main" de.inetsoftware.jwebassembly.WasmException: Unimplemented Java byte code operation: 42 at Add.java:11
https://en.wikipedia.org/wiki/List_of_Java_bytecode_instructions
And I don't understand why because in this guy's presentation https://www.youtube.com/watch?v=93z9SaLQVVw (40 min+) you can see that it works and compiles
Now C++
I use emscripten, I wanted to do a bubble sort but for the sake of simplicity an example showing the problem
#include <emscripten.h>
using namespace std;
EMSCRIPTEN_KEEPALIVE
int* mainFunction(int table[], int length)
{
int* outTable = new int[length];
for(int i = 0;i<length; i++){
outTable[i] = table[i];
}
return table;
}
By running it with this command test.cpp -s WASM=1 -o test.html
after compiling it, files appear to me from which I extract the appropriate data and in javascript I set and import everything
let wasmExports = null;
let asmLibraryArg = {
abort: () => {},
emscripten_resize_heap: () => {},
};
let info = {
env: asmLibraryArg,
wasi_snapshot_preview1: asmLibraryArg,
};
async function loadWasm() {
let response = await fetch("test.wasm");
let bytes = await response.arrayBuffer();
let wasmObj = await WebAssembly.instantiate(bytes, info);
wasmExports = wasmObj.instance.exports;
}
loadWasm();
and later in the code I use
console.log(wasmExports);
console.log(wasmExports._Z12mainFunctionPii(table, table.length));
results
and when I throw in some array of integers it only throws me the number 0 and I have no idea how to get out of it. Or maybe someone knows another language in which it is possible to compile for wasm and then run it on the website?
I'm using R programing to analysis FFT . now I want to make Java web application/ java servlet and calling R to use Rcaller/Rcode for it . I have some reference about Calling Rcode in java application. http://code.google.com/p/rcaller/wiki/Examples
I have CSV File
for example A.csv
time Amplitude
1 0.00000 -0.021
2 0.00001 -0.024
3 0.00003 -0.013
4 0.00004 -0.023
5 0.00005 0.019
6 0.00007 -0.002
7 0.00008 -0.013
then I want to upload this file and use R Code for analysis FFT and Plot it.
Help is much appreciated! Thanks in advance, Maria
You start creating an instance of RCaller and set the current location of install Rscript.exe file. You can start with
RCaller caller = new RCaller();
Globals.detect_current_rscript();
caller.setRscriptExecutable(Globals.Rscript_current);
RCode code = new RCode();
or you can give the exact location
RCaller caller = new RCaller();
caller.setRscriptExecutable("c:\\path\\to\\Rscript.exe");
RCode code = new RCode();
Suppose your data is saved in a file mydata.csv.
code.addRCode("dat <- read.cvs(\"mydata.csv\", header=T, sep=\",\"");
then we are plotting the Amplitude
File file = code.startPlot();
code.addRCode("plot.ts(dat$Amplitude)");
code.endPlot();
and sending our code to R:
caller.setRCode(code);
caller.runOnly();
And now, the file variable holds the image data. It can be shown on screen using the code
code.showPlot(file);
For further reading, follow the blog entries on stdioe blog
When I execute this code is running but didn't show anything !!!!!!!
package test2;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import javax.swing.ImageIcon;
import rcaller.RCaller;
import rcaller.RCode;
import rcaller.exception.RCallerExecutionException;
import rcaller.exception.RCallerParseException;
public class Test2 {
public static void main(String[] args) {
Test2 test2=new Test2();
}
private int span;
#SuppressWarnings("empty-statement")
public void test2()throws IOException{
try {
RCaller caller = new RCaller();
caller.setRscriptExecutable("C:\\Program Files\\R\\R-3.0.3\\bin\\Rscript.exe");
RCode code = new RCode();
code.addRCode("dat<-read.csv(\"NetBeansProjects\"test2\"A.csv\",header=T,sep=\",\"");
File file=code.startPlot();
code.addRCode("plot.ts(dat$Amplitude)");
code.endPlot();
caller.setRCode(code);
caller.runOnly();
ImageIcon i=code.getPlot(file);
code.showPlot(file);
} catch (RCallerExecutionException | RCallerParseException e) {
System.out.println(e.toString());
}
}
}
I'm trying to implement the tTorrent client into my program, I've looked at this link for an example (https://github.com/mpetazzoni/ttorrent/issues/16) and placed that code into the Download class of my program. Here is the code:
import statements:
import main.java.com.turn.ttorrent.client.Client;
import main.java.com.turn.ttorrent.client.SharedTorrent;
import main.java.com.turn.ttorrent.common.Torrent;
import main.java.com.turn.ttorrent.tracker.TrackedTorrent;
import main.java.com.turn.ttorrent.tracker.Tracker;
// Create tracker instance
Tracker tracker = new Tracker(InetAddress.getLocalHost());
// Load torrent file
File torrentFile = new File("/path/to/torrentFile.torrent");
// Create torrent instance
TrackedTorrent torrent = new TrackedTorrent(Torrent.load(torrentFile, null));
// Announce torrent
tracker.announce(torrent);
// Start the tracker
tracker.start();
torrentFile = new File(path + ".torrent");
File downloadDir = new File("/path/to/torrents_download_dir");//unsure
Client client = new Client(InetAddress.getLocalHost(), SharedTorrent.fromFile(torrentFile, downloadDir));
// Add client.share(); if you wish to share the torrent infinitely
client.run();
I'm getting this error message when I hover over load:
The method load(File, boolean) in the type Torrent is not applicable for the arguments (File, null)
I'm also unsure what I should place in File downloadDir. I'm still a beginner and if someone could point me in the right direction to putting this into my program that would be great. I'm still a beginner.
Torrent.load(torrentFile, null) wants a File object.
e.g
Torrent.load(new File(/foo/path.torrent), null)
Try to write your objects and method in a main Method
public static void main(String[] args) {
// Object 1;
// Object 2;
}
This question already has answers here:
Java interpreter? [closed]
(10 answers)
Closed 9 years ago.
For debug reasons, I want to be able to run code that is typed in through the console. For example:
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
}
PLEASE DON'T ACTUALLY USE THIS
I was under the assumption you wanted to evaluate a string as Java code, not some scripting engine like Javascript, so
I created this on a whim after reading this, using the compiler API mark mentioned. It's probably very bad practice but it (somewhat) works like you wanted it to. I doubt it'll be much use in debugging since it runs the code in the context of a new class. Sample usage is included at the bottom.
import javax.tools.JavaCompiler;
import javax.tools.StandardJavaFileManager;
import javax.tools.ToolProvider;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;
public class main {
public static void runCode(String s) throws Exception{
JavaCompiler jc = ToolProvider.getSystemJavaCompiler();
StandardJavaFileManager sjfm = jc.getStandardFileManager(null, null, null);
File jf = new File("test.java"); //create file in current working directory
PrintWriter pw = new PrintWriter(jf);
pw.println("public class test {public static void main(){"+s+"}}");
pw.close();
Iterable fO = sjfm.getJavaFileObjects(jf);
if(!jc.getTask(null,sjfm,null,null,null,fO).call()) { //compile the code
throw new Exception("compilation failed");
}
URL[] urls = new URL[]{new File("").toURI().toURL()}; //use current working directory
URLClassLoader ucl = new URLClassLoader(urls);
Object o= ucl.loadClass("test").newInstance();
o.getClass().getMethod("main").invoke(o);
}
public static void main(String[] args) {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
while(true){
try {
String str = br.readLine(); //This can return 'a = 5;','b = "Text";' or 'pckg.example.MyClass.run(5);'
if(str == null)
return;
runCode(str); //How would I do this?
} catch(Exception e) {
e.printStackTrace();
}
}
}
}
//command line
> System.out.println("hello");
hello
> System.out.println(3+2+3+4+5+2);
19
> for(int i = 0; i < 10; i++) {System.out.println(i);}
0
1
2
3
4
5
6
7
8
9
With the SimpleJavaFileObject you could actually avoid using a file, as shown here, but the syntax seems a bit cumbersome so I just opted for a file in the current working directory.
EDIT: Convert String to Code offers a similar approach but it's not fully fleshed out
If the code is in JavaScript then you can run it with JavaScript engine:
Object res = new ScriptEngineManager().getEngineByName("js").eval(str);
JavaScript engine is part of Java SE since 1.6. See this guide http://download.java.net/jdk8/docs/technotes/guides/scripting/programmer_guide/index.html for details
You can use the Java scripting API which is located in the Package javax.script. There you can include several scripting languages like bsh for example.
You can find a programmer's guide on the web page of Oracle.
Rhino, which is some kind of JavaScript is already included with the Oracle JVM.
For this you may want to look into Java Compiler API. I haven't studied much as to how this works, but it allows you to load a java file, compile and load the class in an already running system. Maybe it can be repurposed into accepting input from console.
For a general compiler you could use Janino which will allow you to compile and run Java code. The expression evaluator may help with your example.
If you are just looking to evaluate expressions while debugging then Eclispe has the Display view which allows you to execute expressions. See this question.