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 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
"""
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