snow_spike / src /optimize /activity_triggered.py
psikosen's picture
Add files using upload-large-folder tool
1e12712 verified
Raw History Blame Contribute Delete
29.1 kB
"""
Activity-triggered computation for spiking neural networks.
This module provides mechanisms for selectively activating computations
based on neural activity patterns, enabling significant performance
improvements for sparse spiking networks.
"""
import numpy as np
from typing import List, Tuple, Dict, Union, Optional, Callable, Any
from enum import Enum
from dataclasses import dataclass
import mlx.core as mx
import mlx.nn as nn
import time
import weakref
from ..utils.common import SpikeState
class CompilationStrategy(Enum):
"""Enumeration of compilation strategies for activity-triggered computation."""
STATIC = "static" # Pre-compile all possible pathways
DYNAMIC = "dynamic" # Compile pathways on-demand
HYBRID = "hybrid" # Pre-compile common pathways, dynamic for rare ones
ADAPTIVE = "adaptive" # Adapt compilation based on observed patterns
class ActivityThreshold(Enum):
"""Enumeration of thresholding strategies for activity-triggered computation."""
ABSOLUTE = "absolute" # Fixed number of active neurons
RELATIVE = "relative" # Fraction of total neurons
STDDEV = "stddev" # Standard deviations from mean
ADAPTIVE = "adaptive" # Automatically adjusted threshold
PERCENTILE = "percentile" # Percentile of activity distribution
@dataclass
class ActivityTrigger:
"""
Data class for activity trigger configuration.
Attributes:
threshold_type: Type of threshold to use
threshold_value: Value for the threshold
min_active: Minimum number of active neurons
cooldown: Number of steps to wait before recompiling
compilation_strategy: Strategy for compiling computation paths
"""
threshold_type: ActivityThreshold = ActivityThreshold.RELATIVE
threshold_value: float = 0.1 # Default: 10% of neurons must be active
min_active: int = 1 # At least one neuron must be active
cooldown: int = 5 # Wait 5 steps before recompiling
compilation_strategy: CompilationStrategy = CompilationStrategy.HYBRID
@dataclass
class ActivityStats:
"""
Data class for tracking neural activity statistics.
Attributes:
mean_activity: Mean activity level
stddev_activity: Standard deviation of activity
max_activity: Maximum observed activity
min_activity: Minimum observed activity
activity_history: Recent activity levels
last_trigger_time: When the last trigger occurred
trigger_count: How many times triggers have occurred
"""
mean_activity: float = 0.0
stddev_activity: float = 0.0
max_activity: float = 0.0
min_activity: float = 0.0
activity_history: List[float] = None
last_trigger_time: int = 0
trigger_count: int = 0
def __post_init__(self):
if self.activity_history is None:
self.activity_history = []
class ActivityTriggeredComputation:
"""
Class for managing activity-triggered computation.
This class provides mechanisms to selectively activate computations
based on neural activity patterns, enabling more efficient processing
of sparse spiking activity.
"""
def __init__(
self,
trigger: ActivityTrigger = None,
history_length: int = 100,
max_cached_pathways: int = 10
):
"""
Initialize activity-triggered computation.
Args:
trigger: Activity trigger configuration
history_length: Length of activity history to maintain
max_cached_pathways: Maximum number of compiled pathways to cache
"""
self.trigger = trigger if trigger is not None else ActivityTrigger()
self.history_length = history_length
self.max_cached_pathways = max_cached_pathways
# Initialize activity statistics
self.stats = ActivityStats(activity_history=[])
# Initialize compilation cache
self.compiled_pathways = {}
self.pathway_usage = {}
self.current_time = 0
def update_stats(self, activity_level: float) -> None:
"""
Update activity statistics.
Args:
activity_level: Current activity level (0 to 1)
"""
# Add to history
self.stats.activity_history.append(activity_level)
# Trim history if needed
if len(self.stats.activity_history) > self.history_length:
self.stats.activity_history = self.stats.activity_history[-self.history_length:]
# Update statistics
if self.stats.activity_history:
self.stats.mean_activity = np.mean(self.stats.activity_history)
self.stats.stddev_activity = np.std(self.stats.activity_history)
self.stats.max_activity = max(self.stats.activity_history)
self.stats.min_activity = min(self.stats.activity_history)
# Increment current time
self.current_time += 1
def should_trigger(
self,
active_neurons: Union[List[int], np.ndarray, mx.array],
total_neurons: int
) -> bool:
"""
Determine if computation should be triggered based on activity.
Args:
active_neurons: List or array of active neuron indices
total_neurons: Total number of neurons
Returns:
Boolean indicating whether computation should be triggered
"""
# Calculate activity level
if isinstance(active_neurons, (list, tuple)):
activity_level = len(active_neurons) / total_neurons
active_count = len(active_neurons)
elif isinstance(active_neurons, (np.ndarray, mx.array)):
if active_neurons.ndim == 1:
activity_level = len(active_neurons) / total_neurons
active_count = len(active_neurons)
else:
# For multi-dimensional arrays, count non-zero elements
activity_level = np.count_nonzero(active_neurons) / total_neurons
active_count = np.count_nonzero(active_neurons)
else:
raise ValueError(f"Unsupported active_neurons type: {type(active_neurons)}")
# Update activity statistics
self.update_stats(activity_level)
# Check cooldown period
if self.current_time - self.stats.last_trigger_time < self.trigger.cooldown:
return False
# Apply threshold based on threshold type
if self.trigger.threshold_type == ActivityThreshold.ABSOLUTE:
should_trigger = active_count >= self.trigger.threshold_value
elif self.trigger.threshold_type == ActivityThreshold.RELATIVE:
should_trigger = activity_level >= self.trigger.threshold_value
elif self.trigger.threshold_type == ActivityThreshold.STDDEV:
# Trigger if activity is more than threshold_value standard deviations above mean
if len(self.stats.activity_history) > 10: # Ensure enough history
threshold = self.stats.mean_activity + self.trigger.threshold_value * self.stats.stddev_activity
should_trigger = activity_level >= threshold
else:
should_trigger = activity_level >= self.trigger.threshold_value
elif self.trigger.threshold_type == ActivityThreshold.ADAPTIVE:
# Adaptive threshold based on recent history
if len(self.stats.activity_history) > 10:
# Use the 75th percentile as an adaptive threshold
threshold = np.percentile(self.stats.activity_history, 75)
should_trigger = activity_level >= threshold
else:
should_trigger = activity_level >= self.trigger.threshold_value
elif self.trigger.threshold_type == ActivityThreshold.PERCENTILE:
# Use the specified percentile
if len(self.stats.activity_history) > 10:
threshold = np.percentile(self.stats.activity_history, self.trigger.threshold_value * 100)
should_trigger = activity_level >= threshold
else:
should_trigger = activity_level >= 0.5 # Default 50% threshold
else:
raise ValueError(f"Unsupported threshold type: {self.trigger.threshold_type}")
# Also check minimum active count
should_trigger = should_trigger and active_count >= self.trigger.min_active
# Update trigger statistics if triggered
if should_trigger:
self.stats.last_trigger_time = self.current_time
self.stats.trigger_count += 1
return should_trigger
def get_active_pathway(
self,
active_neurons: Union[List[int], np.ndarray, mx.array],
computation_fn: Callable,
force_compile: bool = False
) -> Callable:
"""
Get compiled computation pathway for the current activity pattern.
Args:
active_neurons: List or array of active neuron indices
computation_fn: Function to compile for the pathway
force_compile: Whether to force recompilation
Returns:
Compiled function for the activity pathway
"""
# Create a hashable representation of active neurons
if isinstance(active_neurons, (list, tuple)):
active_key = tuple(sorted(active_neurons))
elif isinstance(active_neurons, np.ndarray):
active_key = tuple(sorted(active_neurons.flatten().tolist()))
elif isinstance(active_neurons, mx.array):
active_key = tuple(sorted(active_neurons.tolist()))
else:
raise ValueError(f"Unsupported active_neurons type: {type(active_neurons)}")
# Check if pathway is already compiled
if not force_compile and active_key in self.compiled_pathways:
# Update usage statistics
self.pathway_usage[active_key] = self.current_time
return self.compiled_pathways[active_key]
# Decide whether to compile based on strategy
should_compile = True
if self.trigger.compilation_strategy == CompilationStrategy.STATIC:
# Only use pre-compiled pathways, don't compile new ones
should_compile = active_key in self.compiled_pathways
elif self.trigger.compilation_strategy == CompilationStrategy.DYNAMIC:
# Always compile new pathways
should_compile = True
elif self.trigger.compilation_strategy == CompilationStrategy.HYBRID:
# Compile if we have space or if this is a common pattern
if len(self.compiled_pathways) < self.max_cached_pathways:
should_compile = True
else:
# Check if this pattern is similar to an existing one
for existing_key in self.compiled_pathways:
if _pattern_similarity(active_key, existing_key) > 0.8:
# Use the existing pathway
active_key = existing_key
should_compile = False
break
elif self.trigger.compilation_strategy == CompilationStrategy.ADAPTIVE:
# Compile new pathways adaptively based on history
if len(self.compiled_pathways) < self.max_cached_pathways:
should_compile = True
else:
# Find the least recently used pathway
lru_key, _ = min(self.pathway_usage.items(), key=lambda x: x[1])
# Replace it with the new pathway
del self.compiled_pathways[lru_key]
del self.pathway_usage[lru_key]
should_compile = True
# Compile the pathway if needed
if should_compile and not (active_key in self.compiled_pathways):
# Create a specialized version of the function for this activity pattern
specialized_fn = _create_specialized_function(computation_fn, active_key)
# Compile the specialized function
compiled_fn = mx.compile(specialized_fn)
# Store in cache
self.compiled_pathways[active_key] = compiled_fn
self.pathway_usage[active_key] = self.current_time
return compiled_fn
# Return the compiled pathway
return self.compiled_pathways.get(active_key, computation_fn)
def get_stats(self) -> Dict[str, Any]:
"""
Get current activity statistics.
Returns:
Dictionary of statistics
"""
return {
'mean_activity': self.stats.mean_activity,
'stddev_activity': self.stats.stddev_activity,
'max_activity': self.stats.max_activity,
'min_activity': self.stats.min_activity,
'current_time': self.current_time,
'last_trigger_time': self.stats.last_trigger_time,
'trigger_count': self.stats.trigger_count,
'compiled_pathways': len(self.compiled_pathways),
'activity_history': self.stats.activity_history[-10:] if self.stats.activity_history else []
}
def _pattern_similarity(
pattern1: Tuple[int, ...],
pattern2: Tuple[int, ...]
) -> float:
"""
Compute similarity between two activity patterns.
Args:
pattern1: First activity pattern as tuple of neuron indices
pattern2: Second activity pattern as tuple of neuron indices
Returns:
Similarity score (0 to 1, higher is more similar)
"""
# Convert to sets for efficient intersection and union
set1 = set(pattern1)
set2 = set(pattern2)
# Compute Jaccard similarity
intersection = len(set1.intersection(set2))
union = len(set1.union(set2))
if union == 0:
return 1.0 if len(set1) == 0 and len(set2) == 0 else 0.0
return intersection / union
def _create_specialized_function(
original_fn: Callable,
active_pattern: Tuple[int, ...]
) -> Callable:
"""
Create a specialized version of a function for a specific activity pattern.
Args:
original_fn: Original computation function
active_pattern: Activity pattern as tuple of neuron indices
Returns:
Specialized function
"""
# Create a closure over the original function and active pattern
def specialized_fn(*args, **kwargs):
# Call the original function with the knowledge of which neurons are active
return original_fn(*args, active_neurons=active_pattern, **kwargs)
# Set metadata
specialized_fn.__name__ = f"{original_fn.__name__}_specialized"
return specialized_fn
def trigger_on_activity(
spike_pattern: List[List[Tuple[int, SpikeState]]],
computation_fn: Callable,
trigger_config: ActivityTrigger = None,
default_result: Any = None
) -> Any:
"""
Execute computation only if activity threshold is met.
Args:
spike_pattern: Spike pattern to analyze
computation_fn: Computation function to potentially execute
trigger_config: Activity trigger configuration
default_result: Result to return if computation is not triggered
Returns:
Computation result or default
"""
# Use default configuration if not provided
trigger = trigger_config if trigger_config is not None else ActivityTrigger()
# Calculate active neurons
active_neurons = []
for neuron_idx, neuron_spikes in enumerate(spike_pattern):
for _, state in neuron_spikes:
if state == SpikeState.POSITIVE:
active_neurons.append(neuron_idx)
break # Only count each neuron once
# Create activity triggered computation manager
manager = ActivityTriggeredComputation(trigger=trigger)
# Check if computation should be triggered
if manager.should_trigger(active_neurons, len(spike_pattern)):
# Execute computation
return computation_fn(spike_pattern)
else:
# Return default result
return default_result
def compile_active_pathway(
computation_fn: Callable,
active_neurons: Union[List[int], np.ndarray, mx.array],
input_shape: Tuple[int, ...] = None
) -> Callable:
"""
Compile a computation pathway optimized for a specific activity pattern.
Args:
computation_fn: Computation function to compile
active_neurons: List or array of active neuron indices
input_shape: Shape of input data
Returns:
Compiled function
"""
# Create a specialized function for the active neurons
if isinstance(active_neurons, (list, tuple)):
active_key = tuple(sorted(active_neurons))
elif isinstance(active_neurons, np.ndarray):
active_key = tuple(sorted(active_neurons.flatten().tolist()))
elif isinstance(active_neurons, mx.array):
active_key = tuple(sorted(active_neurons.tolist()))
else:
raise ValueError(f"Unsupported active_neurons type: {type(active_neurons)}")
# Create specialized function
specialized_fn = _create_specialized_function(computation_fn, active_key)
# If input shape is provided, create a dummy input for tracing
if input_shape is not None:
# Create dummy input
dummy_input = mx.zeros(input_shape)
# Trace the function with dummy input
def traced_fn(*args, **kwargs):
# Replace the first argument with dummy_input during tracing
if args:
args = (dummy_input,) + args[1:]
return specialized_fn(*args, **kwargs)
# Compile the traced function
compiled_fn = mx.compile(traced_fn)
else:
# Compile without tracing
compiled_fn = mx.compile(specialized_fn)
return compiled_fn
class ActivityTriggeredNetwork:
"""
Network with activity-triggered computation for sparse spike processing.
This class wraps a neural network to selectively activate computations
based on neural activity patterns.
"""
def __init__(
self,
network: Any,
trigger_config: ActivityTrigger = None,
history_length: int = 100,
max_cached_pathways: int = 10,
activation_fn: Optional[Callable] = None
):
"""
Initialize the activity-triggered network.
Args:
network: Underlying neural network to wrap
trigger_config: Activity trigger configuration
history_length: Length of activity history to maintain
max_cached_pathways: Maximum number of compiled pathways to cache
activation_fn: Optional activation function for determining active neurons
"""
self.network = network
self.trigger_manager = ActivityTriggeredComputation(
trigger=trigger_config,
history_length=history_length,
max_cached_pathways=max_cached_pathways
)
self.activation_fn = activation_fn
# Create weak reference to avoid memory leaks
self._network_ref = weakref.ref(network)
def forward(self, x: Any, *args, **kwargs) -> Any:
"""
Forward pass through the network with activity-triggered optimization.
Args:
x: Input data
*args: Additional arguments to pass to network
**kwargs: Additional keyword arguments to pass to network
Returns:
Network output
"""
# Get active neurons based on input
active_neurons = self._get_active_neurons(x)
# Check if we should use the activity-triggered pathway
if self.trigger_manager.should_trigger(active_neurons, self._get_total_neurons()):
# Get compiled pathway for these active neurons
network_fn = self.trigger_manager.get_active_pathway(
active_neurons,
self._create_network_function()
)
# Execute the compiled pathway
return network_fn(x, *args, **kwargs)
else:
# Fall back to regular network execution
network = self._network_ref()
if network is None:
raise ValueError("Network has been garbage collected")
return network(x, *args, **kwargs)
def _get_active_neurons(self, x: Any) -> List[int]:
"""
Determine active neurons based on input.
Args:
x: Input data
Returns:
List of active neuron indices
"""
# Use provided activation function if any
if self.activation_fn is not None:
return self.activation_fn(x)
# Default implementation depends on input type
if isinstance(x, (np.ndarray, mx.array)):
if x.ndim == 1:
# For 1D input, treat non-zero values as active
return np.where(np.abs(x) > 0)[0].tolist()
elif x.ndim == 2:
# For 2D input (neurons x time), check if any time step is active
if isinstance(x, mx.array):
x_np = x.tolist()
return [i for i, row in enumerate(x_np) if any(np.abs(val) > 0 for val in row)]
else:
return [i for i, row in enumerate(x) if np.any(np.abs(row) > 0)]
else:
# For higher dimensions, flatten and find non-zero indices
flat_x = x.reshape(-1)
return np.where(np.abs(flat_x) > 0)[0].tolist()
elif isinstance(x, list):
# Assume list of spike trains format [neurons][spikes]
return [i for i, spikes in enumerate(x) if spikes]
# Default: assume all neurons are active
return list(range(self._get_total_neurons()))
def _get_total_neurons(self) -> int:
"""
Get total number of neurons in the network.
Returns:
Number of neurons
"""
network = self._network_ref()
if network is None:
raise ValueError("Network has been garbage collected")
# Try to get from network attributes
if hasattr(network, 'n_neurons'):
return network.n_neurons
elif hasattr(network, 'units'):
return network.units
# Default: assume a reasonably sized network
return 100
def _create_network_function(self) -> Callable:
"""
Create a function that wraps the network forward pass.
Returns:
Network function
"""
def network_fn(x, *args, active_neurons=None, **kwargs):
network = self._network_ref()
if network is None:
raise ValueError("Network has been garbage collected")
# If active_neurons is provided, optimize computation
if active_neurons is not None:
# Create optimized version of input and network operations
return self._optimized_forward(x, active_neurons, *args, **kwargs)
# Otherwise, regular forward pass
return network(x, *args, **kwargs)
return network_fn
def _optimized_forward(
self,
x: Any,
active_neurons: List[int],
*args,
**kwargs
) -> Any:
"""
Optimized forward pass that only computes for active neurons.
Args:
x: Input data
active_neurons: List of active neuron indices
*args: Additional arguments
**kwargs: Additional keyword arguments
Returns:
Network output
"""
network = self._network_ref()
if network is None:
raise ValueError("Network has been garbage collected")
# Create mask for active neurons
mask = np.zeros(self._get_total_neurons(), dtype=bool)
mask[active_neurons] = True
# Apply mask to input if appropriate
if isinstance(x, (np.ndarray, mx.array)) and x.shape[0] == len(mask):
# Only keep active rows
masked_x = x[mask]
# Call network with masked input (implementation specific)
if hasattr(network, 'forward_masked'):
# If network has specialized masked forward, use it
result = network.forward_masked(masked_x, mask, *args, **kwargs)
else:
# Otherwise, use regular forward and expand result
partial_result = network(masked_x, *args, **kwargs)
# Expand partial result back to full size
# Note: This assumes the network output has the same number of neurons
# as the input, which may not always be true
result = _expand_partial_result(partial_result, mask)
return result
# If masking is not possible, fall back to regular forward
return network(x, *args, **kwargs)
def get_stats(self) -> Dict[str, Any]:
"""
Get current activity statistics.
Returns:
Dictionary of statistics
"""
return self.trigger_manager.get_stats()
def _expand_partial_result(
partial_result: Any,
mask: np.ndarray
) -> Any:
"""
Expand a partial result to full size based on mask.
Args:
partial_result: Result for active neurons only
mask: Boolean mask indicating active neurons
Returns:
Full-sized result
"""
if isinstance(partial_result, (np.ndarray, mx.array)):
# Get shape information
full_size = len(mask)
active_size = np.sum(mask)
if partial_result.ndim == 1 and len(partial_result) == active_size:
# 1D case: expand to full size
full_result = np.zeros(full_size, dtype=partial_result.dtype)
full_result[mask] = partial_result
return full_result
elif partial_result.ndim == 2 and partial_result.shape[0] == active_size:
# 2D case: expand first dimension
full_result = np.zeros((full_size, partial_result.shape[1]), dtype=partial_result.dtype)
full_result[mask] = partial_result
return full_result
# If expansion is not possible or needed, return as is
return partial_result
def create_activity_triggered_network(
network: Any,
trigger_config: Optional[ActivityTrigger] = None,
activation_fn: Optional[Callable] = None
) -> ActivityTriggeredNetwork:
"""
Create an activity-triggered version of a network.
Args:
network: Neural network to wrap
trigger_config: Activity trigger configuration
activation_fn: Optional function to determine active neurons
Returns:
Activity-triggered network
"""
return ActivityTriggeredNetwork(
network=network,
trigger_config=trigger_config,
activation_fn=activation_fn
)
def optimize_computational_graph(
network: Any,
input_examples: List[Any],
compile_full: bool = True
) -> Any:
"""
Optimize the computational graph of a network based on example inputs.
Args:
network: Neural network to optimize
input_examples: Example inputs for optimization
compile_full: Whether to compile the full network
Returns:
Optimized network
"""
# Create activity-triggered network
triggered_network = create_activity_triggered_network(network)
# Pre-compile pathways for example inputs
for example in input_examples:
# Get active neurons for this example
active_neurons = triggered_network._get_active_neurons(example)
# Pre-compile pathway
triggered_network.trigger_manager.get_active_pathway(
active_neurons,
triggered_network._create_network_function(),
force_compile=True
)
# Optionally compile the full network
if compile_full:
full_network_fn = triggered_network._create_network_function()
compiled_full = mx.compile(full_network_fn)
# Store in the pathway cache
triggered_network.trigger_manager.compiled_pathways['full'] = compiled_full
triggered_network.trigger_manager.pathway_usage['full'] = 0
return triggered_network