chip-brain 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. chip_brain-1.0.0/LICENSE +21 -0
  2. chip_brain-1.0.0/PKG-INFO +248 -0
  3. chip_brain-1.0.0/README.md +218 -0
  4. chip_brain-1.0.0/amygdala/__init__.py +7 -0
  5. chip_brain-1.0.0/amygdala/affective_forecast.py +154 -0
  6. chip_brain-1.0.0/amygdala/arousal_modulator.py +92 -0
  7. chip_brain-1.0.0/amygdala/emotional_core.py +199 -0
  8. chip_brain-1.0.0/amygdala/emotional_memory.py +147 -0
  9. chip_brain-1.0.0/amygdala/fear_assessment.py +123 -0
  10. chip_brain-1.0.0/amygdala/habituation.py +152 -0
  11. chip_brain-1.0.0/brain.py +983 -0
  12. chip_brain-1.0.0/brainstem/__init__.py +8 -0
  13. chip_brain-1.0.0/brainstem/circadian.py +168 -0
  14. chip_brain-1.0.0/brainstem/cryostasis.py +268 -0
  15. chip_brain-1.0.0/brainstem/device.py +112 -0
  16. chip_brain-1.0.0/brainstem/forgetting_prevention.py +185 -0
  17. chip_brain-1.0.0/brainstem/gradient_clipper.py +102 -0
  18. chip_brain-1.0.0/brainstem/health_monitor.py +156 -0
  19. chip_brain-1.0.0/brainstem/online_trainer.py +358 -0
  20. chip_brain-1.0.0/brainstem/running_stats.py +78 -0
  21. chip_brain-1.0.0/brainstem/scheduler.py +140 -0
  22. chip_brain-1.0.0/cerebellum/__init__.py +7 -0
  23. chip_brain-1.0.0/cerebellum/action_smoother.py +111 -0
  24. chip_brain-1.0.0/cerebellum/emotional_contagion.py +235 -0
  25. chip_brain-1.0.0/cerebellum/skill_library.py +147 -0
  26. chip_brain-1.0.0/cerebellum/swarm_coordinator.py +150 -0
  27. chip_brain-1.0.0/cerebrum/__init__.py +7 -0
  28. chip_brain-1.0.0/cerebrum/attention_query.py +145 -0
  29. chip_brain-1.0.0/cerebrum/causal_engine.py +445 -0
  30. chip_brain-1.0.0/cerebrum/chip_policy.py +240 -0
  31. chip_brain-1.0.0/cerebrum/concept_grounding.py +138 -0
  32. chip_brain-1.0.0/cerebrum/goal_generator.py +153 -0
  33. chip_brain-1.0.0/cerebrum/goal_stack.py +292 -0
  34. chip_brain-1.0.0/cerebrum/inner_speech.py +326 -0
  35. chip_brain-1.0.0/cerebrum/meta_cognition.py +262 -0
  36. chip_brain-1.0.0/cerebrum/narrative_self.py +314 -0
  37. chip_brain-1.0.0/cerebrum/personality.py +130 -0
  38. chip_brain-1.0.0/cerebrum/planner.py +125 -0
  39. chip_brain-1.0.0/cerebrum/reasoning.py +193 -0
  40. chip_brain-1.0.0/cerebrum/self_consistency.py +268 -0
  41. chip_brain-1.0.0/cerebrum/theory_of_mind.py +195 -0
  42. chip_brain-1.0.0/cerebrum/working_memory.py +164 -0
  43. chip_brain-1.0.0/cerebrum/world_model.py +172 -0
  44. chip_brain-1.0.0/chip_brain.egg-info/PKG-INFO +248 -0
  45. chip_brain-1.0.0/chip_brain.egg-info/SOURCES.txt +90 -0
  46. chip_brain-1.0.0/chip_brain.egg-info/dependency_links.txt +1 -0
  47. chip_brain-1.0.0/chip_brain.egg-info/entry_points.txt +2 -0
  48. chip_brain-1.0.0/chip_brain.egg-info/requires.txt +6 -0
  49. chip_brain-1.0.0/chip_brain.egg-info/top_level.txt +13 -0
  50. chip_brain-1.0.0/core/chip_policy.py +15 -0
  51. chip_brain-1.0.0/core/device.py +7 -0
  52. chip_brain-1.0.0/core/emotional_core.py +7 -0
  53. chip_brain-1.0.0/core/episodic_memory.py +7 -0
  54. chip_brain-1.0.0/core/interfaces.py +21 -0
  55. chip_brain-1.0.0/core/latent_alignment.py +7 -0
  56. chip_brain-1.0.0/core/merge_strategies.py +7 -0
  57. chip_brain-1.0.0/core/online_trainer.py +7 -0
  58. chip_brain-1.0.0/core/running_stats.py +7 -0
  59. chip_brain-1.0.0/core/transformer_architecture.py +7 -0
  60. chip_brain-1.0.0/hippocampus/__init__.py +7 -0
  61. chip_brain-1.0.0/hippocampus/active_dreaming.py +294 -0
  62. chip_brain-1.0.0/hippocampus/boundary_detector.py +177 -0
  63. chip_brain-1.0.0/hippocampus/dream_cycle.py +123 -0
  64. chip_brain-1.0.0/hippocampus/episodic_memory.py +228 -0
  65. chip_brain-1.0.0/hippocampus/episodic_recall.py +178 -0
  66. chip_brain-1.0.0/hippocampus/memory_consolidation.py +96 -0
  67. chip_brain-1.0.0/hippocampus/spatial_map.py +167 -0
  68. chip_brain-1.0.0/hippocampus/temporal_abstraction.py +115 -0
  69. chip_brain-1.0.0/hypothalamus/__init__.py +7 -0
  70. chip_brain-1.0.0/hypothalamus/curiosity_drive.py +114 -0
  71. chip_brain-1.0.0/hypothalamus/drive_arbitrator.py +106 -0
  72. chip_brain-1.0.0/hypothalamus/energy_manager.py +131 -0
  73. chip_brain-1.0.0/hypothalamus/entropy_temperature.py +136 -0
  74. chip_brain-1.0.0/hypothalamus/homeostasis.py +93 -0
  75. chip_brain-1.0.0/interfaces/__init__.py +28 -0
  76. chip_brain-1.0.0/interfaces/base.py +231 -0
  77. chip_brain-1.0.0/interfaces/plugins.py +183 -0
  78. chip_brain-1.0.0/interfaces/signals.py +235 -0
  79. chip_brain-1.0.0/locomotion/ModelMovementAndLocomotion.py +532 -0
  80. chip_brain-1.0.0/locomotion/__init__.py +1 -0
  81. chip_brain-1.0.0/parasite/ModelWeightParasiticExtraction.py +257 -0
  82. chip_brain-1.0.0/parasite/__init__.py +1 -0
  83. chip_brain-1.0.0/pyproject.toml +67 -0
  84. chip_brain-1.0.0/run.py +133 -0
  85. chip_brain-1.0.0/setup.cfg +4 -0
  86. chip_brain-1.0.0/thalamus/__init__.py +13 -0
  87. chip_brain-1.0.0/thalamus/attention_bottleneck.py +152 -0
  88. chip_brain-1.0.0/thalamus/granite_embedder.py +372 -0
  89. chip_brain-1.0.0/thalamus/latent_alignment.py +153 -0
  90. chip_brain-1.0.0/thalamus/merge_strategies.py +117 -0
  91. chip_brain-1.0.0/thalamus/sensory_encoder.py +177 -0
  92. chip_brain-1.0.0/thalamus/transformer_backbone.py +206 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Chip Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,248 @@
