View Javadoc
1   package net.bmahe.genetics4j.gpu;
2   
3   import java.util.concurrent.ExecutorService;
4   import java.util.concurrent.ForkJoinPool;
5   
6   import net.bmahe.genetics4j.core.EASystem;
7   import net.bmahe.genetics4j.core.EASystemFactory;
8   import net.bmahe.genetics4j.gpu.spec.GPUEAConfiguration;
9   import net.bmahe.genetics4j.gpu.spec.GPUEAExecutionContext;
10  
11  /**
12   * Factory class for creating GPU-accelerated evolutionary algorithm systems using OpenCL.
13   * 
14   * <p>GPUEASystemFactory provides convenient factory methods for creating {@link EASystem} instances that leverage GPU
15   * acceleration through OpenCL for fitness evaluation. This factory extends the capabilities of the core EA framework to
16   * support high-performance computing on graphics processors and other OpenCL-compatible devices.
17   * 
18   * <p>The factory handles the integration between GPU-specific configurations and the core EA framework:
19   * <ul>
20   * <li><strong>GPU Configuration</strong>: Uses {@link GPUEAConfiguration} with OpenCL program specifications</li>
21   * <li><strong>Device Selection</strong>: Leverages {@link GPUEAExecutionContext} for platform and device filtering</li>
22   * <li><strong>GPU Evaluator</strong>: Creates specialized {@link GPUFitnessEvaluator} for OpenCL fitness
23   * computation</li>
24   * <li><strong>Resource Management</strong>: Coordinates executor services with OpenCL resource lifecycle</li>
25   * </ul>
26   * 
27   * <p>GPU acceleration benefits:
28   * <ul>
29   * <li><strong>Massive parallelism</strong>: Evaluate hundreds or thousands of individuals simultaneously</li>
30   * <li><strong>Memory bandwidth</strong>: High-throughput data processing for population-based algorithms</li>
31   * <li><strong>Specialized hardware</strong>: Leverage dedicated compute units optimized for parallel operations</li>
32   * <li><strong>Energy efficiency</strong>: Often better performance-per-watt compared to CPU-only execution</li>
33   * </ul>
34   * 
35   * <p>Common usage patterns:
36   * 
37   * <pre>{@code
38   * // Define OpenCL kernel for fitness evaluation
39   * Program fitnessProgram = Program.ofResource("/kernels/fitness.cl").withBuildOption("-DPROBLEM_SIZE=256");
40   * 
41   * // Configure GPU-specific EA settings
42   * GPUEAConfiguration<Double> gpuConfig = GPUEAConfigurationBuilder.<Double>builder()
43   * 		.chromosomeSpecs(chromosomeSpec)
44   * 		.parentSelectionPolicy(Tournament.of(3))
45   * 		.combinationPolicy(SinglePointCrossover.build())
46   * 		.mutationPolicies(List.of(RandomMutation.of(0.1)))
47   * 		.replacementStrategy(Elitism.builder().offspringRatio(0.8).build())
48   * 		.program(fitnessProgram)
49   * 		.fitness(myGPUFitness)
50   * 		.build();
51   * 
52   * // Configure execution context with device preferences
53   * GPUEAExecutionContext<Double> gpuContext = GPUEAExecutionContextBuilder.<Double>builder()
54   * 		.populationSize(1000)
55   * 		.termination(Generations.of(100))
56   * 		.platformFilter(platform -> platform.profile() == PlatformProfile.FULL_PROFILE)
57   * 		.deviceFilter(device -> device.type() == DeviceType.GPU)
58   * 		.build();
59   * 
60   * // Create GPU-accelerated EA system
61   * EASystem<Double> gpuSystem = GPUEASystemFactory.from(gpuConfig, gpuContext);
62   * 
63   * // Run evolution on GPU
64   * EvolutionResult<Double> result = gpuSystem.evolve();
65   * }</pre>
66   * 
67   * <p>OpenCL integration considerations:
68   * <ul>
69   * <li><strong>Device compatibility</strong>: Ensure target devices support required OpenCL features</li>
70   * <li><strong>Memory management</strong>: GPU memory is typically limited compared to system RAM</li>
71   * <li><strong>Kernel optimization</strong>: GPU performance depends heavily on kernel implementation</li>
72   * <li><strong>Transfer overhead</strong>: Consider data transfer costs between CPU and GPU memory</li>
73   * </ul>
74   * 
75   * <p>Performance optimization tips:
76   * <ul>
77   * <li><strong>Large populations</strong>: GPU acceleration benefits increase with population size</li>
78   * <li><strong>Complex fitness functions</strong>: More computation per individual improves GPU utilization</li>
79   * <li><strong>Minimize transfers</strong>: Keep data on GPU between generations when possible</li>
80   * <li><strong>Coalesced memory access</strong>: Design kernels for optimal memory access patterns</li>
81   * </ul>
82   * 
83   * @see GPUEAConfiguration
84   * @see GPUEAExecutionContext
85   * @see GPUFitnessEvaluator
86   * @see net.bmahe.genetics4j.core.EASystemFactory
87   * @see net.bmahe.genetics4j.gpu.opencl.model.Program
88   */
89  public class GPUEASystemFactory {
90  
91  	private GPUEASystemFactory() {
92  	}
93  
94  	/**
95  	 * Creates a GPU-accelerated EA system with explicit thread pool management.
96  	 * 
97  	 * <p>This method provides full control over thread pool management while enabling GPU acceleration for fitness
98  	 * evaluation. The provided executor service is used for coordinating between CPU and GPU operations, managing
99  	 * asynchronous OpenCL operations, and handling concurrent access to OpenCL resources.
100 	 * 
101 	 * <p>The factory method performs the following operations:
102 	 * <ol>
103 	 * <li>Creates a specialized {@link GPUFitnessEvaluator} configured for OpenCL execution</li>
104 	 * <li>Integrates the GPU evaluator with the core EA framework</li>
105 	 * <li>Ensures proper resource management and cleanup for OpenCL contexts</li>
106 	 * </ol>
107 	 * 
108 	 * <p>Use this method when:
109 	 * <ul>
110 	 * <li>You need explicit control over thread pool configuration and lifecycle</li>
111 	 * <li>Integration with existing thread management systems is required</li>
112 	 * <li>Custom executor services are needed for performance tuning</li>
113 	 * <li>Resource-constrained environments require careful thread pool sizing</li>
114 	 * </ul>
115 	 * 
116 	 * @param <T>                   the type of fitness values, must be comparable for selection operations
117 	 * @param gpuEAConfiguration    the GPU-specific EA configuration with OpenCL program and fitness function
118 	 * @param gpuEAExecutionContext the GPU execution context with device selection and population parameters
119 	 * @param executorService       the thread pool for managing CPU-GPU coordination (caller responsible for shutdown)
120 	 * @return a fully configured {@link EASystem} with GPU acceleration capabilities
121 	 * @throws IllegalArgumentException if any parameter is null
122 	 * @throws RuntimeException         if OpenCL initialization fails or no compatible devices are found
123 	 */
124 	public static <T extends Comparable<T>> EASystem<T> from(final GPUEAConfiguration<T> gpuEAConfiguration,
125 			final GPUEAExecutionContext<T> gpuEAExecutionContext, final ExecutorService executorService) {
126 
127 		final var gpuFitnessEvaluator = new GPUFitnessEvaluator<T>(gpuEAExecutionContext,
128 				gpuEAConfiguration,
129 				executorService);
130 		return EASystemFactory.from(gpuEAConfiguration, gpuEAExecutionContext, gpuFitnessEvaluator);
131 	}
132 
133 	/**
134 	 * Creates a GPU-accelerated EA system using the common thread pool.
135 	 * 
136 	 * <p>This convenience method provides GPU acceleration without requiring explicit thread pool management. It
137 	 * automatically uses {@link ForkJoinPool#commonPool()} for CPU-GPU coordination, making it ideal for applications
138 	 * where thread pool management is not critical.
139 	 * 
140 	 * <p>This method is recommended for:
141 	 * <ul>
142 	 * <li>Rapid prototyping and experimentation with GPU acceleration</li>
143 	 * <li>Applications where default thread pool behavior is sufficient</li>
144 	 * <li>Educational purposes and demonstration code</li>
145 	 * <li>Simple GPU-accelerated applications without complex threading requirements</li>
146 	 * </ul>
147 	 * 
148 	 * <p>The common thread pool provides automatic parallelization and reasonable default behavior for most GPU
149 	 * acceleration scenarios. However, for production systems with specific performance requirements, consider using
150 	 * {@link #from(GPUEAConfiguration, GPUEAExecutionContext, ExecutorService)} with a custom thread pool.
151 	 * 
152 	 * @param <T>                   the type of fitness values, must be comparable for selection operations
153 	 * @param gpuEAConfiguration    the GPU-specific EA configuration with OpenCL program and fitness function
154 	 * @param gpuEAExecutionContext the GPU execution context with device selection and population parameters
155 	 * @return a fully configured {@link EASystem} with GPU acceleration using the common thread pool
156 	 * @throws IllegalArgumentException if any parameter is null
157 	 * @throws RuntimeException         if OpenCL initialization fails or no compatible devices are found
158 	 */
159 	public static <T extends Comparable<T>> EASystem<T> from(final GPUEAConfiguration<T> gpuEAConfiguration,
160 			final GPUEAExecutionContext<T> gpuEAExecutionContext) {
161 		final ExecutorService executorService = ForkJoinPool.commonPool();
162 
163 		return from(gpuEAConfiguration, gpuEAExecutionContext, executorService);
164 	}
165 }