Instructions to use psikosen/snow_spike with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- MLX
How to use psikosen/snow_spike with MLX:
# Make sure mlx-lm is installed # pip install --upgrade mlx-lm # if on a CUDA device, also pip install mlx[cuda] # Generate text with mlx-lm from mlx_lm import load, generate model, tokenizer = load("psikosen/snow_spike") prompt = "Once upon a time in" text = generate(model, tokenizer, prompt=prompt, verbose=True) - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- LM Studio
- MLX LM
How to use psikosen/snow_spike with MLX LM:
Generate or start a chat session
# Install MLX LM uv tool install mlx-lm # Generate some text mlx_lm.generate --model "psikosen/snow_spike" --prompt "Once upon a time"
- Atomic Chat
Download examples/optimize/integrated_optimization.py from psikosen/snow_spike: direct link, hf CLI and curl.
- Browser
- Download file 11 kB
-
https://huggingface.co/psikosen/snow_spike/resolve/main/examples/optimize/integrated_optimization.py
- Command line
-
hf download hf://psikosen/snow_spike/examples/optimize/integrated_optimization.py
-
curl -L -o integrated_optimization.py https://huggingface.co/psikosen/snow_spike/resolve/main/examples/optimize/integrated_optimization.py
11 kB
| """ | |
| Integration test for all optimization components: | |
| - Sparse pattern representation | |
| - MLX-accelerated batch processing | |
| - Activity-triggered computation | |
| - Compression techniques | |
| This script performs a realistic workflow combining all optimization techniques. | |
| """ | |
| import numpy as np | |
| import time | |
| import matplotlib.pyplot as plt | |
| import os | |
| from typing import List, Tuple, Dict | |
| from src.utils.common import SpikeState | |
| from src.weights.adaptive_network import AdaptiveNetwork | |
| from src.weights.living_weight import LivingWeight | |
| # Import optimization modules | |
| from src.optimize.sparse_patterns import ( | |
| SparseFormat, SparsePattern, convert_to_sparse, convert_from_sparse | |
| ) | |
| from src.optimize.mlx_batch import ( | |
| MLXBatchProcessor, batch_process_spikes | |
| ) | |
| from src.optimize.activity_triggered import ( | |
| ActivityThreshold, ActivityTrigger, create_activity_triggered_network | |
| ) | |
| from src.optimize.compression import ( | |
| CompressionScheme, encode_spike_pattern, decode_spike_pattern | |
| ) | |
| def integrated_optimization_workflow(n_neurons=100, n_patterns=50, max_time=100): | |
| """ | |
| Demonstrate a full optimization workflow combining all techniques. | |
| Args: | |
| n_neurons: Number of neurons in the network | |
| n_patterns: Number of patterns to process | |
| max_time: Maximum time step for patterns | |
| """ | |
| print(f"\n===== Integrated Optimization Workflow =====") | |
| print(f"Network: {n_neurons} neurons, Processing: {n_patterns} patterns") | |
| # Create a network | |
| network = AdaptiveNetwork(n_neurons=n_neurons, n_inputs=n_neurons) | |
| # Create activity-triggered version of network | |
| triggered_network = create_activity_triggered_network( | |
| network, | |
| trigger_config=ActivityTrigger( | |
| threshold_type=ActivityThreshold.RELATIVE, | |
| threshold_value=0.1 # 10% activity threshold | |
| ) | |
| ) | |
| # Create batch processor | |
| batch_processor = MLXBatchProcessor() | |
| # Create patterns with varying activity levels | |
| patterns = [] | |
| for i in range(n_patterns): | |
| pattern = [] | |
| for j in range(n_neurons): | |
| spikes = [] | |
| # Activity decreases with pattern index (sparse to dense) | |
| activity_level = 1.0 - (i / n_patterns) | |
| if np.random.random() < activity_level: | |
| # Add spikes at random times | |
| for _ in range(np.random.randint(1, 5)): | |
| t = np.random.randint(0, max_time) | |
| state = SpikeState.POSITIVE if np.random.random() < 0.7 else SpikeState.NEGATIVE | |
| spikes.append((t, state)) | |
| pattern.append(spikes) | |
| patterns.append(pattern) | |
| # Step 1: Convert patterns to sparse representation | |
| print("\nStep 1: Sparse Representation") | |
| sparse_patterns = [] | |
| dense_sizes = [] | |
| sparse_sizes = [] | |
| sparse_conversion_start = time.time() | |
| for pattern in patterns: | |
| # Estimate original size | |
| dense_size = sum(len(neuron) for neuron in pattern) * 9 # 9 bytes per spike | |
| dense_sizes.append(dense_size) | |
| # Convert to sparse | |
| sparse = convert_to_sparse(pattern, format=SparseFormat.BINARY_MASK) | |
| sparse_patterns.append(sparse) | |
| # Estimate sparse size | |
| sparse_size = sparse.metadata.get('n_spikes', 0) * 4 # 4 bytes per spike | |
| sparse_sizes.append(sparse_size) | |
| sparse_conversion_time = time.time() - sparse_conversion_start | |
| print(f"Conversion time: {sparse_conversion_time*1000:.2f} ms") | |
| print(f"Average compression ratio: {sum(dense_sizes)/sum(sparse_sizes):.2f}x") | |
| # Step 2: Process with MLX batch processor | |
| print("\nStep 2: MLX Batch Processing") | |
| # Define processing function - compute activity ratio | |
| def compute_activity(pattern): | |
| if isinstance(pattern, SparsePattern): | |
| # For sparse pattern, use metadata | |
| n_spikes = pattern.metadata.get('n_spikes', 0) | |
| neurons = pattern.shape[0] | |
| times = pattern.shape[1] | |
| return n_spikes / (neurons * times) if neurons * times > 0 else 0 | |
| else: | |
| # For dense pattern | |
| total_spikes = sum(len(neuron) for neuron in pattern) | |
| neurons = len(pattern) | |
| # Estimate max time | |
| max_t = max([t for neuron in pattern for t, _ in neuron]) if any(pattern) else 0 | |
| return total_spikes / (neurons * (max_t + 1)) if neurons * (max_t + 1) > 0 else 0 | |
| # Sequential processing | |
| sequential_start = time.time() | |
| sequential_results = [compute_activity(pattern) for pattern in patterns] | |
| sequential_time = time.time() - sequential_start | |
| # Batch processing | |
| batch_start = time.time() | |
| batch_results = batch_processor.process_batch( | |
| patterns, # Use original patterns for fair comparison | |
| compute_activity | |
| ) | |
| batch_time = time.time() - batch_start | |
| print(f"Sequential time: {sequential_time*1000:.2f} ms") | |
| print(f"Batch processing time: {batch_time*1000:.2f} ms") | |
| print(f"Speedup: {sequential_time/batch_time:.2f}x") | |
| # Step 3: Activity-triggered computation | |
| print("\nStep 3: Activity-Triggered Computation") | |
| # Process with standard network | |
| standard_start = time.time() | |
| standard_outputs = [] | |
| for pattern in patterns: | |
| output = network.forward(pattern) | |
| standard_outputs.append(output) | |
| standard_time = time.time() - standard_start | |
| # Process with activity-triggered network | |
| triggered_start = time.time() | |
| triggered_outputs = [] | |
| for pattern in patterns: | |
| output = triggered_network.forward(pattern) | |
| triggered_outputs.append(output) | |
| triggered_time = time.time() - triggered_start | |
| print(f"Standard network time: {standard_time*1000:.2f} ms") | |
| print(f"Activity-triggered time: {triggered_time*1000:.2f} ms") | |
| print(f"Speedup: {standard_time/triggered_time:.2f}x") | |
| # Get trigger statistics | |
| stats = triggered_network.get_stats() | |
| print(f"Trigger count: {stats.get('trigger_count', 0)}") | |
| print(f"Compiled pathways: {stats.get('compiled_pathways', 0)}") | |
| # Step 4: Pattern compression | |
| print("\nStep 4: Pattern Compression") | |
| # Create a shared codebook for dictionary compression | |
| codebook = {} | |
| # Test different compression schemes | |
| schemes = [ | |
| CompressionScheme.RUN_LENGTH, | |
| CompressionScheme.DELTA, | |
| CompressionScheme.HUFFMAN, | |
| CompressionScheme.HYBRID | |
| ] | |
| scheme_results = {} | |
| for scheme in schemes: | |
| scheme_start = time.time() | |
| # Compress all patterns | |
| compressed_patterns = [] | |
| for pattern in patterns: | |
| compressed = encode_spike_pattern(pattern, scheme=scheme, codebook=codebook) | |
| compressed_patterns.append(compressed) | |
| # Measure compression ratio and time | |
| ratio = sum(dense_sizes) / sum( | |
| compressed.metadata.get('compressed_size', | |
| len(pickle.dumps(compressed.data))) | |
| for compressed in compressed_patterns | |
| ) | |
| compression_time = time.time() - scheme_start | |
| scheme_results[scheme.value] = { | |
| 'ratio': ratio, | |
| 'time': compression_time | |
| } | |
| print(f"Scheme: {scheme.value}") | |
| print(f" Average ratio: {ratio:.2f}x") | |
| print(f" Total time: {compression_time*1000:.2f} ms") | |
| # Final integrated step: Full pipeline with all optimizations | |
| print("\nFull Optimization Pipeline") | |
| # Time full pipeline with all optimizations | |
| pipeline_start = time.time() | |
| # 1. Convert to sparse | |
| sparse_patterns = [convert_to_sparse(p, format=SparseFormat.BINARY_MASK) for p in patterns] | |
| # 2. Compress the sparse patterns | |
| compressed_patterns = [encode_spike_pattern(p, scheme=CompressionScheme.HYBRID) | |
| for p in sparse_patterns] | |
| # 3. Batch process with MLX | |
| def process_compressed(compressed): | |
| # Decompress | |
| sparse = decode_spike_pattern(compressed) | |
| # Convert to dense | |
| pattern = convert_from_sparse(sparse) | |
| # Process with activity-triggered network | |
| return triggered_network.forward(pattern) | |
| results = batch_processor.process_batch( | |
| compressed_patterns, | |
| process_compressed | |
| ) | |
| pipeline_time = time.time() - pipeline_start | |
| # Time baseline without optimizations | |
| baseline_start = time.time() | |
| baseline_results = [] | |
| for pattern in patterns: | |
| output = network.forward(pattern) | |
| baseline_results.append(output) | |
| baseline_time = time.time() - baseline_start | |
| print(f"Baseline time: {baseline_time*1000:.2f} ms") | |
| print(f"Optimized pipeline time: {pipeline_time*1000:.2f} ms") | |
| print(f"Overall speedup: {baseline_time/pipeline_time:.2f}x") | |
| return { | |
| 'sparse_ratio': sum(dense_sizes)/sum(sparse_sizes), | |
| 'mlx_speedup': sequential_time/batch_time, | |
| 'activity_speedup': standard_time/triggered_time, | |
| 'compression_ratios': {scheme: results['ratio'] for scheme, results in scheme_results.items()}, | |
| 'overall_speedup': baseline_time/pipeline_time | |
| } | |
| if __name__ == "__main__": | |
| # Create output directory | |
| os.makedirs("outputs", exist_ok=True) | |
| # Import pickle here to avoid global import | |
| import pickle | |
| # Run the integrated workflow | |
| results = integrated_optimization_workflow() | |
| # Print summary | |
| print("\n===== Optimization Summary =====") | |
| print(f"Sparse representation compression: {results['sparse_ratio']:.2f}x") | |
| print(f"MLX batch processing speedup: {results['mlx_speedup']:.2f}x") | |
| print(f"Activity-triggered computation speedup: {results['activity_speedup']:.2f}x") | |
| print(f"Best compression ratio: {max(results['compression_ratios'].values()):.2f}x") | |
| print(f"Overall pipeline speedup: {results['overall_speedup']:.2f}x") | |
| # Create a summary visualization | |
| plt.figure(figsize=(10, 6)) | |
| # Plot speedups | |
| speedups = { | |
| 'Sparse\nRepresentation': results['sparse_ratio'], | |
| 'MLX\nBatch': results['mlx_speedup'], | |
| 'Activity\nTriggered': results['activity_speedup'], | |
| 'Compression\n(Best)': max(results['compression_ratios'].values()), | |
| 'Full\nPipeline': results['overall_speedup'] | |
| } | |
| plt.bar(speedups.keys(), speedups.values()) | |
| plt.ylabel('Improvement Factor (x)') | |
| plt.title('Performance Optimization Results') | |
| plt.ylim(bottom=0) | |
| # Add value labels | |
| for i, (key, value) in enumerate(speedups.items()): | |
| plt.text(i, value + 0.1, f'{value:.2f}x', ha='center') | |
| plt.tight_layout() | |
| plt.savefig('outputs/optimization_summary.png') | |
| plt.close() | |
| print("\nOptimization summary saved to outputs/optimization_summary.png") | |