""" Benchmark tests comparing performance with and without MLX acceleration. This script addresses the Phase 6 TODO item for performance benchmarking. """ import sys import os import time import numpy as np import matplotlib.pyplot as plt import random import argparse from typing import Dict, List, Tuple, Any # Add project root to path sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) # Import core modules from src.entropy.spike_entropy import compute_neuron_entropy, aggregate_network_entropy from src.weights.living_weight import LivingWeight from src.weights.adaptive_network import AdaptiveNetwork # Import NLP modules from src.nlp.char_encoding import TextSpikeEncoder from src.nlp.sequential import SequentialAdaptiveNetwork from src.nlp.multi_scale import MultiScaleTextProcessor # Try to import MLX try: import mlx.core as mx HAS_MLX = True except ImportError: HAS_MLX = False print("MLX not found. Will benchmark with NumPy only.") # Global settings ITERATIONS = 5 # Number of iterations for each benchmark WARMUP = 2 # Warmup iterations to exclude from timing def benchmark_entropy_calculation(sizes: List[int], use_mlx: bool = True) -> Dict[int, float]: """ Benchmark entropy calculation with different sizes. Args: sizes: List of neuron counts to benchmark use_mlx: Whether to use MLX acceleration Returns: results: Dict mapping size to average time """ print(f"\nBenchmarking entropy calculation {'with MLX' if use_mlx else 'without MLX'}") # Toggle MLX usage through environment variable if not use_mlx: os.environ['USE_MLX'] = '0' else: os.environ['USE_MLX'] = '1' results = {} for size in sizes: print(f" Testing size: {size}") times = [] for i in range(ITERATIONS + WARMUP): # Generate random spike data spike_data = np.random.choice([-1, 0, 1], size=(100, size)) # Time computation start_time = time.time() # Calculate entropy entropies = [] for neuron_idx in range(size): spikes = spike_data[:, neuron_idx] counts = [sum(spikes == -1), sum(spikes == 0), sum(spikes == 1)] probabilities = [c / len(spikes) for c in counts] entropy = compute_neuron_entropy(probabilities) entropies.append(entropy) network_entropy = aggregate_network_entropy(entropies) elapsed = time.time() - start_time # Skip warmup iterations if i >= WARMUP: times.append(elapsed) # Calculate average avg_time = sum(times) / len(times) results[size] = avg_time print(f" Average time: {avg_time:.6f} seconds") return results def benchmark_adaptive_network(sizes: List[int], use_mlx: bool = True) -> Dict[int, float]: """ Benchmark adaptive network forward pass. Args: sizes: List of input sizes to benchmark use_mlx: Whether to use MLX acceleration Returns: results: Dict mapping size to average time """ print(f"\nBenchmarking adaptive network {'with MLX' if use_mlx else 'without MLX'}") # Toggle MLX usage through environment variable if not use_mlx: os.environ['USE_MLX'] = '0' else: os.environ['USE_MLX'] = '1' results = {} for input_size in sizes: print(f" Testing input size: {input_size}") # Create network (fixed architecture scaled to input) layer_sizes = [input_size, input_size//2, input_size//4] network = AdaptiveNetwork(layer_sizes) times = [] for i in range(ITERATIONS + WARMUP): # Generate random input inputs = np.random.choice([-1, 0, 1], size=input_size) # Time forward pass start_time = time.time() _ = network.forward(inputs) elapsed = time.time() - start_time # Skip warmup iterations if i >= WARMUP: times.append(elapsed) # Calculate average avg_time = sum(times) / len(times) results[input_size] = avg_time print(f" Average time: {avg_time:.6f} seconds") return results def benchmark_nlp_processing(text_sizes: List[int], use_mlx: bool = True) -> Dict[int, float]: """ Benchmark NLP processing with different text sizes. Args: text_sizes: List of text lengths to benchmark use_mlx: Whether to use MLX acceleration Returns: results: Dict mapping size to average time """ print(f"\nBenchmarking NLP processing {'with MLX' if use_mlx else 'without MLX'}") # Toggle MLX usage through environment variable if not use_mlx: os.environ['USE_MLX'] = '0' else: os.environ['USE_MLX'] = '1' # Sample text to replicate sample_text = """ The quick brown fox jumps over the lazy dog. This sentence contains every letter in the English alphabet. Natural language processing with spiking neural networks is an interesting research area. How can we adapt traditional methods for this new paradigm? The key is to find representations that work well with discrete spike patterns. """ # Create processor with smaller networks for benchmarking processor = MultiScaleTextProcessor({ 'char_network_sizes': [32, 16, 8], 'word_network_sizes': [48, 24, 8], 'structure_network_sizes': [24, 16, 8], 'integration_network_sizes': [24, 16, 8] }) results = {} for size in text_sizes: print(f" Testing text size: {size}") # Create text of appropriate size if size <= len(sample_text): text = sample_text[:size] else: # Repeat sample text repetitions = (size // len(sample_text)) + 1 text = sample_text * repetitions text = text[:size] times = [] for i in range(ITERATIONS + WARMUP): # Time processing start_time = time.time() _ = processor.process_text(text) elapsed = time.time() - start_time # Skip warmup iterations if i >= WARMUP: times.append(elapsed) # Calculate average avg_time = sum(times) / len(times) results[size] = avg_time print(f" Average time: {avg_time:.6f} seconds") return results def plot_comparison(with_mlx: Dict[int, float], without_mlx: Dict[int, float], title: str, xlabel: str, ylabel: str, output_file: str) -> None: """ Plot comparison of with/without MLX performance. Args: with_mlx: Results with MLX without_mlx: Results without MLX title: Plot title xlabel: X-axis label ylabel: Y-axis label output_file: Output file path """ plt.figure(figsize=(10, 6)) # Extract data sizes = sorted(with_mlx.keys()) mlx_times = [with_mlx[size] for size in sizes] numpy_times = [without_mlx[size] for size in sizes] # Calculate speedup speedups = [numpy_times[i] / mlx_times[i] for i in range(len(sizes))] # Plotting plt.subplot(1, 2, 1) plt.plot(sizes, mlx_times, 'b-o', label='With MLX') plt.plot(sizes, numpy_times, 'r-o', label='Without MLX') plt.title(title) plt.xlabel(xlabel) plt.ylabel(ylabel) plt.grid(True) plt.legend() plt.subplot(1, 2, 2) plt.bar(range(len(sizes)), speedups, align='center') plt.xticks(range(len(sizes)), sizes) plt.title('MLX Speedup Factor') plt.xlabel(xlabel) plt.ylabel('Speedup (x)') plt.grid(True) # Add value labels on bars for i, v in enumerate(speedups): plt.text(i, v + 0.1, f"{v:.2f}x", ha='center') plt.tight_layout() plt.savefig(output_file) print(f"Plot saved as '{output_file}'") def run_all_benchmarks() -> None: """Run all benchmarks and plot results.""" print("Running comprehensive benchmarks (this may take some time)...") # Create output directory os.makedirs('benchmarks', exist_ok=True) # Benchmark entropy calculation entropy_sizes = [100, 500, 1000, 5000, 10000] entropy_with_mlx = benchmark_entropy_calculation(entropy_sizes, use_mlx=True) entropy_without_mlx = benchmark_entropy_calculation(entropy_sizes, use_mlx=False) plot_comparison( entropy_with_mlx, entropy_without_mlx, 'Entropy Calculation Performance', 'Number of Neurons', 'Time (seconds)', 'benchmarks/entropy_benchmark.png' ) # Benchmark adaptive network network_sizes = [100, 500, 1000, 2000, 5000] network_with_mlx = benchmark_adaptive_network(network_sizes, use_mlx=True) network_without_mlx = benchmark_adaptive_network(network_sizes, use_mlx=False) plot_comparison( network_with_mlx, network_without_mlx, 'Adaptive Network Performance', 'Input Size', 'Time (seconds)', 'benchmarks/network_benchmark.png' ) # Benchmark NLP processing nlp_sizes = [100, 500, 1000, 2000, 5000] nlp_with_mlx = benchmark_nlp_processing(nlp_sizes, use_mlx=True) nlp_without_mlx = benchmark_nlp_processing(nlp_sizes, use_mlx=False) plot_comparison( nlp_with_mlx, nlp_without_mlx, 'NLP Processing Performance', 'Text Length (characters)', 'Time (seconds)', 'benchmarks/nlp_benchmark.png' ) # Create summary report with open('benchmarks/benchmark_summary.txt', 'w') as f: f.write("Snow Spike Benchmark Summary\n") f.write("===========================\n\n") f.write("System Information:\n") f.write(f"MLX Available: {HAS_MLX}\n") f.write(f"Python Version: {sys.version}\n\n") f.write("Entropy Calculation Benchmark:\n") f.write("-----------------------------\n") for size in entropy_sizes: speedup = entropy_without_mlx[size] / entropy_with_mlx[size] f.write(f"Size {size}: {entropy_with_mlx[size]:.6f}s (MLX) vs {entropy_without_mlx[size]:.6f}s (NumPy) - {speedup:.2f}x speedup\n") f.write("\n") f.write("Adaptive Network Benchmark:\n") f.write("-------------------------\n") for size in network_sizes: speedup = network_without_mlx[size] / network_with_mlx[size] f.write(f"Size {size}: {network_with_mlx[size]:.6f}s (MLX) vs {network_without_mlx[size]:.6f}s (NumPy) - {speedup:.2f}x speedup\n") f.write("\n") f.write("NLP Processing Benchmark:\n") f.write("------------------------\n") for size in nlp_sizes: speedup = nlp_without_mlx[size] / nlp_with_mlx[size] f.write(f"Size {size}: {nlp_with_mlx[size]:.6f}s (MLX) vs {nlp_without_mlx[size]:.6f}s (NumPy) - {speedup:.2f}x speedup\n") print("\nBenchmark summary saved to 'benchmarks/benchmark_summary.txt'") if __name__ == "__main__": parser = argparse.ArgumentParser(description='Snow Spike Performance Benchmarks') parser.add_argument('--entropy', action='store_true', help='Run entropy calculation benchmark only') parser.add_argument('--network', action='store_true', help='Run adaptive network benchmark only') parser.add_argument('--nlp', action='store_true', help='Run NLP processing benchmark only') parser.add_argument('--sizes', type=str, default=None, help='Comma-separated list of sizes to benchmark') args = parser.parse_args() # Parse custom sizes if provided custom_sizes = None if args.sizes: try: custom_sizes = [int(s) for s in args.sizes.split(',')] except ValueError: print("Error: sizes must be comma-separated integers") sys.exit(1) # Run specific benchmark or all if args.entropy: sizes = custom_sizes or [100, 500, 1000, 5000, 10000] with_mlx = benchmark_entropy_calculation(sizes, use_mlx=True) without_mlx = benchmark_entropy_calculation(sizes, use_mlx=False) os.makedirs('benchmarks', exist_ok=True) plot_comparison( with_mlx, without_mlx, 'Entropy Calculation Performance', 'Number of Neurons', 'Time (seconds)', 'benchmarks/entropy_benchmark.png' ) elif args.network: sizes = custom_sizes or [100, 500, 1000, 2000, 5000] with_mlx = benchmark_adaptive_network(sizes, use_mlx=True) without_mlx = benchmark_adaptive_network(sizes, use_mlx=False) os.makedirs('benchmarks', exist_ok=True) plot_comparison( with_mlx, without_mlx, 'Adaptive Network Performance', 'Input Size', 'Time (seconds)', 'benchmarks/network_benchmark.png' ) elif args.nlp: sizes = custom_sizes or [100, 500, 1000, 2000, 5000] with_mlx = benchmark_nlp_processing(sizes, use_mlx=True) without_mlx = benchmark_nlp_processing(sizes, use_mlx=False) os.makedirs('benchmarks', exist_ok=True) plot_comparison( with_mlx, without_mlx, 'NLP Processing Performance', 'Text Length (characters)', 'Time (seconds)', 'benchmarks/nlp_benchmark.png' ) else: run_all_benchmarks()