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
File size: 10,962 Bytes
26be21c | 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 | """
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")
|