Posts Tagged ‘JavaAI’
[DevoxxBE2025] Java for AI
Lecturer
Paul Sandoz is a Distinguished Engineer at Oracle, leading efforts in Java platform features for AI and machine learning. With contributions to projects like Valhalla and Babylon, he focuses on performance enhancements and interoperability. Paul has a history in RESTful web services, co-authoring JAX-RS specifications.
Abstract
This article surveys Java platform capabilities supporting AI, encompassing current tools like Foreign Function & Memory API and Vector API, alongside prospective ones from Valhalla and Babylon. It clarifies mechanisms for native interoperation and vectorized computations, placed amid demands for competitive AI libraries. Via examples of array manipulations and kernel generations, the narrative spotlights tactics for efficiency and portability. The exploration gauges situational elements in AI workloads, ramifications for library construction and app performance, and furnishes views on Java’s trajectory in empowering AI solutions.
Current Platform Tools for AI Efficiency
Java’s existing arsenal includes the Foreign Function & Memory API (FFM) for native code access and the Vector API for SIMD operations. FFM enables safe, efficient calls to C libraries, crucial for AI frameworks like TensorFlow.
Examples: Loading libraries, invoking functions via MethodHandles. Vector API vectorizes loops:
VectorSpecies<Float> SPECIES = FloatVector.SPECIES_PREFERRED;
FloatVector a = FloatVector.fromArray(SPECIES, arrayA, 0);
FloatVector b = FloatVector.fromArray(SPECIES, arrayB, 0);
FloatVector c = a.add(b);
c.intoArray(result, 0);
This accelerates computations on hardware like AVX.
Context: These address Java’s gaps in low-level access, enabling NumPy-like libraries. Implications: Better performance in ML without external dependencies.
Valhalla’s Value Types for Data Optimization
Project Valhalla introduces value types—immutable, identity-free—for efficient data structures. Arrays of values flatten, reducing overheads.
Code: Defining value classes, using in arrays for contiguous memory. Implications: Dense layouts boost cache efficiency, vital for AI tensors.
Babylon’s Code Reflection for Kernel Generation
Project Babylon enables runtime code generation via reflection, targeting GPUs/CPUs. It translates Java methods to IR for compilation.
Examples: Reflecting methods, generating OpenCL kernels for Game of Life. Implications: Portable acceleration without manual native code.
Synergies and AI Library Building
Combined, these enable competitive libraries: FFM for interop, Vector for math, Valhalla for structures, Babylon for kernels.
Analysis: Supports dialects for GPU code, like OpenAI’s Triton. Ramifications: Empowers Java AI ecosystems rivaling Python’s.
Future: Stabilizing features in Java 24+.
In summary, Java’s enhancements position it strongly for AI, providing building blocks for high-performance solutions.
Links:
- Lecture video: https://www.youtube.com/watch?v=CjPPJFcUCl8
- Paul Sandoz on LinkedIn: https://www.linkedin.com/in/paul-sandoz-697a711/
- Paul Sandoz on Twitter/X: https://twitter.com/paulsandoz
- Oracle website: https://www.oracle.com/
[VoxxedDaysTicino2026] Training My Rival in Java: A Deep Q-Learning AI to Play Azul
Lecturer
Victor Uria Valle is a Full Stack Software Engineer at CERN, specializing in modernizing and developing enterprise applications to support laboratory operations. He holds a degree from Universidad de Oviedo and pursues personal projects in artificial intelligence, including game-playing agents. Relevant links include his LinkedIn profile (https://ch.linkedin.com/in/vuria).
Abstract
This article scrutinizes Victor Uria Valle’s endeavor to construct a Deep Q-Network (DQN) in Java for mastering the board game Azul. It delineates the game’s mechanics, Q-learning fundamentals, neural network integration, and training methodologies. Through analytical exploration, it assesses environmental modeling, state representation, reward engineering, and performance implications, underscoring Java’s viability for reinforcement learning without specialized frameworks.
Contextualizing Azul and Reinforcement Learning
Victor commences by elucidating Azul’s rules, a tile-placement game involving a shared board with factories displaying colored tiles and a central area. Players select tiles of one color from a factory or center, placing them on their personal board’s pattern lines—a right-angled triangular grid. Completed lines transfer tiles to a wall, scoring points based on adjacency, while excess tiles incur penalties on the floor line. Code structures reflect this: enums define tile colors, factories hold tile lists, player boards track pattern lines, walls, floor lines, scores, and penalties. Legal moves constrain placements—tiles must match line colors, avoid filled wall positions, and handle overflows. This setup frames reinforcement learning (RL), where agents learn via trial-and-error interactions. Victor employs Q-learning, estimating action values (Q-values) in states to maximize cumulative rewards. Traditionally tabular, Q-learning suits discrete spaces but falters in Azul’s vast state space (exponential due to board configurations). Contextually, AI in games traces to chess and Go, but Victor opts for Java sans PyTorch or TensorFlow, demonstrating accessibility. Implications: Democratizes RL for Java developers, though lacks optimized libraries.
Deep Q-Network Architecture and Innovations
To address state complexity, Victor integrates deep neural networks, approximating Q-values via function approximation. The DQN processes states as inputs, outputting Q-values per action. State encoding vectorizes boards: binary representations for tile presence in factories, centers, pattern lines, walls, and floors. Actions encode selections (factory/center, color, line/floor). The neural network, a multi-layer perceptron, uses rectified linear units (ReLU) for non-linearity, trained via backpropagation with mean squared error loss. Innovations include experience replay—storing state-action-reward-next-state tuples in a buffer, sampling mini-batches to break correlations—and a target network, periodically updated to stabilize learning. Epsilon-greedy policy balances exploration (random actions) and exploitation (highest Q-value actions), decaying epsilon over episodes. Code snippets illustrate:
public double[] forward(double[] input) {
// Input to hidden layer
double[] hidden = new double[hiddenSize];
for (int i = 0; i < hiddenSize; i++) {
double sum = 0;
for (int j = 0; j < inputSize; j++) {
sum += input[j] * weightsInputHidden[j][i];
}
hidden[i] = Math.max(0, sum + biasHidden[i]); // ReLU
}
// Hidden to output
double[] output = new double[outputSize];
for (int i = 0; i < outputSize; i++) {
double sum = 0;
for (int j = 0; j < hiddenSize; j++) {
sum += hidden[j] * weightsHiddenOutput[j][i];
}
output[i] = sum + biasOutput[i];
}
return output;
}
This forward pass computes Q-values, enabling action selection. Implications: Custom implementation fosters understanding, though less efficient than frameworks; suitable for educational prototypes.
Training Methodology and Reward Design
Training employs a DQN agent and trainer. The agent selects actions via epsilon-greedy, executes them, computes rewards, and stores experiences. Replay samples batches, updating the network; target updates occur periodically. Rewards equal score deltas minus amplified floor penalties, incentivizing efficient placements. Trainer parameters include episodes, steps per save, epsilon decay (initial 1.0 to minimum 0.05). Live demo showcases training: loading pre-trained models, executing moves in a terminal UI, observing random explorations (5% minimum) for continual learning. Methodologically, Victor iterates games, refining via replays. Contexts: Balances short-term gains (line completions) with long-term strategies (wall synergies). Implications: Reward shaping critical—penalizing floors curbs suboptimal habits; serialization enables resuming, vital for lengthy trainings.
Analytical Implications for Java-Based AI
Victor’s approach validates Java for RL sans external dependencies, leveraging enums, lists for game logic, arrays for neural computations. Innovations: Pure Java DQN demystifies black-box frameworks, aiding pedagogy. Challenges: Manual matrix operations less performant; state space demands efficient encoding. Future: Enhance UI, explore advanced variants (Double DQN). Broader ramifications: Empowers non-ML specialists in game AI; implications for scalable, interpretable agents in constrained environments.