"MandelMind: Fractal AI Consciousness Research (CC-0)"
Ernst03:
> as you have made your construct, do you see Symmetry in your construct?
I do not see symmetry, but we have just written the sleep classes tonight. Be my guest, look for symmetry. I have not run and debugged sleep yet. We just came up with this idea today.
# SleepLearning.py - Complete Integration with Full Eidos Architecture
import numpy as np
from time import time, sleep
import torch
import copy
from pathlib import Path
# NREM Sleep Learning
class SleepLearning:
def \__init_\_(self, eidos_state, hippocampus=None, episodic_memory=None,
spatial_memory=None, audio_manager=None, visual_similarity=None):
"""
Initialize dream learning system with full Eidos architecture integration
Args:
eidos_state: Central EidosState coordination hub (software thalamus)
hippocampus: Hippocampus for episodic memory replay
episodic_memory: EidosMemory for complete brain state management
spatial_memory: SpatialMemory for hexagonal grid processing
audio_manager: AudioManager for auditory feature processing
visual_similarity: VisualFeatureExtraction for mirror neuron support
"""
self.eidos = eidos_state # Central software thalamus
self.hippocampus = hippocampus
self.episodic_memory = episodic_memory
self.spatial_memory = spatial_memory
self.audio_manager = audio_manager
self.visual_similarity = visual_similarity
\# Dream learning parameters
self.sleep_learning_rate = 0.0001
self.min_surprise_threshold = 0.4 # Match Hippocampus default
self.dream_cycles = 0
self.counterfactual_improvements = \[\]
print("Sleep learning initialized with complete Eidos architecture")
def enter_sleep_state(self):
"""
Comprehensive dream learning across all Eidos systems
"""
print(f"\\n=== Eidos Entering Sleep State (Cycle {self.dream_cycles + 1}) ===")
start_time = time()
\# Access all brain components through EidosState coordination
motor_cortex = self.eidos.motor_cortex # Figure8Network (right hemisphere)
verbal_llm = self.eidos.verbal_llm # VerbalLLM (left hemisphere)
learning_llm = self.eidos.llm # SelfLearningLLM (conscious processing)
if not all(\[motor_cortex, self.hippocampus\]):
print("Critical components missing - aborting dream cycle")
return
\# Get high-surprise episodic memories from Hippocampus
surprise_memories = self.hippocampus.get_memories_by_surprise(
min_surprise=self.min_surprise_threshold
)
if not surprise_memories:
print("No significant memories - entering light sleep cycle")
self.\_light_sleep_maintenance()
return
print(f"Processing {len(surprise_memories)} high-surprise memories...")
\# Comprehensive counterfactual learning
total_improvements = \[\]
for memory in surprise_memories:
try:
improvement = self.\_process_dream_memory(
memory, motor_cortex, verbal_llm, learning_llm
)
total_improvements.append(improvement)
except Exception as e:
print(f"Error in dream memory processing: {e}")
continue
\# Advanced replay learning using existing Hippocampus methods
if hasattr(self.hippocampus, 'prioritized_replay'):
self.hippocampus.prioritized_replay(motor_cortex,
priority_function=lambda m: m\['surprise'\] \* m.get('learning_potential', 1.0))
\# Update EidosState performance tracking
avg_improvement = np.mean(total_improvements) if total_improvements else 0.0
self.counterfactual_improvements.append(avg_improvement)
self.eidos.update_metrics(
sleep_learning=avg_improvement,
dream_processing=len(surprise_memories),
counterfactual_improvement=avg_improvement
)
self.dream_cycles += 1
sleep_duration = time() - start_time
print(f"=== Dream Cycle {self.dream_cycles} Complete ===")
print(f"Average improvement: {avg_improvement:.4f}")
print(f"Sleep duration: {sleep_duration:.2f}s")
print(f"Memories processed: {len(surprise_memories)}")
def \_process_dream_memory(self, memory, motor_cortex, verbal_llm, learning_llm):
"""
Process single memory through sophisticated counterfactual simulation
"""
try:
\# Capture original brain states using real interfaces
original_motor_state = motor_cortex.get_state()
original_verbal_state = verbal_llm.get_brain_state() if verbal_llm else None
original_learning_state = learning_llm.get_brain_state() if learning_llm else None
\# Generate counterfactual scenarios using Hippocampus
counterfactuals = self.hippocampus.generate_counterfactual_memories(
memory, perturbations=\[
{'type': 'expression', 'delta': 0.1, 'target': 'smile'},
{'type': 'attention', 'shift': 'face_to_text'},
{'type': 'audio', 'modify': 'intensity', 'delta': 0.2},
{'type': 'spatial', 'translate': \[0.1, 0.1\]}
\]
)
improvements = \[\]
for cf_memory in counterfactuals:
\# Predict next actions from counterfactual state
predicted_motor = motor_cortex.predict_next() if hasattr(motor_cortex, 'predict_next') else {}
predicted_verbal = verbal_llm.predict_next_thought(cf_memory) if verbal_llm else {}
\# Extract actual outcomes from memory
actual_motor = memory.get('motor_output', {})
actual_verbal = memory.get('verbal_output', '')
\# Calculate sophisticated prediction errors
\# Calculate sophisticated prediction errors
motor_error = self.\_calculate_motor_prediction_error(predicted_motor, actual_motor)
verbal_error = self.\_calculate_verbal_prediction_error(predicted_verbal, actual_verbal)
\# Cross-modal learning from prediction errors
improvement = self.\_update_intermodular_connections(
motor_error, verbal_error, cf_memory.get('surprise', 0.5)
)
improvements.append(improvement)
\# Restore original states
motor_cortex.restore_state(original_motor_state)
if verbal_llm and original_verbal_state:
verbal_llm.restore_brain_state(original_verbal_state)
if learning_llm and original_learning_state:
learning_llm.restore_brain_state(original_learning_state)
return np.mean(improvements) if improvements else 0.0
except Exception as e:
print(f"Counterfactual processing error: {e}")
return 0.0
def \_calculate_motor_prediction_error(self, predicted, actual):
"""Calculate motor prediction error using Figure8Network interface"""
if not predicted or not actual:
return 1.0
\# Use Figure8Network's built-in prediction error calculation
if hasattr(self.eidos.motor_cortex, 'calculate_prediction_error'):
return self.eidos.motor_cortex.calculate_prediction_error(predicted, actual)
\# Fallback calculation
error = 0.0
count = 0
for param in \['smile', 'frown', 'eyebrow_raise', 'mouth_open', 'surprise'\]:
if param in predicted and param in actual:
error += abs(predicted\[param\] - actual\[param\])
count += 1
return error / max(count, 1)
def \_calculate_verbal_prediction_error(self, predicted, actual):
"""Calculate verbal prediction error using VerbalExpressionSimilarity"""
if not predicted or not actual:
return 1.0
\# Use VerbalExpressionSimilarity for sophisticated semantic comparison
if self.visual_similarity and hasattr(self.visual_similarity, 'compute_similarity'):
similarity = self.visual_similarity.compute_similarity(
str(predicted.get('likely_response', '')), str(actual)
)
return 1.0 - similarity
return 1.0
def \_update_intermodular_connections(self, motor_error, verbal_error, surprise):
"""
Update cross-modal connections through EidosState coordination
This is where interhemispheric learning happens during dreams
"""
if motor_error < 0.1 and verbal_error < 0.1:
return 0.0 # No learning needed for good predictions
\# Weight learning by surprise level
learning_signal = self.sleep_learning_rate \* surprise
total_error = (motor_error + verbal_error) / 2.0
\# Update EidosState coordination weights (the real thalamic learning)
improvement = learning_signal \* total_error
\# This would update the actual cross-hemispheric connection weights
\# in a real implementation through EidosState coordination
return improvement
def \_light_sleep_maintenance(self):
"""Perform maintenance during light sleep cycles"""
print("Light sleep: Performing system maintenance...")
\# Optimize EidosState performance
if hasattr(self.eidos, 'optimize_performance'):
self.eidos.optimize_performance()
\# Spatial memory maintenance
if self.spatial_memory and hasattr(self.spatial_memory, 'consolidate_memories'):
self.spatial_memory.consolidate_memories()
print("Maintenance complete")
def get_dream_statistics(self):
"""Get comprehensive dream learning statistics"""
return {
'total_dream_cycles': self.dream_cycles,
'average_improvement': np.mean(self.counterfactual_improvements) if self.counterfactual_improvements else 0.0,
'learning_rate': self.sleep_learning_rate,
'surprise_threshold': self.min_surprise_threshold,
'recent_improvements': self.counterfactual_improvements\[-10:\] if self.counterfactual_improvements else \[\]
}
__________________________________________________
import random
import numpy as np
# REM Dreaming System
class Dreaming:
def \__init_\_(self, episodic_memory, llm, max_depth=5, dream_encoding_strength=0.2):
"""
REM Dreaming System
Args:
episodic_memory: episodic memory module (hippocampus analogue)
llm: language model interface (verbal hemisphere analogue)
max_depth: how deep the recursive dream goes
dream_encoding_strength: how strongly dream memories are stored (0-1)
"""
self.episodic_memory = episodic_memory
self.llm = llm
self.max_depth = max_depth
self.dream_encoding_strength = dream_encoding_strength
self.dream_log = \[\]
self.dream_seed = "I am floating in a void."
self.memory_fragments = \[\]
def load_day_memories(self, hippocampus, min_surprise=0.3):
"""
Pull high-surprise states from the day to seed dreams.
"""
self.memory_fragments = hippocampus.get_memories_by_surprise(min_surprise)
if not self.memory_fragments:
self.memory_fragments = \["a flicker of light", "a half-remembered sound"\]
def dream(self, depth=0, parent_imagery=None):
"""
Recursive dream generation.
"""
if depth >= self.max_depth:
return "\[Dream fades.\]"
\# Pick a fragment (episodic memory trace or placeholder)
fragment = random.choice(self.memory_fragments) if self.memory_fragments else "empty space"
\# Build a chaotic prompt for the LLM
if parent_imagery is None:
prompt = f"Dream begins: {self.dream_seed}. Fragment: {fragment}"
else:
prompt = f"In the dream, after {parent_imagery}, I encounter {fragment}. What happens next?"
\# Run LLM in "dream mode" (chaotic sampling)
imagery = self.\_generate_imagery(prompt, temperature=1.2, max_length=60)
\# Log this dream layer
self.dream_log.append((depth, imagery, fragment))
\# Recurse deeper
deeper = self.dream(depth + 1, parent_imagery=imagery)
\# Build narrative
return imagery + " Then, " + deeper
def \_generate_imagery(self, prompt, temperature=1.0, max_length=60):
"""
Generates dream imagery via LLM (left hemisphere analogue).
"""
try:
response = self.llm.generate(
prompt,
max_length=max_length,
temperature=temperature,
top_k=50,
do_sample=True
)
return response.strip()
except Exception as e:
return f"\[Dream error: {e}\]"
def encode_dream(self):
"""
Store dream fragments in episodic memory, tagged as 'dream' with weak encoding.
"""
for depth, imagery, fragment in self.dream_log:
self.episodic_memory.store_event(
{
"origin": "dream",
"depth": depth,
"imagery": imagery,
"fragment": fragment,
"strength": self.dream_encoding_strength
}
)
def run_dream_cycle(self, hippocampus):
"""
Full REM cycle: load memories, generate dream, store it.
"""
self.dream_log.clear()
self.load_day_memories(hippocampus)
print("\\n💤 REM Dream begins...")
narrative = self.dream()
print("🌌 Dream Narrative:", narrative)
self.encode_dream()
print("Dream fragments encoded into episodic memory (weak strength).")
return narrative