1
+ Metadata-Version: 2.4
2
+ Name: chip-brain
3
+ Version: 1.0.0
4
+ Summary: Brain-anatomical proto-AGI cognitive engine
5
+ Author: Chip Contributors
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/Doorman11991/Chip
8
+ Project-URL: Repository, https://github.com/Doorman11991/Chip
9
+ Project-URL: Changelog, https://github.com/Doorman11991/Chip/blob/main/CHANGELOG.md
10
+ Keywords: ai,agi,cognitive-architecture,reinforcement-learning,brain
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.10
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Requires-Python: <3.14,>=3.10
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Requires-Dist: torch>=2.0
25
+ Requires-Dist: transformers>=4.30
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest; extra == "dev"
28
+ Requires-Dist: ruff; extra == "dev"
29
+ Dynamic: license-file
30
+
31
+ # Chip — A Brain-Anatomical Proto-AGI
32
+
33
+ Chip is a pure-Python cognitive engine modelled after the human brain. Every module lives in the brain region it belongs to, communicates through typed signals on a central bus, and can be disabled without crashing the system.
34
+
35
+ It doesn't generate text. It doesn't call APIs. It *thinks* — in a 512-dimensional latent space where observations, emotions, memories, goals, and actions all share the same geometry.
36
+
37
+ ## Installation
38
+
39
+ ```bash
40
+ # Option 1: pip (recommended)
41
+ pip install chip-brain
42
+
43
+ # Option 2: Docker
44
+ docker run -it ghcr.io/doorman11991/chip:latest
45
+
46
+ # Option 3: From source
47
+ git clone https://github.com/Doorman11991/Chip.git
48
+ cd Chip
49
+ pip install torch transformers
50
+
51
+ # (Optional) Copy the env template
52
+ cp .env.example .env
53
+
54
+ # Verify everything works
55
+ python -c "from brain import ChipBrain; print(ChipBrain())"
56
+ ```
57
+
58
+ **Requirements:**
59
+ - Python 3.10–3.13 (3.14 has known numpy issues on Windows)
60
+ - PyTorch 2.0+
61
+ - HuggingFace Transformers 4.30+
62
+
63
+ **Optional (for GPU acceleration):**
64
+ - CUDA toolkit (NVIDIA)
65
+ - DirectML (AMD on Windows)
66
+ - MPS (Apple Silicon — automatic)
67
+
68
+ The first call to the text encoder downloads IBM Granite-125m (~250MB) from HuggingFace. After that it's cached locally and loads in ~5 seconds. The Docker image pre-caches it at build time.
69
+
70
+ ## Quick Start
71
+
72
+ ```bash
73
+ # Interactive session — just talk to it
74
+ python run.py
75
+ ```
76
+
77
+ ```
78
+ Chip Brain — Interactive Session
79
+
80
+ Commands:
81
+ [text] Feed an observation to the brain
82
+ status Show brain state
83
+ mood Show current mood and drives
84
+ thoughts Show recent inner speech
85
+ goals Show active goals
86
+ memory Show memory stats
87
+ save Force save to disk
88
+ quit Save and exit
89
+
90
+ you > I notice something strange in the corner of the room.
91
+
92
+ [tick 1] mood=Calm, confidence=0.49, |action|=0.42
93
+ thought: "I notice this feels novel. There is also a sense of risky."
94
+
95
+ you > thoughts
96
+
97
+ [Calm] I notice this feels novel. There is also a sense of risky.
98
+
99
+ you > status
100
+
101
+ tick: 1
102
+ mood: Calm
103
+ top goal: explore_frontier
104
+ confidence: 0.49
105
+ memories: 0
106
+ wm slots: 3/7
107
+ ```
108
+
109
+ ### As a Python library
110
+
111
+ ```python
112
+ from brain import ChipBrain
113
+
114
+ brain = ChipBrain().boot()
115
+
116
+ # One cognitive tick from a text observation:
117
+ action = brain.tick("I see an unfamiliar door at the end of the corridor.")
118
+
119
+ # Feed reward, advance training:
120
+ brain.train_step(reward=0.5, done=False)
121
+
122
+ # Save state to disk:
123
+ brain.shutdown()
124
+ ```
125
+
126
+ ## Requirements
127
+
128
+ ```
129
+ pip install torch transformers
130
+ ```
131
+
132
+ That's it. Two dependencies. Everything else is built from scratch.
133
+
134
+ ## Architecture
135
+
136
+ ```
137
+ Chip/
138
+ ├── brain.py ← Consciousness loop (top-level orchestrator)
139
+ ├── interfaces/ ← White matter: ABCs, SignalBus, plugin slots
140
+ ├── thalamus/ ← Sensory relay: granite encoder, transformer backbone, attention bottleneck
141
+ ├── amygdala/ ← Emotion: valence, fear veto, habituation, arousal modulation
142
+ ├── hippocampus/ ← Memory: episodic store, recall, dreams, boundary detection, cognitive maps
143
+ ├── hypothalamus/ ← Drives: homeostasis, curiosity, energy, entropy temperature
144
+ ├── cerebrum/ ← Cognition: policy, working memory, world model, reasoning, goals, inner speech
145
+ ├── cerebellum/ ← Coordination: action smoothing, skill library, swarm consensus, emotional contagion
146
+ ├── brainstem/ ← Life support: training loop, health monitor, persistence, scheduling
147
+ ├── locomotion/ ← Network migration (cognitive snapshot serialisation)
148
+ └── parasite/ ← Parasitic knowledge extraction from black-box models
149
+ ```
150
+
151
+ ## How It Works
152
+
153
+ Everything is a 512-D vector on a unit sphere. Text, emotions, memories, actions, goals — all in the same space. Cosine similarity = semantic relatedness.
154
+
155
+ **One tick flows like this:**
156
+
157
+ 1. **Thalamus** — Text enters via IBM Granite-125m (768→512 projection). Transformer backbone filters and routes tokens. Attention bottleneck selects the top-k most salient. Top-down query from previous tick's cerebrum biases what passes through.
158
+
159
+ 2. **Amygdala** — Fast emotional assessment (valence network). Habituation dampens repeated stimuli. Arousal gain signal sent to thalamus. Fear assessor can veto dangerous actions.
160
+
161
+ 3. **Hippocampus** — Retrieves top-3 relevant past episodes into working memory. Boundary detector auto-segments the stream via prediction-error spikes. Temporal abstractor compresses across timescales. Cognitive map tracks explored latent regions.
162
+
163
+ 4. **Hypothalamus** — 6-dim drive vector (arousal, energy, safety, engagement, curiosity, coherence). Curiosity reward from world model prediction error. Drive arbitrator picks the most urgent need. Entropy temperature adjusts exploration.
164
+
165
+ 5. **Cerebrum** — Working memory (7 slots). Policy selects action via dual-actor SAC with personality bias. Meta-cognition checks confidence; if low, fires 3-step reasoning chain. Inner speech surfaces thoughts in language. Contradiction detector checks new evidence against core beliefs. Goal stack manages hierarchical sub-goal planning.
166
+
167
+ 6. **Cerebellum** — Action smoothing (EMA). Skill library retrieval. Swarm consensus (if multi-node). Emotional contagion across nodes.
168
+
169
+ 7. **Brainstem** — SAC training update. Gradient clipping. Health monitoring (NaN detection). Periodic autosave to disk with HMAC-signed snapshots.
170
+
171
+ ## Key Design Decisions
172
+
173
+ **One latent space.** No translation layers between modalities. Everything projects into the same 512-D sphere so any two things can be compared by dot product.
174
+
175
+ **Signal bus, not imports.** Brain regions never import each other. They publish typed `NeuralSignal` objects on a priority-ordered bus. This makes the system testable, observable, and gracefully degradable.
176
+
177
+ **Stop-gradient boundaries.** The world model trains on detached latents so it can't fight the policy optimizer for the backbone's representation.
178
+
179
+ **Periodic language grounding.** Every 100 ticks, the brain translates its internal state into English ("I feel calm and curious"), encodes it with granite, and anchors the identity token to it. The subconscious drifts in language-grounded space, not arbitrary latent drift.
180
+
181
+ **SLERP belief revision.** When new evidence contradicts a core belief, the belief embedding rotates on the unit sphere via spherical linear interpolation. Small contradictions → quiet revision. Large contradictions → narrative crisis that forces deliberation.
182
+
183
+ **Active dreaming.** The hippocampus doesn't just replay memories — it identifies key decision points, imagines alternative actions via the world model, evaluates the counterfactual trajectories, and stores the best as synthetic memories. Creativity from imagination.
184
+
185
+ ## Plugin Slots
186
+
187
+ Chip is designed to be embedded in a larger system. The host application provides:
188
+
189
+ ```python
190
+ from interfaces.plugins import ITool, ToolRegistry, IEnvironment
191
+
192
+ class MyTool(ITool):
193
+ name = "search"
194
+ def call(self, args): ...
195
+
196
+ brain = ChipBrain(tool_registry=ToolRegistry()).boot()
197
+ ```
198
+
199
+ Available extension points:
200
+ - `ITool` / `ToolRegistry` — external tool dispatch
201
+ - `IEnvironment` — step-based environment loop
202
+ - `ISensor` — custom sensory modality
203
+ - `IRewardSource` — external reward signal
204
+ - `HookRegistry` — observe brain events (inner speech, contradictions, boundaries)
205
+
206
+ ## Persistence
207
+
208
+ The brain autosaves to `.chip_state/` every N ticks:
209
+ - HMAC-SHA256 signed snapshots (tamper-proof)
210
+ - Atomic writes (crash-safe)
211
+ - Rolling backups (corruption recovery)
212
+ - Auto-restore on boot
213
+
214
+ ```python
215
+ brain.save() # manual save
216
+ brain.shutdown() # save + cleanup
217
+ ```
218
+
219
+ ## Tests
220
+
221
+ ```
222
+ python scripts/e2e_brain_test.py # full brain against LM Studio endpoint
223
+ python scripts/example_granite_integration.py # granite embedder demo
224
+ python scripts/test_feature_episodic_recall.py # inference-time memory retrieval
225
+ python scripts/test_feature_topdown_attention.py # corticothalamic feedback loop
226
+ python scripts/test_feature_persistence.py # save/restore/crash recovery
227
+ python scripts/test_feature_inner_speech.py # internal monologue
228
+ python scripts/test_feature_self_consistency.py # contradiction detection + belief revision
229
+ python scripts/test_feature_stability_fixes.py # stop-gradient + Platt calibration
230
+ python scripts/test_feature_goal_stack.py # hierarchical sub-goal planning
231
+ python scripts/test_feature_habit_boundary.py # habituation + episodic boundaries
232
+ python scripts/test_feature_contagion_dreaming.py # emotional contagion + active dreaming
233
+ ```
234
+
235
+ 191 tests. All passing.
236
+
237
+ ## What This Is Not
238
+
239
+ - Not a chatbot. It doesn't generate text.
240
+ - Not a LangChain wrapper. No API calls in the loop.
241
+ - Not a research toy. It persists state, handles crashes, and scales.
242
+ - Not finished. It needs a real training environment to become intelligent.
243
+
244
+ The architecture is complete. The intelligence emerges from training.
245
+
246
+ ## License
247
+
248
+ See [LICENSE](LICENSE).
@@ -0,0 +1,218 @@
1
+ # Chip — A Brain-Anatomical Proto-AGI
2
+
3
+ Chip is a pure-Python cognitive engine modelled after the human brain. Every module lives in the brain region it belongs to, communicates through typed signals on a central bus, and can be disabled without crashing the system.
4
+
5
+ It doesn't generate text. It doesn't call APIs. It *thinks* — in a 512-dimensional latent space where observations, emotions, memories, goals, and actions all share the same geometry.
6
+
7
+ ## Installation
8
+
9
+ ```bash
10
+ # Option 1: pip (recommended)
11
+ pip install chip-brain
12
+
13
+ # Option 2: Docker
14
+ docker run -it ghcr.io/doorman11991/chip:latest
15
+
16
+ # Option 3: From source
17
+ git clone https://github.com/Doorman11991/Chip.git
18
+ cd Chip
19
+ pip install torch transformers
20
+
21
+ # (Optional) Copy the env template
22
+ cp .env.example .env
23
+
24
+ # Verify everything works
25
+ python -c "from brain import ChipBrain; print(ChipBrain())"
26
+ ```
27
+
28
+ **Requirements:**
29
+ - Python 3.10–3.13 (3.14 has known numpy issues on Windows)
30
+ - PyTorch 2.0+
31
+ - HuggingFace Transformers 4.30+
32
+
33
+ **Optional (for GPU acceleration):**
34
+ - CUDA toolkit (NVIDIA)
35
+ - DirectML (AMD on Windows)
36
+ - MPS (Apple Silicon — automatic)
37
+
38
+ The first call to the text encoder downloads IBM Granite-125m (~250MB) from HuggingFace. After that it's cached locally and loads in ~5 seconds. The Docker image pre-caches it at build time.
39
+
40
+ ## Quick Start
41
+
42
+ ```bash
43
+ # Interactive session — just talk to it
44
+ python run.py
45
+ ```
46
+
47
+ ```
48
+ Chip Brain — Interactive Session
49
+
50
+ Commands:
51
+ [text] Feed an observation to the brain
52
+ status Show brain state
53
+ mood Show current mood and drives
54
+ thoughts Show recent inner speech
55
+ goals Show active goals
56
+ memory Show memory stats
57
+ save Force save to disk
58
+ quit Save and exit
59
+
60
+ you > I notice something strange in the corner of the room.
61
+
62
+ [tick 1] mood=Calm, confidence=0.49, |action|=0.42
63
+ thought: "I notice this feels novel. There is also a sense of risky."
64
+
65
+ you > thoughts
66
+
67
+ [Calm] I notice this feels novel. There is also a sense of risky.
68
+
69
+ you > status
70
+
71
+ tick: 1
72
+ mood: Calm
73
+ top goal: explore_frontier
74
+ confidence: 0.49
75
+ memories: 0
76
+ wm slots: 3/7
77
+ ```
78
+
79
+ ### As a Python library
80
+
81
+ ```python
82
+ from brain import ChipBrain
83
+
84
+ brain = ChipBrain().boot()
85
+
86
+ # One cognitive tick from a text observation:
87
+ action = brain.tick("I see an unfamiliar door at the end of the corridor.")
88
+
89
+ # Feed reward, advance training:
90
+ brain.train_step(reward=0.5, done=False)
91
+
92
+ # Save state to disk:
93
+ brain.shutdown()
94
+ ```
95
+
96
+ ## Requirements
97
+
98
+ ```
99
+ pip install torch transformers
100
+ ```
101
+
102
+ That's it. Two dependencies. Everything else is built from scratch.
103
+
104
+ ## Architecture
105
+
106
+ ```
107
+ Chip/
108
+ ├── brain.py ← Consciousness loop (top-level orchestrator)
109
+ ├── interfaces/ ← White matter: ABCs, SignalBus, plugin slots
110
+ ├── thalamus/ ← Sensory relay: granite encoder, transformer backbone, attention bottleneck
111
+ ├── amygdala/ ← Emotion: valence, fear veto, habituation, arousal modulation
112
+ ├── hippocampus/ ← Memory: episodic store, recall, dreams, boundary detection, cognitive maps
113
+ ├── hypothalamus/ ← Drives: homeostasis, curiosity, energy, entropy temperature
114
+ ├── cerebrum/ ← Cognition: policy, working memory, world model, reasoning, goals, inner speech
115
+ ├── cerebellum/ ← Coordination: action smoothing, skill library, swarm consensus, emotional contagion
116
+ ├── brainstem/ ← Life support: training loop, health monitor, persistence, scheduling
117
+ ├── locomotion/ ← Network migration (cognitive snapshot serialisation)
118
+ └── parasite/ ← Parasitic knowledge extraction from black-box models
119
+ ```
120
+
121
+ ## How It Works
122
+
123
+ Everything is a 512-D vector on a unit sphere. Text, emotions, memories, actions, goals — all in the same space. Cosine similarity = semantic relatedness.
124
+
125
+ **One tick flows like this:**
126
+
127
+ 1. **Thalamus** — Text enters via IBM Granite-125m (768→512 projection). Transformer backbone filters and routes tokens. Attention bottleneck selects the top-k most salient. Top-down query from previous tick's cerebrum biases what passes through.
128
+
129
+ 2. **Amygdala** — Fast emotional assessment (valence network). Habituation dampens repeated stimuli. Arousal gain signal sent to thalamus. Fear assessor can veto dangerous actions.
130
+
131
+ 3. **Hippocampus** — Retrieves top-3 relevant past episodes into working memory. Boundary detector auto-segments the stream via prediction-error spikes. Temporal abstractor compresses across timescales. Cognitive map tracks explored latent regions.
132
+
133
+ 4. **Hypothalamus** — 6-dim drive vector (arousal, energy, safety, engagement, curiosity, coherence). Curiosity reward from world model prediction error. Drive arbitrator picks the most urgent need. Entropy temperature adjusts exploration.
134
+
135
+ 5. **Cerebrum** — Working memory (7 slots). Policy selects action via dual-actor SAC with personality bias. Meta-cognition checks confidence; if low, fires 3-step reasoning chain. Inner speech surfaces thoughts in language. Contradiction detector checks new evidence against core beliefs. Goal stack manages hierarchical sub-goal planning.
136
+
137
+ 6. **Cerebellum** — Action smoothing (EMA). Skill library retrieval. Swarm consensus (if multi-node). Emotional contagion across nodes.
138
+
139
+ 7. **Brainstem** — SAC training update. Gradient clipping. Health monitoring (NaN detection). Periodic autosave to disk with HMAC-signed snapshots.
140
+
141
+ ## Key Design Decisions
142
+
143
+ **One latent space.** No translation layers between modalities. Everything projects into the same 512-D sphere so any two things can be compared by dot product.
144
+
145
+ **Signal bus, not imports.** Brain regions never import each other. They publish typed `NeuralSignal` objects on a priority-ordered bus. This makes the system testable, observable, and gracefully degradable.
146
+
147
+ **Stop-gradient boundaries.** The world model trains on detached latents so it can't fight the policy optimizer for the backbone's representation.
148
+
149
+ **Periodic language grounding.** Every 100 ticks, the brain translates its internal state into English ("I feel calm and curious"), encodes it with granite, and anchors the identity token to it. The subconscious drifts in language-grounded space, not arbitrary latent drift.
150
+
151
+ **SLERP belief revision.** When new evidence contradicts a core belief, the belief embedding rotates on the unit sphere via spherical linear interpolation. Small contradictions → quiet revision. Large contradictions → narrative crisis that forces deliberation.
152
+
153
+ **Active dreaming.** The hippocampus doesn't just replay memories — it identifies key decision points, imagines alternative actions via the world model, evaluates the counterfactual trajectories, and stores the best as synthetic memories. Creativity from imagination.
154
+
155
+ ## Plugin Slots
156
+
157
+ Chip is designed to be embedded in a larger system. The host application provides:
158
+
159
+ ```python
160
+ from interfaces.plugins import ITool, ToolRegistry, IEnvironment
161
+
162
+ class MyTool(ITool):
163
+ name = "search"
164
+ def call(self, args): ...
165
+
166
+ brain = ChipBrain(tool_registry=ToolRegistry()).boot()
167
+ ```
168
+
169
+ Available extension points:
170
+ - `ITool` / `ToolRegistry` — external tool dispatch
171
+ - `IEnvironment` — step-based environment loop
172
+ - `ISensor` — custom sensory modality
173
+ - `IRewardSource` — external reward signal
174
+ - `HookRegistry` — observe brain events (inner speech, contradictions, boundaries)
175
+
176
+ ## Persistence
177
+
178
+ The brain autosaves to `.chip_state/` every N ticks:
179
+ - HMAC-SHA256 signed snapshots (tamper-proof)
180
+ - Atomic writes (crash-safe)
181
+ - Rolling backups (corruption recovery)
182
+ - Auto-restore on boot
183
+
184
+ ```python
185
+ brain.save() # manual save
186
+ brain.shutdown() # save + cleanup
187
+ ```
188
+
189
+ ## Tests
190
+
191
+ ```
192
+ python scripts/e2e_brain_test.py # full brain against LM Studio endpoint
193
+ python scripts/example_granite_integration.py # granite embedder demo
194
+ python scripts/test_feature_episodic_recall.py # inference-time memory retrieval
195
+ python scripts/test_feature_topdown_attention.py # corticothalamic feedback loop
196
+ python scripts/test_feature_persistence.py # save/restore/crash recovery
197
+ python scripts/test_feature_inner_speech.py # internal monologue
198
+ python scripts/test_feature_self_consistency.py # contradiction detection + belief revision
199
+ python scripts/test_feature_stability_fixes.py # stop-gradient + Platt calibration
200
+ python scripts/test_feature_goal_stack.py # hierarchical sub-goal planning
201
+ python scripts/test_feature_habit_boundary.py # habituation + episodic boundaries
202
+ python scripts/test_feature_contagion_dreaming.py # emotional contagion + active dreaming
203
+ ```
204
+
205
+ 191 tests. All passing.
206
+
207
+ ## What This Is Not
208
+
209
+ - Not a chatbot. It doesn't generate text.
210
+ - Not a LangChain wrapper. No API calls in the loop.
211
+ - Not a research toy. It persists state, handles crashes, and scales.
212
+ - Not finished. It needs a real training environment to become intelligent.
213
+
214
+ The architecture is complete. The intelligence emerges from training.
215
+
216
+ ## License
217
+
218
+ See [LICENSE](LICENSE).
@@ -0,0 +1,7 @@
1
+ """
2
+ amygdala/ — Emotion processing.
3
+
4
+ Valence network, mood tracking, fear/risk assessment,
5
+ emotional memory tagging, and arousal-based attention modulation.
6
+ Analogous to the amygdala: fear, emotional memories, threat detection.
7
+ """
@@ -0,0 +1,154 @@
1
+ """
2
+ amygdala/affective_forecast.py — Predict future valence of a trajectory.
3
+
4
+ The world model predicts future *states*. This module predicts future
5
+ *feelings* — how a trajectory will make the agent feel over time. This
6
+ lets the cerebrum pick actions not just by predicted reward, but by
7
+ anticipated emotional outcome.
8
+
9
+ predicted_valence_trajectory = forecast(z_trajectory)
10
+
11
+ Use cases:
12
+ - Avoid actions that lead to sustained negative valence (learned anxiety)
13
+ - Prefer actions that lead to engagement (learned motivation)
14
+ - Detect "emotional dead ends" (trajectories that flatten to neutral)
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ from typing import Optional, Tuple
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+
24
+
25
+ class AffectiveForecaster(nn.Module):
26
+ """
27
+ Predicts the valence trajectory for a sequence of latent states.
28
+
29
+ Architecture: small GRU over the trajectory, outputs per-step valence
30
+ predictions in [-1, 1].
31
+
32
+ Args:
33
+ latent_dim: Dimensionality of latent states.
34
+ hidden_dim: GRU hidden size.
35
+ """
36
+
37
+ def __init__(self, latent_dim: int = 512, hidden_dim: int = 128) -> None:
38
+ super().__init__()
39
+ self.gru = nn.GRU(latent_dim, hidden_dim, batch_first=True)
40
+ self.head = nn.Sequential(
41
+ nn.Linear(hidden_dim, 64),
42
+ nn.GELU(),
43
+ nn.Linear(64, 1),
44
+ nn.Tanh(),
45
+ )
46
+
47
+ def forward(self, trajectory: torch.Tensor) -> torch.Tensor:
48
+ """
49
+ Predict valence at each step of a trajectory.
50
+
51
+ Args:
52
+ trajectory: (B, T, D) latent state sequence.
53
+
54
+ Returns:
55
+ (B, T, 1) predicted valence at each timestep.
56
+ """
57
+ h, _ = self.gru(trajectory) # (B, T, hidden)
58
+ return self.head(h) # (B, T, 1)
59
+
60
+ def forecast_mean(self, trajectory: torch.Tensor) -> torch.Tensor:
61
+ """
62
+ Predict the average valence over a trajectory.
63
+
64
+ Returns:
65
+ (B, 1) mean predicted valence.
66
+ """
67
+ per_step = self.forward(trajectory)
68
+ return per_step.mean(dim=1)
69
+
70
+ def forecast_final(self, trajectory: torch.Tensor) -> torch.Tensor:
71
+ """
72
+ Predict the valence at the END of the trajectory.
73
+
74
+ Returns:
75
+ (B, 1) final-step valence prediction.
76
+ """
77
+ per_step = self.forward(trajectory)
78
+ return per_step[:, -1, :]
79
+
80
+ def compare_trajectories(
81
+ self,
82
+ traj_a: torch.Tensor,
83
+ traj_b: torch.Tensor,
84
+ ) -> Tuple[float, float]:
85
+ """
86
+ Compare two trajectories by predicted emotional outcome.
87
+
88
+ Returns:
89
+ (mean_valence_a, mean_valence_b) — higher is emotionally preferred.
90
+ """
91
+ va = float(self.forecast_mean(traj_a).mean().item())
92
+ vb = float(self.forecast_mean(traj_b).mean().item())
93
+ return va, vb
94
+
95
+ def emotional_dead_end(
96
+ self,
97
+ trajectory: torch.Tensor,
98
+ threshold: float = 0.05,
99
+ ) -> bool:
100
+ """
101
+ Detect if a trajectory leads to emotional flatness (stagnation).
102
+
103
+ A dead end is where predicted valence variance across time is
104
+ near zero AND mean valence is near zero. The agent isn't feeling
105
+ anything — neither good nor bad. Often worse than negative valence
106
+ (which at least indicates engagement).
107
+
108
+ Returns:
109
+ True if the trajectory is an emotional dead end.
110
+ """
111
+ per_step = self.forward(trajectory) # (B, T, 1)
112
+ var = per_step.var(dim=1).mean().item()
113
+ mean = per_step.mean().abs().item()
114
+ return var < threshold and mean < threshold
115
+
116
+
117
+ class AffectiveForecasterTrainer:
118
+ """
119
+ Trains the forecaster on observed (trajectory, actual_valence) pairs.
120
+
121
+ Call `update()` with real episodes and their actual valences from the
122
+ emotional core. The forecaster learns to predict future affect.
123
+ """
124
+
125
+ def __init__(self, forecaster: AffectiveForecaster, lr: float = 1e-4) -> None:
126
+ self.forecaster = forecaster
127
+ self.optimizer = torch.optim.Adam(forecaster.parameters(), lr=lr)
128
+ self._step = 0
129
+
130
+ def update(
131
+ self,
132
+ trajectory: torch.Tensor,
133
+ actual_valences: torch.Tensor,
134
+ ) -> float:
135
+ """
136
+ One training step.
137
+
138
+ Args:
139
+ trajectory: (B, T, D) latent state sequences.
140
+ actual_valences: (B, T, 1) actual valences observed.
141
+
142
+ Returns:
143
+ Scalar MSE loss.
144
+ """
145
+ self.optimizer.zero_grad()
146
+ predicted = self.forecaster(trajectory)
147
+ loss = nn.functional.mse_loss(predicted, actual_valences.detach())
148
+ loss.backward()
149
+ self.optimizer.step()
150
+ self._step += 1
151
+ return loss.item()
152
+
153
+
154
+ __all__ = ["AffectiveForecaster", "AffectiveForecasterTrainer"]