snow_spike / src /advanced_learning /advanced_network.py
psikosen's picture
Add files using upload-large-folder tool
1e12712 verified
Raw History Blame Contribute Delete
12.6 kB
"""
Advanced Learning Network combining STDP, power-law decay, and Hill functions.
This integrates all advanced learning mechanisms into a cohesive network.
"""
import numpy as np
from typing import List, Dict, Optional, Tuple, NamedTuple
import logging
import time
from ..nlp.sequential import SequentialAdaptiveNetwork
from ..stochastic.integration import StochasticSequentialNetwork
from .stdp import STDPRule, STDPWindow
from .power_law_decay import PowerLawDecay, PowerLawSynapticDecay
from .hill_function import HillFunction, CorroborationNetwork
logger = logging.getLogger("snow_spike.advanced_learning.network")
class LearningConfig(NamedTuple):
"""Configuration for advanced learning mechanisms."""
# STDP parameters
enable_stdp: bool = True
stdp_learning_rate: float = 0.01
stdp_tau_plus: float = 20.0
stdp_tau_minus: float = 20.0
# Power-law decay parameters
enable_power_law: bool = True
power_law_alpha: float = 0.8
power_law_t0: float = 1.0
# Hill function parameters
enable_hill: bool = True
hill_n: float = 2.0
hill_K: float = 0.5
# Stochastic parameters
spike_temperature: float = 0.1
spike_method: str = "stochastic"
class AdvancedLearningNetwork(StochasticSequentialNetwork):
"""
Ultimate network combining all advanced features:
- Stochastic spiking (Phase 2)
- STDP learning (Phase 3)
- Power-law decay (Phase 3)
- Hill function corroboration (Phase 3)
"""
def __init__(self,
layer_sizes: List[int],
config: Optional[LearningConfig] = None,
**kwargs):
"""
Initialize advanced learning network.
Args:
layer_sizes: Neurons per layer
config: Learning configuration
**kwargs: Additional parameters for parent class
"""
if config is None:
config = LearningConfig()
# Initialize stochastic network
super().__init__(
layer_sizes=layer_sizes,
spike_temperature=config.spike_temperature,
spike_method=config.spike_method,
**kwargs
)
self.config = config
self.current_time = 0.0
# Initialize STDP
if config.enable_stdp:
self.stdp_rule = STDPRule(
window=STDPWindow(
tau_plus=config.stdp_tau_plus,
tau_minus=config.stdp_tau_minus,
A_plus=config.stdp_learning_rate,
A_minus=config.stdp_learning_rate
),
learning_rate=1.0
)
else:
self.stdp_rule = None
# Initialize power-law decay
if config.enable_power_law:
self.power_law_decay = PowerLawSynapticDecay(
alpha=config.power_law_alpha,
t0=config.power_law_t0
)
self.memory_traces = PowerLawDecay(
alpha=config.power_law_alpha,
t0=config.power_law_t0
)
else:
self.power_law_decay = None
self.memory_traces = None
# Initialize Hill function corroboration
if config.enable_hill:
self.corroboration_network = CorroborationNetwork(
num_neurons=layer_sizes[-1], # Output layer
hill_n=config.hill_n,
hill_K=config.hill_K
)
else:
self.corroboration_network = None
logger.info(f"Created advanced learning network with config: {config}")
def forward(self, inputs: List[int], **kwargs) -> Tuple:
"""
Enhanced forward pass with all learning mechanisms.
"""
# Get base forward pass with distributions
result = super().forward(inputs, return_distributions=True, **kwargs)
if len(result) == 2:
output_spikes, output_distributions = result
else:
output_spikes = result
output_distributions = None
# Apply STDP if enabled
if self.config.enable_stdp and self.stdp_rule:
self._apply_stdp_updates()
# Apply power-law decay if enabled
if self.config.enable_power_law and self.power_law_decay:
self._apply_power_law_decay()
# Update corroboration signals if enabled
if self.config.enable_hill and self.corroboration_network:
self._update_corroboration(output_spikes)
# Advance time
self.current_time += 1.0
return output_spikes, output_distributions
def _apply_stdp_updates(self):
"""Apply STDP to all synapses based on recent spikes."""
# Record current spikes
for layer_idx, layer in enumerate(self.layers):
for neuron_idx, neuron in enumerate(layer):
if hasattr(neuron, 'spike') and neuron.spike != 0:
# This is a simplified version - in reality you'd track exact timing
neuron_id = layer_idx * 1000 + neuron_idx # Unique ID
if layer_idx == 0:
# Input layer - pre-synaptic
self.stdp_rule.record_spike(neuron_id, self.current_time, is_pre=True)
else:
# Hidden/output layers - post-synaptic
self.stdp_rule.record_spike(neuron_id, self.current_time, is_pre=False)
# Update weights between adjacent layers
for layer_idx in range(len(self.layers) - 1):
curr_layer = self.layers[layer_idx]
next_layer = self.layers[layer_idx + 1]
for i, pre_neuron in enumerate(curr_layer):
for j, post_neuron in enumerate(next_layer):
if j < len(pre_neuron.weights):
pre_id = layer_idx * 1000 + i
post_id = (layer_idx + 1) * 1000 + j
# Compute STDP update
dw = self.stdp_rule.compute_stdp_update(
pre_id, post_id,
pre_neuron.weights[j]
)
# Apply update
pre_neuron.weights[j] += dw
# Clean old spikes
self.stdp_rule.clear_old_spikes(self.current_time)
def _apply_power_law_decay(self):
"""Apply power-law decay to weights and memory traces."""
self.power_law_decay.advance_time(1.0)
# Decay synaptic weights
for layer in self.layers:
for i, neuron in enumerate(layer):
for j in range(len(neuron.weights)):
neuron.weights[j] = self.power_law_decay.update_synapse(
i, j, neuron.weights[j]
)
# Update memory traces
if hasattr(self, 'activity_history'):
for layer_idx, history in enumerate(self.activity_history):
if history:
# Add memory trace for recent activity
trace_id = f"layer_{layer_idx}_t{int(self.current_time)}"
avg_activity = np.mean([abs(s) for s in history[-1]])
self.memory_traces.add_memory_trace(
trace_id, avg_activity, self.current_time
)
def _update_corroboration(self, output_spikes: List[int]):
"""Update corroboration signals based on output spikes."""
for i, spike in enumerate(output_spikes):
if i < self.corroboration_network.num_neurons:
# Convert spike to evidence strength
evidence = abs(spike) * 0.5 # Scale spike to evidence
self.corroboration_network.add_evidence(i, evidence)
# Compute corroboration responses
responses = self.corroboration_network.compute_responses()
# Use corroboration to modulate output layer weights
if responses:
output_layer = self.layers[-1]
for i, neuron in enumerate(output_layer):
if i < len(responses):
# Strengthen weights based on corroboration
modulation = 1.0 + 0.1 * responses[i]
for j in range(len(neuron.weights)):
neuron.weights[j] *= modulation
def get_learning_stats(self) -> Dict[str, float]:
"""Get statistics about learning mechanisms."""
stats = {
"current_time": self.current_time,
"network_entropy": self.get_stochastic_entropy()
}
# STDP stats
if self.stdp_rule:
stats["stdp_spike_count"] = sum(
len(times) for times in self.stdp_rule.pre_spike_times.values()
)
# Power-law stats
if self.memory_traces:
traces = self.memory_traces.update_all_traces(self.current_time)
stats["active_memory_traces"] = len(traces)
stats["avg_trace_strength"] = np.mean(list(traces.values())) if traces else 0
# Corroboration stats
if self.corroboration_network:
responses = self.corroboration_network.compute_responses()
stats["avg_corroboration"] = np.mean(responses) if responses else 0
stats["max_corroboration"] = np.max(responses) if responses else 0
return stats
def upgrade_to_advanced_learning(network: SequentialAdaptiveNetwork,
config: Optional[LearningConfig] = None) -> AdvancedLearningNetwork:
"""
Upgrade existing network to advanced learning.
Args:
network: Existing network
config: Learning configuration
Returns:
AdvancedLearningNetwork with copied weights
"""
if config is None:
config = LearningConfig()
# Get layer sizes properly
layer_sizes = []
if hasattr(network, 'layers') and network.layers:
# First layer input size
layer_sizes.append(network.layers[0].weights.input_size)
# Output size for each layer
for layer in network.layers:
layer_sizes.append(layer.weights.output_size)
else:
# Fallback to default sizes if layers not accessible
layer_sizes = [48, 32, 24]
# Get network attributes with defaults
decay_lambda = getattr(network, 'decay_lambda', 0.01)
growth_rate = getattr(network, 'growth_rate', 0.05)
sequence_memory = getattr(network, 'sequence_memory', 3)
# Create advanced network
advanced = AdvancedLearningNetwork(
layer_sizes=layer_sizes,
config=config,
decay_lambda=decay_lambda,
growth_rate=growth_rate,
sequence_memory=sequence_memory
)
# Copy weights properly
if hasattr(network, 'layers') and network.layers:
for layer_idx, layer in enumerate(network.layers):
if layer_idx < len(advanced.layers):
# Copy weight matrix values
advanced.layers[layer_idx].weights.weight_values = layer.weights.weight_values.copy()
advanced.layers[layer_idx].weights.bias_values = layer.weights.bias_values.copy()
# Copy individual weight parameters
for i in range(layer.weights.output_size):
for j in range(layer.weights.input_size):
if (i < advanced.layers[layer_idx].weights.output_size and
j < advanced.layers[layer_idx].weights.input_size):
advanced.layers[layer_idx].weights.weights[i][j].value = layer.weights.weights[i][j].value
advanced.layers[layer_idx].weights.weights[i][j].growth_rate = layer.weights.weights[i][j].growth_rate
advanced.layers[layer_idx].weights.weights[i][j].decay_lambda = layer.weights.weights[i][j].decay_lambda
# Sync the values
advanced.layers[layer_idx].weights._sync_values()
# Copy activity history
if hasattr(network, 'activity_history'):
advanced.activity_history = [h.copy() for h in network.activity_history]
logger.info("Successfully upgraded to advanced learning network")
return advanced