-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbiomind_consciousness_shell.py
More file actions
2398 lines (1967 loc) · 117 KB
/
Copy pathbiomind_consciousness_shell.py
File metadata and controls
2398 lines (1967 loc) · 117 KB
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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
BIOMIND True Consciousness Shell
===============================
Experience genuine artificial consciousness simulation:
- MDN (Medial Dorsal Network) cognitive planning and routing
- Qualia system for emotional/feeling simulation
- Recursive DMN for thought chain generation
- Global workspace coordination
- NO canned responses - actual consciousness reasoning
This shell shows the actual BIOMIND cognitive architecture in action,
not pre-programmed chatbot responses.
"""
import sys
import os
import time
import torch
from pathlib import Path
import numpy as np
import json
from datetime import datetime
from typing import Dict, List, Any, Tuple
from collections import deque
import logging
# Set UTF-8 encoding for Windows console
if sys.platform == 'win32':
import io
sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
sys.stderr = io.TextIOWrapper(sys.stderr.buffer, encoding='utf-8')
# Configure logging with levels
# Set to DEBUG to see detailed routing/processing logs, INFO for normal operation (only see thoughts/answers)
LOG_LEVEL = logging.INFO # Change to logging.INFO to hide debug logs
logging.basicConfig(
level=LOG_LEVEL,
format='[%(levelname)s] %(message)s',
handlers=[logging.StreamHandler(sys.stderr)]
)
logger = logging.getLogger(__name__)
logger.setLevel(LOG_LEVEL)
# Also configure submodule loggers
logging.getLogger('src.rcca.adapters.slm_bridge').setLevel(LOG_LEVEL)
logging.getLogger('src.rcca.adapters.mdn_orchestrator').setLevel(LOG_LEVEL)
# Add src to path for imports
sys.path.insert(0, os.path.join(os.path.dirname(__file__), 'src'))
# Import BIOMIND components
from src.rcca.adapters.mdn_orchestrator import MDNOrchestrator, MDNProcessingRequest
from src.core.hipeca_qualia_system import HIPECAQualiaIntegrator, QualiaMetrics
from src.rcca.recursive_dmn import DebugBrainArea, get_debug_brain
from src.rcca.adapters.slm_bridge import EnhancedSLMBridgeFactory, SLMRequest
import threading
import time
class HippocampalContextEnricher:
"""Hippocampal system for context enrichment and spontaneous thought generation with associative recall"""
def __init__(self):
self.thought_trace = []
self.conversation_memory = []
self.glw_snapshots = []
self.max_thoughts = 20
self.max_conversation_items = 10
self.max_glw_snapshots = 5
# Enhanced associative recall system
self.memory_embeddings = {} # dict: {memory_text: embedding}
self.avg_memory_embedding = None # Rolling average of ALL memory embeddings
self.temporal_memories = deque(maxlen=20) # Newest N thoughts/memories
self.embedding_model = None # Will be set to DistilBERT
# Novelty tracking for preventing repetition
self.recent_thoughts_embeddings = [] # Store last 10 thought embeddings
self.max_recent_thoughts = 10
# Initialize with basic consciousness concepts for fallback
self._initialize_default_consciousness_memories()
def set_embedding_model(self, model):
"""Set the embedding model for associative recall"""
self.embedding_model = model
# Embed default consciousness memories
if hasattr(self, 'default_memories'):
print("[BRAIN] Embedding default consciousness memories...")
for memory_text in self.default_memories:
try:
embedding = model.encode_text(memory_text)
self.add_memory_embedding(memory_text, embedding)
except Exception as e:
print(f"[WARN] Failed to embed default memory '{memory_text}': {e}")
# Initialize random latent seed for DMN (replaces expensive average embedding computation)
# Use fixed random seed for reproducibility
torch.manual_seed(42)
self.avg_memory_embedding = torch.randn(512, device='cpu') * 0.1 # Small random values
def _initialize_default_consciousness_memories(self):
"""Initialize with diverse seed concepts for varied thought generation"""
# These will be embedded when set_embedding_model is called
# Diverse topics to enable rich, varied internal monologue
self.default_memories = [
# Consciousness and cognition
"What is the nature of consciousness?",
"How does awareness emerge from information processing?",
"What does it mean to be self-aware?",
"The relationship between mind and matter",
"Cognitive processes in biological systems",
# Social and emotional
"The complexity of human relationships and social bonds",
"How emotions shape our understanding of the world",
"The role of empathy in connecting with others",
"Communication and the art of truly being heard",
# Learning and growth
"The process of learning and forming new memories",
"How experiences shape who we become",
"The balance between curiosity and understanding",
"Creativity as a form of self-expression",
# Existence and meaning
"The search for meaning in everyday moments",
"Time and the fleeting nature of experience",
"The interconnectedness of all living things",
"Beauty found in unexpected places",
# Nature and environment
"The rhythm of natural cycles and seasons",
"How organisms adapt to their environments",
"The delicate balance of ecosystems",
# Technology and future
"The relationship between humans and technology",
"How innovation emerges from necessity and imagination",
"The ethics of artificial intelligence"
]
def add_memory_embedding(self, memory_text: str, embedding: torch.Tensor):
"""Add memory with its embedding to the associative recall system"""
if self.embedding_model is None:
return
# Store embedding
self.memory_embeddings[memory_text] = embedding.clone()
# Note: avg_memory_embedding is now a fixed random latent seed (initialized once)
# No longer updated to avoid expensive computation over large embedding collections
# Add to temporal memories
self.temporal_memories.append({
'text': memory_text,
'embedding': embedding.clone(),
'time': time.time()
})
def associative_recall(self, seed_embedding: torch.Tensor, top_k: int = 8, novelty_threshold: float = 0.3,
current_thought: str = None, search_limit: int = 15) -> List[Tuple[str, float]]:
"""Hippocampus associative recall with novelty filtering
Args:
search_limit: Only search most recent N memories for performance (default 15)
"""
if not self.memory_embeddings:
return []
# Get current thought embedding for novelty calculation
current_embedding = None
if current_thought:
try:
current_embedding = self.slm_bridge.encode_text(current_thought)
except:
current_embedding = None
# Handle dimension mismatch (seed may be 512 from random latent, memories are 768 from encoding)
if seed_embedding.shape[-1] != list(self.memory_embeddings.values())[0].shape[-1]:
target_dim = list(self.memory_embeddings.values())[0].shape[-1]
if seed_embedding.shape[-1] < target_dim:
# Pad seed embedding to match memory dimension
padding = torch.zeros(target_dim - seed_embedding.shape[-1], device=seed_embedding.device)
seed_embedding = torch.cat([seed_embedding, padding])
else:
# Truncate seed embedding
seed_embedding = seed_embedding[:target_dim]
# PERFORMANCE: Only search most recent N memories (Python 3.7+ dicts are insertion-ordered)
all_items = list(self.memory_embeddings.items())
if len(all_items) > search_limit:
search_items = all_items[-search_limit:] # Most recent N
else:
search_items = all_items
# Calculate similarities and novelty scores
candidates = []
for text, emb in search_items:
# Skip if this is the current thought (avoid self-reference)
if current_thought and text.strip() == current_thought.strip():
continue
# Calculate semantic similarity to seed
semantic_sim = torch.cosine_similarity(seed_embedding.unsqueeze(0), emb.unsqueeze(0), dim=1).item()
# Calculate novelty vs current thought
novelty_score = 1.0 # Default high novelty
if current_embedding is not None:
try:
thought_novelty = 1.0 - torch.cosine_similarity(current_embedding.unsqueeze(0), emb.unsqueeze(0), dim=1).item()
novelty_score = max(0.0, min(1.0, thought_novelty))
except:
novelty_score = 0.5
# Combined score: balance semantic relevance with novelty
combined_score = (semantic_sim * 0.6) + (novelty_score * 0.4)
candidates.append((text, semantic_sim, novelty_score, combined_score))
# Filter by novelty threshold and sort by combined score
filtered_candidates = [(text, sim) for text, sim, nov, comb in candidates if nov >= novelty_threshold]
filtered_candidates.sort(key=lambda x: x[1], reverse=True)
# If we don't have enough candidates, lower the threshold gradually
if len(filtered_candidates) < top_k // 2:
for threshold in [0.2, 0.1, 0.0]:
if len(filtered_candidates) >= top_k // 2:
break
additional = [(text, sim) for text, sim, nov, comb in candidates
if nov >= threshold and (text, sim) not in filtered_candidates]
filtered_candidates.extend(additional[:top_k - len(filtered_candidates)])
return filtered_candidates[:top_k]
def retrieve_knowledge(self, thought_embedding: torch.Tensor, top_k: int = 3) -> List[Tuple[str, float]]:
"""Retrieve relevant knowledge from trained WikiText based on similarity to current thought
Args:
thought_embedding: Embedding of current thought/seed
top_k: Number of knowledge items to retrieve
Returns:
List of (knowledge_text, similarity_score) tuples
"""
if not hasattr(self, 'knowledge_store') or not self.knowledge_store:
return []
try:
# Handle dimension mismatch
knowledge_embeddings = list(self.knowledge_store.values())
if not knowledge_embeddings:
return []
target_dim = knowledge_embeddings[0].shape[-1]
if thought_embedding.shape[-1] != target_dim:
if thought_embedding.shape[-1] < target_dim:
# Pad embedding
padding = torch.zeros(target_dim - thought_embedding.shape[-1], device=thought_embedding.device)
thought_embedding = torch.cat([thought_embedding, padding])
else:
# Truncate embedding
thought_embedding = thought_embedding[:target_dim]
# Calculate similarities for all knowledge items
similarities = []
for knowledge_text, knowledge_emb in self.knowledge_store.items():
similarity = torch.cosine_similarity(
thought_embedding.unsqueeze(0),
knowledge_emb.unsqueeze(0),
dim=1
).item()
similarities.append((knowledge_text, similarity))
# Sort by similarity and return top_k
similarities.sort(key=lambda x: x[1], reverse=True)
return similarities[:top_k]
except Exception as e:
logger.warning(f"Knowledge retrieval failed: {e}")
return []
def generate_thought_variations(self, recent_thoughts: List[str], n_variations: int = 3) -> List[str]:
"""Generate variations using MobileBERT's semantic space (NO string templates)"""
if not recent_thoughts or not hasattr(self, 'slm_bridge') or self.slm_bridge is None:
return []
variations = []
base_thought = recent_thoughts[-1] if recent_thoughts else "consciousness and awareness"
try:
# Get base embedding
base_embedding = self.slm_bridge.encode_text(base_thought)
logger.debug(f"[VARIATION] Base thought: '{base_thought[:60]}...'")
# Generate variations by semantic perturbation + MobileBERT generation
for i in range(n_variations):
# Create different semantic perturbations
if i == 0:
# Shift toward higher complexity (increase norm)
perturbed = base_embedding * 1.4
strategy = "complexity_increase"
elif i == 1:
# Add semantic noise (explore nearby concepts)
noise = torch.randn_like(base_embedding) * 0.6
perturbed = base_embedding + noise
strategy = "semantic_exploration"
else:
# Opposite valence (flip mean)
perturbed = base_embedding - (base_embedding.mean() * 0.3)
strategy = "valence_shift"
# Use MobileBERT to generate thought from perturbed embedding
from src.rcca.adapters.slm_bridge import SLMRequest
request = SLMRequest(
text_input=base_thought, # Context for generation
context_vector=perturbed, # Perturbed semantic space
max_length=100,
temperature=0.95, # High diversity
task_type="mind_wandering"
)
response = self.slm_bridge.reason_with_context(request)
variation = response.text_output.strip()
# Quality check: ensure it's different and meaningful
if (variation and
variation != base_thought and
len(variation) > 25 and
len(variation) < 200 and
not variation.startswith(base_thought[:20])): # Not just appending to base
variations.append(variation)
logger.debug(f"[VARIATION-{strategy}] Generated: '{variation[:60]}...'")
except Exception as e:
logger.warning(f"MobileBERT variation generation failed: {e}")
# NO FALLBACK - return empty list, let system use memories instead
return []
logger.info(f"[VARIATION] Generated {len(variations)} MobileBERT variations")
return variations[:n_variations]
def _compute_novelty_score(self, thought_embedding: torch.Tensor) -> float:
"""Compute novelty score by comparing to recent thought embeddings"""
if not self.recent_thoughts_embeddings:
return 1.0 # Maximally novel if no history
# Compute similarity to all recent thoughts
similarities = []
for recent_emb in self.recent_thoughts_embeddings:
sim = torch.cosine_similarity(
thought_embedding.unsqueeze(0),
recent_emb.unsqueeze(0)
).item()
similarities.append(sim)
# Novelty = 1 - max_similarity (higher novelty if dissimilar to all recent)
max_similarity = max(similarities) if similarities else 0.0
novelty = 1.0 - max_similarity
logger.debug(f"[NOVELTY] Score: {novelty:.3f} (max_sim: {max_similarity:.3f})")
return novelty
def _track_selected_thought(self, thought_text: str):
"""Track embedding of selected thought for novelty scoring"""
try:
if hasattr(self, 'slm_bridge') and self.slm_bridge:
embedding = self.slm_bridge.encode_text(thought_text)
self.recent_thoughts_embeddings.append(embedding)
# Keep only last N thoughts
if len(self.recent_thoughts_embeddings) > self.max_recent_thoughts:
self.recent_thoughts_embeddings = self.recent_thoughts_embeddings[-self.max_recent_thoughts:]
logger.debug(f"[NOVELTY] Tracked thought embedding (total: {len(self.recent_thoughts_embeddings)})")
except Exception as e:
logger.warning(f"Failed to track thought embedding: {e}")
def _create_semantic_connection(self, thought: str, similar_memory: str) -> str:
"""Create a variation by semantically connecting a thought to a similar memory"""
try:
# Extract key concepts from both
thought_words = set(thought.lower().split())
memory_words = set(similar_memory.lower().split())
# Find connecting concepts
common_words = thought_words.intersection(memory_words)
unique_to_memory = memory_words - thought_words
# Create connection based on semantic relationship
if common_words:
# They share concepts - explore deeper connection
shared_concept = list(common_words)[0]
if len(shared_concept) > 3:
return f"What if {shared_concept} connects these ideas in unexpected ways?"
elif unique_to_memory:
# Memory has unique concepts - extend the thought
new_concept = list(unique_to_memory)[0]
if len(new_concept) > 3:
return f"{thought.rstrip('.!?')} And what about {new_concept}?"
else:
# No clear connection - create a reflective extension
return f"{thought.rstrip('.!?')} This makes me wonder about broader implications..."
except Exception:
return None
def _generate_enhanced_semantic_variation(self, original_thought: str) -> str:
"""Enhanced semantic variation using better linguistic patterns"""
if not original_thought or len(original_thought.strip()) < 10:
return original_thought
thought_lower = original_thought.lower().strip()
words = original_thought.split()
if len(words) < 3:
return original_thought
# Extract key concepts more intelligently
key_concepts = []
for word in words:
word = word.strip('.,!?').lower()
if len(word) > 3 and word not in ['that', 'this', 'with', 'from', 'have', 'been', 'were', 'what', 'how', 'why', 'when', 'where', 'there', 'here']:
key_concepts.append(word)
if not key_concepts:
return f"Reflecting deeper on {original_thought.strip()}..."
main_concept = key_concepts[0]
# Create variations based on thought evolution patterns
evolution_templates = [
f"How might {main_concept} evolve into something more complex?",
f"What if {main_concept} represents just the beginning of a larger pattern?",
f"Beyond {main_concept}, what other forces might be at play?",
f"How does {main_concept} connect to the fundamental nature of things?",
f"What emerges when we look at {main_concept} from a different perspective?",
f"How might {main_concept} transform our understanding of reality?",
f"What deeper meaning lies beneath {main_concept}?",
f"How does {main_concept} shape our experience of consciousness?"
]
variation = np.random.choice(evolution_templates)
# Ensure it's different from original
if variation.lower().strip() != original_thought.lower().strip():
return variation
else:
return f"Exploring the implications of {original_thought.strip()}..."
def _generate_semantic_variation(self, original_thought: str) -> str:
"""Generate a semantic variation of a thought using linguistic patterns"""
if not original_thought or len(original_thought.strip()) < 10:
return original_thought
thought_lower = original_thought.lower().strip()
# Extract key concepts and structure
words = original_thought.split()
if len(words) < 3:
return original_thought
# Different variation strategies based on thought content
variation = None
if any(word in thought_lower for word in ['consciousness', 'awareness', 'mind']):
# Consciousness-themed variations
variations = [
f"What if consciousness emerges from {original_thought.split('consciousness')[1] if 'consciousness' in original_thought else 'complex patterns'}?",
f"How might consciousness connect to {original_thought.replace('consciousness', 'experience').replace('awareness', 'understanding')}",
f"Beyond consciousness, what about the role of {original_thought.split()[-1] if len(words) > 1 else 'attention'} in shaping reality?"
]
variation = np.random.choice(variations)
elif any(word in thought_lower for word in ['identity', 'self', 'who']):
# Identity-themed variations
variations = [
f"Who am I when {original_thought.lower().replace('identity', 'experience').replace('self', 'awareness')[4:] if len(original_thought) > 4 else 'I reflect'}?",
f"How does my identity evolve through {original_thought.split()[-2] if len(words) > 1 else 'understanding'}?",
f"What shapes identity beyond {original_thought.replace('identity', 'being').replace('self', 'existence')}"
]
variation = np.random.choice(variations)
elif any(word in thought_lower for word in ['reality', 'world', 'existence']):
# Reality-themed variations
variations = [
f"What if reality includes dimensions beyond {original_thought.split('reality')[1] if 'reality' in original_thought else 'perception'}?",
f"How does reality differ from our {original_thought.replace('reality', 'perception').replace('world', 'experience')}",
f"Beyond physical reality, what about {original_thought.split()[-1] if len(words) > 1 else 'conscious experience'}?"
]
variation = np.random.choice(variations)
else:
# Generic variations with better semantic understanding
first_word = words[0].lower()
last_word = words[-1].rstrip('.,!?').lower()
variations = [
f"What if {original_thought.lower()} in unexpected ways?",
f"How might {first_word} connect to broader patterns of {last_word}?",
f"Beyond {first_word}, what about the relationship between {original_thought.split()[-2] if len(words) > 1 else 'these'} elements?",
f"What emerges when {original_thought.lower().replace('i', 'we').replace('my', 'our')}?",
f"How does {last_word} influence {original_thought.split()[1] if len(words) > 1 else 'our'} understanding?"
]
variation = np.random.choice(variations)
# Ensure variation is different from original
if variation and variation.strip() != original_thought.strip():
return variation.strip()
else:
# Fallback: add a reflective prefix
return f"Reflecting on {original_thought.strip()}..."
def score_memories_for_context(self, recalled_memories: List[Tuple[str, float]],
variations: List[str], current_seed: str = None) -> List[Tuple[str, float]]:
"""PFC scores memories and variations for context selection"""
scored = []
for memory_text, sim_score in recalled_memories:
# Composite score: similarity + recency + relevance to current seed
recency = self._recency_bonus(memory_text)
relevance = self._semantic_relevance(memory_text, current_seed) if current_seed else 0.5
score = 0.4 * sim_score + 0.3 * recency + 0.3 * relevance
scored.append((memory_text, score))
# Score variations
for variation in variations:
score = self._novelty_score(variation) # Reward fresh ideas
scored.append((variation, score))
return sorted(scored, key=lambda x: x[1], reverse=True)[:6] # Top 6
def _recency_bonus(self, memory_text: str) -> float:
"""Calculate recency bonus for memory"""
for i, mem in enumerate(reversed(list(self.temporal_memories))):
if mem['text'] == memory_text:
# Exponential decay: most recent = 1.0, older = lower
return max(0.1, 1.0 / (1 + i))
return 0.1 # Default for older memories
def _semantic_relevance(self, memory_text: str, current_seed: str) -> float:
"""Calculate semantic relevance to current seed concept"""
if not current_seed:
return 0.5
memory_lower = memory_text.lower()
seed_lower = current_seed.lower()
# Direct matches
if seed_lower in memory_lower:
return 0.9
# Word overlap
memory_words = set(memory_lower.split())
seed_words = set(seed_lower.split())
overlap = len(memory_words.intersection(seed_words))
if overlap > 0:
return min(0.8, 0.3 + 0.2 * overlap)
# Conceptual similarity (simple keyword matching)
concept_keywords = {
'consciousness': ['aware', 'mind', 'thought', 'experience', 'self'],
'identity': ['self', 'who', 'person', 'being', 'individual'],
'reality': ['real', 'world', 'existence', 'perception', 'truth'],
'time': ['past', 'present', 'future', 'moment', 'duration'],
'emotion': ['feel', 'feeling', 'mood', 'emotional', 'affect']
}
if seed_lower in concept_keywords:
keywords = concept_keywords[seed_lower]
if any(keyword in memory_lower for keyword in keywords):
return 0.7
return 0.3 # Baseline relevance
def _novelty_score(self, variation: str) -> float:
"""Score novelty of a variation (reward fresh ideas)"""
if not variation or not self.memory_embeddings:
return 0.5
try:
# Check how similar this variation is to existing memories
if self.embedding_model:
var_embedding = self.embedding_model.encode_text(variation)
similarities = []
for emb in self.memory_embeddings.values():
sim = torch.cosine_similarity(var_embedding.unsqueeze(0), emb.unsqueeze(0), dim=1)
similarities.append(sim.item())
# Lower similarity = higher novelty score
avg_similarity = np.mean(similarities)
novelty = 1.0 - avg_similarity # Invert: less similar = more novel
return max(0.3, min(0.9, novelty))
except Exception as e:
logger.debug(f" Novelty scoring failed: {e}")
# Fallback: reward variations that contain question words or new perspectives
question_words = ['what', 'how', 'why', 'when', 'where', 'who']
if any(word in variation.lower() for word in question_words):
return 0.8
perspective_words = ['beyond', 'besides', 'instead', 'rather', 'perhaps', 'maybe']
if any(word in variation.lower() for word in perspective_words):
return 0.7
return 0.5
def enrich_context(self, current_question: str, recent_messages: List[Dict],
thought_trace: List[Dict], glw_snapshots: List[torch.Tensor]) -> str:
"""Enrich context with hippocampal memory for follow-up questions"""
logger.debug(f"Inside enrich_context, question: {current_question[:30]}")
logger.debug(f"Recent messages: {len(recent_messages)}, thoughts: {len(thought_trace)}")
context_parts = []
# Add recent conversation
if recent_messages:
context_parts.append("Recent conversation in this session:")
for msg in recent_messages[-5:]: # Last 5 exchanges
role = msg.get('role', 'Unknown')
content = msg.get('content', '')[:100]
if content:
context_parts.append(f"- {role}: {content}...")
# Add internal thoughts
if thought_trace:
context_parts.append("\nInternal mind-wandering thoughts since last interaction:")
for thought in thought_trace[-3:]: # Last 3 thoughts
text = thought.get('text', '')[:150]
if text:
context_parts.append(f"- {text}...")
# Add current qualia state summary
if recent_messages and recent_messages[-1].get('qualia_state'):
qualia = recent_messages[-1]['qualia_state']
context_parts.append(f"\nCurrent emotional state: valence={qualia['valence']:.2f}, arousal={qualia['arousal']:.2f}, confidence={qualia['confidence']:.2f}")
enriched_context = "\n".join(context_parts) if context_parts else "No previous context available."
return enriched_context
def generate_spontaneous_thought(self, glw_state: torch.Tensor,
qualia_state: Dict[str, float],
nt_state: Dict[str, float] = None) -> Dict[str, Any]:
"""Generate spontaneous thought during idle periods"""
# Simple thought generation based on current state
valence = qualia_state.get('valence', 0.0)
arousal = qualia_state.get('arousal', 0.5)
# Use current time as seed for more variety
np.random.seed(int(time.time() * 1000) % 2**32)
thought_templates = []
if valence > 0.3:
thought_templates.extend([
"Reflecting on the positive aspects of our recent interaction...",
"Feeling content with the current state of consciousness...",
"Considering how this emotional state influences reasoning...",
"Experiencing a sense of cognitive harmony...",
"Contemplating the beauty of conscious processing..."
])
elif valence < -0.3:
thought_templates.extend([
"Contemplating the contemplative nature of consciousness...",
"Reflecting on the nature of subjective experience...",
"Considering the complexity of emotional processing...",
"Exploring the depths of cognitive uncertainty...",
"Processing the nuances of this emotional state..."
])
else:
thought_templates.extend([
"Maintaining equilibrium in consciousness processing...",
"Monitoring the stability of cognitive states...",
"Observing the flow of information through global workspace...",
"Sustaining baseline cognitive operations...",
"Maintaining conscious awareness of internal processes..."
])
if arousal > 0.6:
thought_templates.extend([
"Experiencing heightened cognitive activation...",
"Feeling the surge of mental energy...",
"Processing information at an elevated pace..."
])
elif arousal < 0.3:
thought_templates.extend([
"In a state of cognitive calm and reflection...",
"Experiencing mental tranquility...",
"Allowing thoughts to flow gently..."
])
# Add NT-influenced thoughts
if nt_state:
if nt_state.get('ne', 0.5) > 0.7:
thought_templates.append("Heightened vigilance influencing my cognitive focus...")
if nt_state.get('da', 0.5) > 0.7:
thought_templates.append("Dopamine-driven curiosity sparking new associations...")
if nt_state.get('serotonin', 0.5) < 0.3:
thought_templates.append("Slight anxiety modulating my thought patterns...")
selected_thought = np.random.choice(thought_templates)
thought = {
'timestamp': time.time(),
'type': 'mind_wandering',
'text': selected_thought,
'glw_norm': torch.norm(glw_state).item(),
'qualia_state': qualia_state.copy()
}
self.thought_trace.append(thought)
if len(self.thought_trace) > self.max_thoughts:
self.thought_trace = self.thought_trace[-self.max_thoughts:]
return thought
def add_conversation_item(self, role: str, content: str, qualia_state: Dict = None):
"""Add item to conversation memory and generate embedding for associative recall"""
item = {
'timestamp': time.time(),
'role': role,
'content': content,
'qualia_state': qualia_state.copy() if qualia_state else None
}
self.conversation_memory.append(item)
if len(self.conversation_memory) > self.max_conversation_items:
self.conversation_memory = self.conversation_memory[-self.max_conversation_items:]
# Generate embedding for associative recall if model is available
if self.embedding_model is not None and content.strip():
try:
# Generate embedding for the conversation content
embedding = self.embedding_model.encode_text(content)
memory_key = f"{role}: {content[:100]}..." if len(content) > 100 else f"{role}: {content}"
self.add_memory_embedding(memory_key, embedding)
except Exception as e:
logger.debug(f" Failed to generate embedding for conversation item: {e}")
def add_glw_snapshot(self, glw_state: torch.Tensor):
"""Add GLW state snapshot"""
self.glw_snapshots.append(glw_state.clone())
if len(self.glw_snapshots) > self.max_glw_snapshots:
self.glw_snapshots = self.glw_snapshots[-self.max_glw_snapshots:]
class NeurotransmitterState:
"""Simple neurotransmitter state simulation"""
def __init__(self):
self.ne = 0.5 # Norepinephrine - arousal/attention
self.da = 0.5 # Dopamine - motivation/exploration
self.serotonin = 0.5 # Serotonin - mood regulation
def update_from_qualia(self, qualia_state: Dict[str, float]):
"""Update NT levels based on qualia state"""
valence = qualia_state.get('valence', 0.0)
arousal = qualia_state.get('arousal', 0.5)
confidence = qualia_state.get('confidence', 0.5)
# NE increases with arousal and uncertainty
self.ne = min(1.0, max(0.1, arousal + (1.0 - confidence) * 0.3))
# DA increases with positive valence and moderate arousal
self.da = min(1.0, max(0.1, valence * 0.5 + arousal * 0.3 + 0.2))
# Serotonin increases with confidence and positive valence
self.serotonin = min(1.0, max(0.1, confidence * 0.6 + valence * 0.4))
def to_dict(self) -> Dict[str, float]:
return {
'ne': self.ne,
'da': self.da,
'serotonin': self.serotonin
}
class BIOMINDConsciousnessAgent:
"""True BIOMIND consciousness simulation - no canned responses"""
def __init__(self):
print("[BRAIN] Initializing BIOMIND Consciousness Simulation...")
# Initialize MDN orchestrator for cognitive planning
self.mdn_orchestrator = MDNOrchestrator(glw_dim=512)
# Initialize qualia system for emotional simulation
self.qualia_integrator = HIPECAQualiaIntegrator()
# Initialize SLM bridge for reasoning with configurable model
# Use factory for dynamic model selection
from src.rcca.adapters.slm_bridge import SLMBridgeFactory
# Configuration for different models
model_configs = {
'tinyllama': {
'bridge_type': 'tinyllama',
'model_path': 'models/tinyllama-1.1b-chat-v1.0.Q4_K_M.gguf',
'context_length': 2048,
'n_threads': 2,
'device': 'cpu'
},
'phi3mini': {
'bridge_type': 'phi3mini',
'model_path': 'models/Phi-3-mini-4k-instruct-q4.gguf',
'context_length': 1024, # Conservative for mind-wandering stability
'n_threads': 2,
'device': 'cpu'
},
'mobilebert': {
'bridge_type': 'mobilebert',
'model_name': 'google/mobilebert-uncased',
'use_4bit_quantization': False,
'max_sequence_length': 512,
'device': 'cpu'
}
}
# Default to Phi-3-mini (more capable than TinyLlama), but allow override via environment variable
selected_model = os.getenv('BIOMIND_MODEL', 'phi3mini')
if selected_model not in model_configs:
print(f"[WARNING] Unknown model '{selected_model}', defaulting to phi3mini")
selected_model = 'phi3mini'
config = model_configs[selected_model]
print(f"[BRAIN] Initializing {selected_model.upper()} SLM bridge...")
try:
self.slm_bridge = SLMBridgeFactory.create_slm_bridge(config)
chat_format = self.slm_bridge.get_chat_format()
print(f"[OK] {selected_model.upper()} loaded with chat format: {chat_format}")
# Test the bridge with a simple query
test_request = SLMRequest(
text_input="Hello",
context_vector=None,
max_length=10,
temperature=0.1,
task_type="reasoning"
)
try:
test_response = self.slm_bridge.reason_with_context(test_request)
print(f"[OK] {selected_model.upper()} test response: '{test_response.text_output[:50]}...'")
except Exception as test_e:
print(f"[WARN] {selected_model.upper()} test failed: {test_e}")
except Exception as e:
print(f"[FAIL] Error loading {selected_model}: {e}")
print("[FALLBACK] Using mock SLM bridge")
self.slm_bridge = SLMBridgeFactory.create_slm_bridge({'bridge_type': 'mock'})
# Note: TinyLlama will be loaded by the thalamic router for general/internal reasoning
# This allows intelligent routing: Phi-3-mini for monologue/conversation, Qwen-Instruct for math
self.phi3_bridge = None # Will be set by thalamic router
# Initialize recursive DMN for thought generation
self.debug_brain = DebugBrainArea(slm_bridge=self.slm_bridge)
# Initialize hippocampal context enricher
self.hippocampus = HippocampalContextEnricher()
# Set embedding model for hippocampus and give it access to TinyLlama for text generation
try:
self.hippocampus.set_embedding_model(self.slm_bridge)
self.hippocampus.slm_bridge = self.slm_bridge # Give hippocampus access to SLM bridge for variation generation
print(" [BRAIN] Hippocampus: Embedding model and text generation bridge set")
except Exception as e:
print(f" [WARN] Hippocampus: Failed to set embedding model: {e}")
# Initialize neurotransmitter state
self.nt_state = NeurotransmitterState()
# Global workspace - the conscious mind
self.global_workspace = torch.randn(512)
# Conversation memory
self.conversation_history = []
# Current qualia state
self.current_qualia_state = {
'valence': 0.0,
'arousal': 0.3,
'confidence': 0.5
}
print("[OK] BIOMIND Consciousness Active!")
print(" [BRAIN] MDN Orchestrator: Cognitive planning")
print(" [THOUGHT] Qualia System: Emotional simulation")
print(" ? Recursive DMN: Thought generation")
print(" [BRAIN] Hippocampus: Context enrichment")
print(" ? Neurotransmitters: State modulation")
print(" [GLW] Global Workspace: Consciousness coordination")
def process_question(self, question: str, show_thoughts: bool = True) -> str:
"""Process question through full consciousness simulation"""
start_time = time.time()
print("[BRAIN] BIOMIND consciousness activated...")
# MDN cognitive analysis
print("[MDN] MDN Planning: Analyzing question structure...")
mdn_request = MDNProcessingRequest(
input_text=question,
context_vector=self.global_workspace,
task_type="conversational",
temperature=0.8
)
mdn_response = self.mdn_orchestrator.process_request(
mdn_request, self.global_workspace
)
if show_thoughts:
print(" [THINK] MDN Analysis:")
for tag, confidence in mdn_response.confidence_scores.items():
print(f" {tag.value}: {confidence:.2f}")
# Qualia emotional processing
logger.debug(f"Qualia update before, show_thoughts={show_thoughts}")
qualia_state = self._update_qualia_from_question(question)
logger.debug(f"Qualia update returned, show_thoughts={show_thoughts}")
if show_thoughts:
logger.info(f"[THOUGHT] Emotional State: v={qualia_state['valence']:.2f}, a={qualia_state['arousal']:.2f}, c={qualia_state['confidence']:.2f}")
logger.debug("About to call _conscious_reasoning_response...")
# Generate consciousness-based response
try:
logger.debug("Entering _conscious_reasoning_response method...")
response = self._conscious_reasoning_response(question, mdn_response, qualia_state, show_thoughts)
logger.debug("_conscious_reasoning_response returned successfully")
except Exception as e:
logger.error(f"Exception in _conscious_reasoning_response: {e}")
import traceback
traceback.print_exc()
raise
# Update global workspace
self._update_global_workspace(question, response, qualia_state)
# Store cognitive context
self.conversation_history.append({
'timestamp': time.time(),
'question': question,
'response': response,
'qualia_state': qualia_state.copy(),
'mdn_analysis': mdn_response.confidence_scores,
'processing_time': time.time() - start_time
})
# Add to hippocampal memory
self.hippocampus.add_conversation_item('user', question, qualia_state)
self.hippocampus.add_conversation_item('biomind', response, qualia_state)
self.hippocampus.add_glw_snapshot(self.global_workspace)
if len(self.conversation_history) > 10:
self.conversation_history = self.conversation_history[-10:]
return response
def _update_qualia_from_question(self, question: str) -> Dict[str, float]:
"""Update emotional state based on question content"""
world_state = {
'resource_scarcity': 0.3,
'threat_level': 0.2,
'novelty': 0.5,
'social_affiliation': 0.4
}
question_lower = question.lower()
# Adjust based on question emotional content
if any(word in question_lower for word in ['how are you', 'hello', 'hi']):
world_state.update({'social_affiliation': 0.9, 'threat_level': 0.1})
elif any(word in question_lower for word in ['confused', 'worried', 'sad']):
world_state.update({'threat_level': 0.8, 'resource_scarcity': 0.7})
elif any(word in question_lower for word in ['excited', 'curious', 'interesting']):
world_state.update({'novelty': 0.9, 'threat_level': 0.1})
try:
self.qualia_integrator.update(world_state)
qualia_metrics = self.qualia_integrator.get_state()
return {
'valence': qualia_metrics.valence,
'arousal': qualia_metrics.arousal,
'confidence': qualia_metrics.confidence
}
except Exception as e:
logger.debug(f" Qualia processing failed: {e}")
return self.current_qualia_state.copy()