Since then, TornadoVM itself has gone (almost) pure Java: the JNI code was replaced with Project Panama, and Graal made way for its own compiler, also written in Java. So, how does that work? Let’s find out the hard way: we will only need a modern OpenJDK (I’m using OpenJDK 26), Project Panama and a magnetized needle, and a steady hand.
Oh, and an NVIDIA GPU. We’ll be talking to libcuda.so.1, the user-space half of the NVIDIA driver, so you’ll need Linux (or WSL2). Sorry, Mac folks (TornadoVM has a Metal backend, though).
Project Panama
Project Panama is the codename for a set of APIs and Java runtime capabilities to interact with platform code without writing JNI. With the Panama APIs you can allocate native memory, get handles to unmanaged memory regions and transfer control to native code in pure Java.
For instance, here’s a how you print hello world by directly invoking printf(3) from the C standard library:
import java.lang.foreign.*;
import java.lang.invoke.MethodHandle;
import static java.lang.foreign.ValueLayout.*;
void main() throws Throwable {
Linker linker = Linker.nativeLinker();
MemorySegment addr = linker.defaultLookup().find("printf").orElseThrow();
// int printf(const char *format, ...)
MethodHandle printf = linker.downcallHandle(
addr,
FunctionDescriptor.of(JAVA_INT, ADDRESS),
Linker.Option.firstVariadicArg(1));
try (Arena arena = Arena.ofConfined()) {
MemorySegment fmt = arena.allocateFrom("Hello, World!\n");
int _ = (int) printf.invokeExact(fmt);
}
}
What we are doing here is looking up printf on the platform’s libc:
- we find its address,
- we get a
MethodHandlewrapping a native function pointer, by describing the function signature. - we create an arena allocator
- allocate a string on the arena and get a pointer
- we invoke printf over the string pointer.
Save the code to main.java and then call it as java main.java.
$ java main.java WARNING: A restricted method in java.lang.foreign.Linker has been called WARNING: java.lang.foreign.Linker::downcallHandle has been called by main in an unnamed module (...) WARNING: Use --enable-native-access=ALL-UNNAMED to avoid a warning for callers in this module WARNING: Restricted methods will be blocked in a future release unless native access is enabled Hello, World!
You can follow the instruction to hide the scary warning.
$ java --enable-native-access=ALL-UNNAMED main.java Hello, World!
Pretty neat, huh?
CUDA BE any more impressed?
Now, let’s talk GPU kernels. We are not going to be fancy this time, but we are going to go quite low-level. In fact, I recently learned that you can pass a string of PTX code to libcuda and it will load it and run it on device. But maybe I’m getting ahead of myself.
What is PTX? And, since we’re here. What is CUDA?
CUDA is NVIDIA’s platform for running general-purpose code on their GPUs. You usually write kernels in a C++ dialect and compile them with nvcc. But under the hood, nvcc emits PTX, a sort of bytecode for a virtual GPU. The driver then compiles PTX to the actual instruction set of your card. And the driver is just a C library: the CUDA Driver API. You can see where this is going.
Let’s start with the simplest hello world we could write, only a few lines of code. We’ll write it first using CUDA C++, then we’ll see how that gets translated to PTX, and then I’ll show you how to call that from Java. How does that sound?
The “hello world” of GPU programming is not printing a string, it’s adding two vectors. Here it is in CUDA C++:
extern "C" __global__ void add(const float *a, const float *b, float *c, int n) {
int i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n) {
c[i] = a[i] + b[i];
}
}
__global__ marks add as a kernel: a function that runs on the device, but that we launch from the host. When we launch it, we don’t call it once: we spawn thousands of threads, grouped in blocks, and each thread runs the same function. Each thread computes its own index i from its position in the block (threadIdx.x) and the block’s position in the grid (blockIdx.x), and it takes care of exactly one element. The if is there because the number of threads we spawn is usually rounded up to a multiple of the block size, so a few threads at the end may have nothing to do.
extern "C" is there so that the compiler doesn’t mangle the name. It will come in handy later, when we’ll look up the kernel by name.
NOTE: The following part will assume you have access to NVIDIA hardware and a Linux box.
Let’s save it as add.cu, and ask nvcc (we are using version 13.0.88 here) to stop at PTX:
$ nvcc -ptx add.cu -o add.ptx
If you don’t have nvcc ready, you can also do the same using Compiler Explorer.
.version 9.0 // PTX ISA version
.target sm_75 // minimum GPU architecture
.address_size 64 // 64-bit pointers
// .globl add
// extern "C" __global__ void add(...): an unmangled kernel entry point
.visible .entry add(
.param .u64 add_param_0, // const float *a
.param .u64 add_param_1, // const float *b
.param .u64 add_param_2, // float *c
.param .u32 add_param_3 // int n
)
{
// virtual registers: PTX has infinitely many,
// the driver maps them to real ones
.reg .pred %p<2>; // booleans
.reg .f32 %f<4>; // floats
.reg .b32 %r<6>; // 32-bit ints
.reg .b64 %rd<11>; // 64-bit ints (pointers)
// load the kernel arguments
ld.param.u64 %rd1, [add_param_0]; // a
ld.param.u64 %rd2, [add_param_1]; // b
ld.param.u64 %rd3, [add_param_2]; // c
ld.param.u32 %r2, [add_param_3]; // n
// int i = blockIdx.x * blockDim.x + threadIdx.x;
mov.u32 %r3, %ctaid.x; // blockIdx.x
mov.u32 %r4, %ntid.x; // blockDim.x
mov.u32 %r5, %tid.x; // threadIdx.x
mad.lo.s32 %r1, %r3, %r4, %r5; // i (multiply-add)
// if (i < n): skip to the end when i >= n
setp.ge.s32 %p1, %r1, %r2;
@%p1 bra $DONE;
// &a[i]: offset = i * sizeof(float)
cvta.to.global.u64 %rd4, %rd1; // a, as a global memory address
mul.wide.s32 %rd5, %r1, 4;
add.s64 %rd6, %rd4, %rd5;
// &b[i]
cvta.to.global.u64 %rd7, %rd2;
add.s64 %rd8, %rd7, %rd5;
// a[i] + b[i]
ld.global.f32 %f1, [%rd8]; // b[i]
ld.global.f32 %f2, [%rd6]; // a[i]
add.f32 %f3, %f2, %f1;
// c[i] = ...
cvta.to.global.u64 %rd9, %rd3;
add.s64 %rd10, %rd9, %rd5;
st.global.f32 [%rd10], %f3;
$DONE:
ret;
}
You can also emit the lower-level, device-specific native code, i.e. SASS: while PTX is guaranteed to be forward-compatible SASS is not fully documented and may change from architecture to architecture. If you want to look at SASS (where we assume the GPU architecture code is sm_75):
$ nvcc -cubin -arch=sm_75 add.cu -o add.cubin
$ cuobjdump -sass add.cubin
code for sm_75
.target sm_75
Function : add
.headerflags @"EF_CUDA_SM75 EF_CUDA_VIRTUAL_SM(EF_CUDA_SM75)"
/*0000*/ MOV R1, c[0x0][0x28] ; /* 0x00000a0000017a02 */
/* 0x000fe40000000f00 */
/*0010*/ S2R R6, SR_CTAID.X ; /* 0x0000000000067919 */
/* 0x000e280000002500 */
/*0020*/ S2R R3, SR_TID.X ; /* 0x0000000000037919 */
/* 0x000e240000002100 */
/*0030*/ IMAD R6, R6, c[0x0][0x0], R3 ; /* 0x0000000006067a24 */
/* 0x001fca00078e0203 */
/*0040*/ ISETP.GE.AND P0, PT, R6, c[0x0][0x178], PT ; /* 0x00005e0006007a0c */
/* 0x000fd80003f06270 */
/*0050*/ @P0 EXIT ; /* 0x000000000000094d */
/* 0x000fea0003800000 */
/*0060*/ MOV R7, 0x4 ; /* 0x0000000400077802 */
/* 0x000fca0000000f00 */
/*0070*/ IMAD.WIDE R4, R6, R7, c[0x0][0x168] ; /* 0x00005a0006047625 */
/* 0x000fc800078e0207 */
/*0080*/ IMAD.WIDE R2, R6, R7, c[0x0][0x160] ; /* 0x0000580006027625 */
/* 0x000fc800078e0207 */
/*0090*/ LDG.E.SYS R4, [R4] ; /* 0x0000000004047381 */
/* 0x000ea800001ee900 */
/*00a0*/ LDG.E.SYS R3, [R2] ; /* 0x0000000002037381 */
/* 0x000ea200001ee900 */
/*00b0*/ IMAD.WIDE R6, R6, R7, c[0x0][0x170] ; /* 0x00005c0006067625 */
/* 0x000fc800078e0207 */
/*00c0*/ FADD R9, R4, R3 ; /* 0x0000000304097221 */
/* 0x004fd00000000000 */
/*00d0*/ STG.E.SYS [R6], R9 ; /* 0x0000000906007386 */
/* 0x000fe2000010e900 */
/*00e0*/ EXIT ; /* 0x000000000000794d */
/* 0x000fea0003800000 */
/*00f0*/ BRA 0xf0; /* 0xfffffff000007947 */
/* 0x000fc0000383ffff */
..........
Before we jump to Java, let’s make sure our kernel actually runs. This is how you would normally launch it from C++, using the CUDA Runtime API. Save this to main.cu:
#include "add.cu"
#include <iomanip>
#include <iostream>
#include <vector>
constexpr int N = 1 << 20;
constexpr int BLOCK = 256;
constexpr int PREVIEW = 8;
int main() {
// Inputs: a = [0, 1, 2, ...], b = [1, 1, 1, ...]
std::vector<float> a(N), b(N), c(N);
for (int i = 0; i < N; i++) {
a[i] = i;
b[i] = 1.0f;
}
// Allocate device memory and copy the inputs over.
size_t bytes = N * sizeof(float);
float *da, *db, *dc;
cudaMalloc(&da, bytes);
cudaMalloc(&db, bytes);
cudaMalloc(&dc, bytes);
cudaMemcpy(da, a.data(), bytes, cudaMemcpyHostToDevice);
cudaMemcpy(db, b.data(), bytes, cudaMemcpyHostToDevice);
// Launch enough blocks to cover N elements (rounded up).
int grid = (N + BLOCK - 1) / BLOCK;
add<<<grid, BLOCK>>>(da, db, dc, N);
// Synchronous copy back: waits for the kernel.
cudaMemcpy(c.data(), dc, bytes, cudaMemcpyDeviceToHost);
// Expect [1.0, 2.0, 3.0, ...]
std::cout << std::fixed << std::setprecision(1) << "[";
for (int i = 0; i < PREVIEW; i++) {
std::cout << (i ? ", " : "") << c[i];
}
std::cout << "]" << std::endl;
cudaFree(da);
cudaFree(db);
cudaFree(dc);
}
The funny <<<grid, BLOCK>>> syntax is how CUDA C++ launches a kernel: it tells the GPU how many blocks to spawn, and how many threads per block. nvcc compiles both the host and the device code, embeds the kernel in the executable, and turns that line into a few calls to the CUDA runtime, which, in turn, talks to the driver for us.
$ nvcc main.cu -o main
$ ./main
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0]
If you are interested you can see how this expands to libcuda API calls using:
$ nvcc --keep main.cu -o main
NOW WHAT?
We have learned how a CUDA Kernel gets compiled to its low-level representation and how to invoke it on the device.
If you want to learn more, stick around for the second part, where we will see how to load a kernel from pure Java, and how to write a small embedded language to generate and execute a kernel on-the-fly!
Author: Edoardo Vacchi
After my PhD at University of Milan on programming language design and implementation, I worked for three years at UniCredit Bank’s R&D department.
Later, I have joined Red Hat where I worked on the Drools rule engine, the jBPM workflow engine and the Kogito cloud-native business automation platform.
I joined Tetrate to work on the wazero WebAssembly runtime for Go.
At Dylibso I contributed to wazero and Chicory Wasm runtime for the JVM, and other runtimes!
I am currently back at Red Hat AI.
I sometimes write on my own personal blog.
steinhauer.software