""" MLX-accelerated batch processing for spiking neural networks. This module provides optimized batch processing capabilities using the MLX framework, which is specifically designed for high-performance computation on Apple Silicon hardware. """ import numpy as np from typing import List, Tuple, Dict, Union, Optional, Callable, Any import mlx.core as mx import mlx.nn as nn from dataclasses import dataclass import time import platform from ..utils.common import SpikeState from .sparse_patterns import SparsePattern, SparseFormat, convert_to_sparse, convert_from_sparse class MLXBatchProcessor: """ Class for handling MLX-accelerated batch processing of spike patterns. This class manages efficient transfer of data to and from MLX arrays, automatic batching, and optimized computation on Apple Silicon. """ def __init__( self, device: str = 'gpu', batch_size: Optional[int] = None, precision: str = 'float32' ): """ Initialize the MLX batch processor. Args: device: Device to use ('gpu' or 'cpu') batch_size: Batch size for processing (None for auto-detection) precision: Numerical precision to use """ # Check if MLX is available self.mlx_available = _check_mlx_availability() # Set device self.device = device # Auto-detect optimal batch size if not provided if batch_size is None: self.batch_size = self._detect_optimal_batch_size() else: self.batch_size = batch_size # Set precision if precision == 'float32': self.dtype = mx.float32 elif precision == 'float16': self.dtype = mx.float16 elif precision == 'bfloat16': self.dtype = mx.bfloat16 else: raise ValueError(f"Unsupported precision: {precision}") # Initialize runtime stats self.runtime_stats = { 'total_processing_time': 0.0, 'batch_count': 0, 'total_patterns': 0, 'data_transfer_time': 0.0, 'computation_time': 0.0 } def _detect_optimal_batch_size(self) -> int: """ Detect optimal batch size based on hardware. Returns: Optimal batch size """ if not self.mlx_available: return 32 # Default batch size # Get device information device_info = _get_device_info() # Simple heuristic based on device memory if self.device == 'gpu': if device_info.get('memory_gb', 0) >= 32: return 256 elif device_info.get('memory_gb', 0) >= 16: return 128 elif device_info.get('memory_gb', 0) >= 8: return 64 else: return 32 else: # CPU if device_info.get('memory_gb', 0) >= 32: return 128 elif device_info.get('memory_gb', 0) >= 16: return 64 else: return 32 def process_batch( self, spike_patterns: List[List[List[Tuple[int, SpikeState]]]], processing_function: Callable, sparse_format: Optional[SparseFormat] = None ) -> List[Any]: """ Process a batch of spike patterns using MLX. Args: spike_patterns: List of spike patterns to process processing_function: Function to apply to each pattern sparse_format: Optional sparse format to use Returns: List of processing results """ if not self.mlx_available: # Fall back to sequential processing without MLX return [processing_function(pattern) for pattern in spike_patterns] # Record start time start_time = time.time() # Convert to sparse format if specified if sparse_format is not None: sparse_patterns = [] for pattern in spike_patterns: sparse_patterns.append(convert_to_sparse(pattern, format=sparse_format)) data_to_process = sparse_patterns else: data_to_process = spike_patterns # Process in batches results = [] total_batches = (len(data_to_process) + self.batch_size - 1) // self.batch_size for batch_idx in range(total_batches): batch_start = batch_idx * self.batch_size batch_end = min((batch_idx + 1) * self.batch_size, len(data_to_process)) batch = data_to_process[batch_start:batch_end] # Record data transfer start time transfer_start = time.time() # Convert batch to MLX arrays mlx_batch = self._convert_to_mlx(batch) # Record data transfer end time and computation start time transfer_end = time.time() self.runtime_stats['data_transfer_time'] += transfer_end - transfer_start # Apply processing function to the batch batch_results = self._apply_function_to_batch(mlx_batch, processing_function) # Record computation end time computation_end = time.time() self.runtime_stats['computation_time'] += computation_end - transfer_end # Add batch results to overall results results.extend(batch_results) # Update runtime stats end_time = time.time() self.runtime_stats['total_processing_time'] += end_time - start_time self.runtime_stats['batch_count'] += total_batches self.runtime_stats['total_patterns'] += len(spike_patterns) return results def _convert_to_mlx(self, batch: List[Any]) -> List[Any]: """ Convert batch data to MLX arrays. Args: batch: Batch of data to convert Returns: Batch with MLX arrays """ # Check if batch contains sparse patterns if batch and isinstance(batch[0], SparsePattern): # Convert sparse patterns to MLX-friendly format return self._convert_sparse_to_mlx(batch) # Convert dense patterns to MLX arrays mlx_batch = [] for pattern in batch: if not pattern: # Handle empty pattern mlx_batch.append([]) continue # Get dimensions n_neurons = len(pattern) max_time = max([t for neuron in pattern for t, _ in neuron]) if any(pattern) else 0 # Create empty array pattern_array = mx.zeros((n_neurons, max_time + 1), dtype=self.dtype) # Fill array with spike values for neuron_idx, neuron_spikes in enumerate(pattern): for t, state in neuron_spikes: pattern_array = mx.scatter_add( pattern_array, (neuron_idx, t), mx.array(state.value, dtype=self.dtype) ) mlx_batch.append(pattern_array) return mlx_batch def _convert_sparse_to_mlx(self, batch: List[SparsePattern]) -> List[Any]: """ Convert sparse patterns to MLX arrays. Args: batch: Batch of sparse patterns Returns: Batch with MLX arrays """ mlx_batch = [] for sparse_pattern in batch: if sparse_pattern.format == SparseFormat.BINARY_MASK: # Binary mask format is already efficient for MLX binary_masks = sparse_pattern.data max_time = sparse_pattern.shape[1] # Create full array pattern_array = mx.zeros(sparse_pattern.shape, dtype=self.dtype) # Fill with binary mask data for t, mask in binary_masks.items(): if t < max_time: # Use slice for the entire column indices = list(range(sparse_pattern.shape[0])) for idx, val in enumerate(mask): if idx < sparse_pattern.shape[0]: pattern_array = mx.scatter_add( pattern_array, (idx, t), mx.array(val, dtype=self.dtype) ) mlx_batch.append(pattern_array) else: # Other formats need to be converted to COO first coo_data = convert_from_sparse(sparse_pattern) # Create empty array pattern_array = mx.zeros(sparse_pattern.shape, dtype=self.dtype) # Fill array with spike values for neuron_idx, neuron_spikes in enumerate(coo_data): for t, state in neuron_spikes: pattern_array = mx.scatter_add( pattern_array, (neuron_idx, t), mx.array(state.value, dtype=self.dtype) ) mlx_batch.append(pattern_array) return mlx_batch def _apply_function_to_batch( self, mlx_batch: List[Any], processing_function: Callable ) -> List[Any]: """ Apply processing function to a batch of MLX arrays. Args: mlx_batch: Batch with MLX arrays processing_function: Function to apply Returns: List of processing results """ batch_results = [] for item in mlx_batch: # Apply processing function result = processing_function(item) # Convert result back to CPU if needed if hasattr(result, 'to_numpy'): result = result.to_numpy() batch_results.append(result) return batch_results def get_runtime_stats(self) -> Dict[str, Union[float, int]]: """ Get runtime statistics for performance monitoring. Returns: Dictionary of runtime statistics """ stats = self.runtime_stats.copy() # Add derived statistics if stats['batch_count'] > 0: stats['avg_batch_time'] = stats['total_processing_time'] / stats['batch_count'] if stats['total_patterns'] > 0: stats['avg_pattern_time'] = stats['total_processing_time'] / stats['total_patterns'] if stats['total_processing_time'] > 0: stats['data_transfer_percentage'] = (stats['data_transfer_time'] / stats['total_processing_time']) * 100 stats['computation_percentage'] = (stats['computation_time'] / stats['total_processing_time']) * 100 return stats def reset_runtime_stats(self) -> None: """Reset runtime statistics.""" self.runtime_stats = { 'total_processing_time': 0.0, 'batch_count': 0, 'total_patterns': 0, 'data_transfer_time': 0.0, 'computation_time': 0.0 } def _check_mlx_availability() -> bool: """ Check if MLX is available and properly installed. Returns: Boolean indicating MLX availability """ try: # Check if basic MLX operations work x = mx.array([1, 2, 3]) y = x * 2 return True except Exception: return False def _get_device_info() -> Dict[str, Any]: """ Get information about the current device. Returns: Dictionary with device information """ device_info = {} # Get system information device_info['platform'] = platform.system() device_info['processor'] = platform.processor() # Try to detect Apple Silicon if device_info['platform'] == 'Darwin': try: # Get machine type (arm64 for Apple Silicon) device_info['architecture'] = platform.machine() device_info['is_apple_silicon'] = device_info['architecture'] == 'arm64' # Try to identify specific chip model and memory import subprocess result = subprocess.run(['sysctl', 'hw.memsize'], capture_output=True, text=True) if result.returncode == 0: # Convert bytes to GB memory_bytes = int(result.stdout.split(':')[1].strip()) device_info['memory_gb'] = memory_bytes / (1024**3) except Exception: # Fall back to reasonable defaults device_info['is_apple_silicon'] = False device_info['memory_gb'] = 8 # Conservative default return device_info def batch_process_spikes( spike_patterns: List[List[List[Tuple[int, SpikeState]]]], processing_function: Callable, batch_size: Optional[int] = None, device: str = 'gpu', sparse_format: Optional[SparseFormat] = None ) -> List[Any]: """ Process spike patterns in batches using MLX acceleration. This is a simplified interface for the MLXBatchProcessor. Args: spike_patterns: List of spike patterns to process processing_function: Function to apply to each pattern batch_size: Batch size for processing (None for auto-detection) device: Device to use ('gpu' or 'cpu') sparse_format: Optional sparse format to use Returns: List of processing results """ # Create batch processor processor = MLXBatchProcessor( device=device, batch_size=batch_size ) # Process batch results = processor.process_batch( spike_patterns=spike_patterns, processing_function=processing_function, sparse_format=sparse_format ) return results def run_mlx_accelerated( function: Callable, *args, compile_fn: bool = True, **kwargs ) -> Any: """ Run a function with MLX acceleration. This compiles the function for optimal performance and runs it on GPU if available. Args: function: Function to accelerate *args: Arguments to pass to the function compile_fn: Whether to compile the function **kwargs: Keyword arguments to pass to the function Returns: Function result """ if not _check_mlx_availability(): # Fall back to regular execution return function(*args, **kwargs) # Check if arguments are MLX arrays mlx_args = [] for arg in args: if isinstance(arg, (list, tuple, np.ndarray)) and not isinstance(arg, mx.array): mlx_args.append(mx.array(arg)) else: mlx_args.append(arg) mlx_kwargs = {} for key, value in kwargs.items(): if isinstance(value, (list, tuple, np.ndarray)) and not isinstance(value, mx.array): mlx_kwargs[key] = mx.array(value) else: mlx_kwargs[key] = value # Compile function if requested if compile_fn: compiled_fn = mx.compile(function) result = compiled_fn(*mlx_args, **mlx_kwargs) else: result = function(*mlx_args, **mlx_kwargs) return result def get_device_optimized_batch_size( n_neurons: int, max_time: int, dtype: str = 'float32' ) -> int: """ Calculate optimal batch size based on device capabilities and data dimensions. Args: n_neurons: Number of neurons in each pattern max_time: Maximum time in each pattern dtype: Data type to use Returns: Optimal batch size """ # Get device information device_info = _get_device_info() # Calculate memory per pattern bytes_per_element = 4 if dtype == 'float32' else 2 # float32 = 4 bytes, float16/bfloat16 = 2 bytes pattern_size = n_neurons * max_time * bytes_per_element # Consider overhead and intermediate results total_pattern_size = pattern_size * 2.5 # Factor to account for intermediate results # Calculate optimal batch size based on available memory memory_bytes = device_info.get('memory_gb', 8) * (1024**3) # Allocate 60% of memory for batch processing available_memory = memory_bytes * 0.6 # Calculate batch size batch_size = int(available_memory / total_pattern_size) # Apply reasonable limits batch_size = max(1, min(1024, batch_size)) return batch_size def copy_to_device(data: Any) -> Any: """ Copy data to MLX device memory. Args: data: Data to copy Returns: Data on device """ if not _check_mlx_availability(): return data if isinstance(data, list): return [copy_to_device(item) for item in data] elif isinstance(data, dict): return {key: copy_to_device(value) for key, value in data.items()} elif isinstance(data, tuple): return tuple(copy_to_device(item) for item in data) elif isinstance(data, (int, float, str, bool)): return data elif isinstance(data, np.ndarray): return mx.array(data) elif isinstance(data, SparsePattern): # Convert to dense for MLX processing dense_pattern = convert_from_sparse(data) return copy_to_device(dense_pattern) elif hasattr(data, '__array__'): # Other array-like objects return mx.array(data) else: # Return as-is if not convertible return data def process_in_batches( data: List[Any], process_fn: Callable, batch_size: Optional[int] = None ) -> List[Any]: """ Process a list of data in batches. Args: data: List of data to process process_fn: Processing function to apply batch_size: Batch size (None for auto-detection) Returns: List of processed results """ if not data: return [] # Detect optimal batch size if not provided if batch_size is None: # Use MLXBatchProcessor's auto-detection processor = MLXBatchProcessor() batch_size = processor.batch_size # Process in batches results = [] total_batches = (len(data) + batch_size - 1) // batch_size for batch_idx in range(total_batches): batch_start = batch_idx * batch_size batch_end = min((batch_idx + 1) * batch_size, len(data)) batch = data[batch_start:batch_end] # Process batch if _check_mlx_availability(): # Use MLX for acceleration mlx_batch = copy_to_device(batch) batch_results = run_mlx_accelerated(process_fn, mlx_batch) # Convert results back to regular format if needed if hasattr(batch_results, 'tolist'): batch_results = batch_results.tolist() elif isinstance(batch_results, (list, tuple)) and batch_results and hasattr(batch_results[0], 'tolist'): batch_results = [item.tolist() if hasattr(item, 'tolist') else item for item in batch_results] else: # Regular processing without MLX batch_results = process_fn(batch) # Add batch results to overall results if isinstance(batch_results, list): results.extend(batch_results) else: # Handle case where process_fn returns a single value for the whole batch results.append(batch_results) return results