# tgakathunderr/bim-2 architecture

> Architecture diagram of the GitHub repository tgakathunderr/bim-2, generated by GitDiagram from its file tree, README and a sample of source files (last updated 2026-05-26). It is an AI-made overview: check details against the source.

- Interactive diagram: https://gitdiagram.com/tgakathunderr/bim-2
- Repository: https://github.com/tgakathunderr/bim-2

## Overview

1. **Project shape and runtime boundary**
   - BIM 2 is a **CPU-only, online sequence learning system** exposed through a small CLI in `main.py`.
   - The repository is organized around a session loop that learns from each token as it arrives, with optional checkpoint load/save for persistence across runs.

2. **Top-level execution flow**
   - User text enters through `interaction/loop.py`.
   - Text is tokenized in `inference/tokenizer.py`.
   - Tokens are converted into sparse distributed representations by the core spatial pooler.
   - Those SDRs flow through the hierarchical cortex for prediction and learning.
   - Outputs are decoded back to tokens and returned to the interaction loop.
   - Session state can be saved/restored via `utils/save_load.py`.

3. **Core representation layer**
   - `core/spatial_pooler.py` is the token-to-SDR boundary.
   - Each token maps to a sparse pattern of active columns, giving the model a fixed high-dimensional representation space.
   - `core/sdr.py` likely provides the SDR data structures and set-like operations used throughout the rest of the system.

4. **Hierarchical cortex subsystem**
   - `core/sparse_cortex.py` and `core/hierarchy.py` implement the main predictive substrate.
   - The architecture is two-layered: a lower sensory layer for local token transitions and an upper abstract layer for slower context.
   - The README’s “apical bias” feedback means top-down influence is part of the prediction path, not just a post-processing step.

5. **Learning subsystem**
   - The learning package contains the model’s adaptation rules:
     - `learning/prediction_error.py` computes surprise/error between predicted and actual SDRs.
     - `learning/sparse_predictive.py` holds the Hebbian-style potentiation/depression logic.
     - `learning/reward.py` adds scalar reward-based adjustment for previous/current winners.
     - `learning/homeostasis.py` performs synaptic scaling to prevent runaway permanence growth.
   - The key design boundary is that **surprise directly scales learning**, so updates happen only when prediction was wrong.

6. **Concept formation and abstraction**
   - `learning/concepts.py` builds the `ConceptGraph`.
   - Repeated abstract L2 patterns crystallize into named concepts, and weighted edges capture co-occurrence relationships.
   - This subsystem is separate from the raw cortex: it turns stable internal patterns into graph-based symbolic memory and shallow inference.

7. **Interaction and working memory**
   - `interaction/loop.py` is the conversational orchestrator and REPL-facing control loop.
   - `interaction/memory.py` stores recent `(input SDR, response SDR, surprise)` tuples with decay.
   - This working memory is the bridge between immediate token-level behavior and longer session context, including correction behavior.

8. **Inference boundary**
   - `inference/tokenizer.py` is the only explicit text-processing boundary in the repo.
   - It enforces a **word-level vocabulary** and maps text to model tokens and back.
   - This matters architecturally because the model does not operate on subword pieces or embeddings; it learns directly over discrete tokens.

9. **Persistence and observability**
   - `utils/save_load.py` handles full-state checkpointing, which is important because the model is intended to accumulate knowledge over time.
   - `utils/metrics.py` and `main.py stats` expose system-level measurements.
   - `utils/visualization.py` is the inspection/diagnostic boundary for understanding learned structure and activity patterns.

10. **Operational modes**
   - `main.py` dispatches at least three workflows:
     - `interact` for online teaching and dialogue,
     - `stats` for inspection,
     - `benchmark` for the fictional NovaCorp knowledge/inference test.
   - The benchmark is not a training pipeline separate from the system; it is a scripted exercise of the same online learning stack.

11. **Important data flow to capture in a diagram**
   - Token in → tokenizer → spatial pooler SDR → hierarchical cortex → prediction/error comparison → surprise-scaled learning update → updated permanences/state → token out.
   - In parallel, repeated abstract patterns may flow into `ConceptGraph`, and recent exchanges may flow into working memory.

12. **Architectural constraints that shape the system**
   - No backpropagation, no GPU, no pretraining: learning is local, incremental, and stateful.
   - The system’s “knowledge” is therefore distributed across permanence matrices, contextual winners, memory buffers, and concept edges rather than a single trained weight file.

Main entry points: [`main.py`](https://github.com/tgakathunderr/bim-2/blob/main/main.py) (Main), [`core/sparse_cortex.py`](https://github.com/tgakathunderr/bim-2/blob/main/core/sparse_cortex.py) (Sparse cortex), [`interaction/loop.py`](https://github.com/tgakathunderr/bim-2/blob/main/interaction/loop.py) (Session loop), [`learning/sparse_predictive.py`](https://github.com/tgakathunderr/bim-2/blob/main/learning/sparse_predictive.py) (Predictive learning)

## Diagram (Mermaid)

```mermaid
flowchart TD

subgraph group_grp_entry["Entry & I/O"]
  node_main["Main<br/>CLI dispatcher<br/>[main.py]"]
  node_tokenizer["Tokenizer<br/>word-level text<br/>[tokenizer.py]"]
  node_config["Config<br/>runtime settings<br/>[config.py]"]
end

subgraph group_grp_core["Core Model"]
  node_spatial_pooler["Spatial pooler<br/>token-to-SDR<br/>[spatial_pooler.py]"]
  node_sdr["SDR<br/>sparse repr<br/>[sdr.py]"]
  node_cortex["Sparse cortex<br/>predictive substrate<br/>[sparse_cortex.py]"]
  node_hierarchy["Hierarchy<br/>two-layer cortex<br/>[hierarchy.py]"]
end

subgraph group_grp_learning["Learning"]
  node_error["Prediction error<br/>surprise signal"]
  node_predictive["Predictive learning<br/>hebbian updates"]
  node_reward["Reward<br/>scalar modulation<br/>[reward.py]"]
  node_homeostasis["Homeostasis<br/>synaptic scaling<br/>[homeostasis.py]"]
  node_concepts{{"Concept graph<br/>symbolic memory<br/>[concepts.py]"}}
end

subgraph group_grp_interaction["Interaction"]
  node_loop["Session loop<br/>online REPL<br/>[loop.py]"]
  node_memory["Working memory<br/>session buffer<br/>[memory.py]"]
end

subgraph group_grp_utils["Utilities"]
  node_save_load["Checkpointing<br/>state persistence<br/>[save_load.py]"]
  node_metrics["Metrics<br/>system stats<br/>[metrics.py]"]
  node_visualization["Visualization<br/>inspection<br/>[visualization.py]"]
end

node_main -->|"interact"| node_loop
node_main -->|"stats"| node_metrics
node_main -->|"inspect"| node_visualization
node_main -->|"checkpoint"| node_save_load
node_loop -->|"text"| node_tokenizer
node_tokenizer -->|"tokens"| node_spatial_pooler
node_spatial_pooler -->|"encode"| node_sdr
node_sdr -->|"SDR flow"| node_cortex
node_cortex -->|"layers"| node_hierarchy
node_hierarchy -->|"compare"| node_error
node_error -->|"scale"| node_predictive
node_predictive -->|"update"| node_cortex
node_reward -->|"modulate"| node_predictive
node_homeostasis -->|"stabilize"| node_predictive
node_hierarchy -->|"abstract patterns"| node_concepts
node_loop -->|"store turns"| node_memory
node_memory -->|"context"| node_loop
node_save_load -->|"restore"| node_loop
node_cortex -->|"state"| node_save_load
node_metrics -->|"report"| node_visualization
node_config -->|"params"| node_main
node_config -->|"tuning"| node_cortex

click node_main "https://github.com/tgakathunderr/bim-2/blob/main/main.py"
click node_tokenizer "https://github.com/tgakathunderr/bim-2/blob/main/inference/tokenizer.py"
click node_loop "https://github.com/tgakathunderr/bim-2/blob/main/interaction/loop.py"
click node_memory "https://github.com/tgakathunderr/bim-2/blob/main/interaction/memory.py"
click node_spatial_pooler "https://github.com/tgakathunderr/bim-2/blob/main/core/spatial_pooler.py"
click node_sdr "https://github.com/tgakathunderr/bim-2/blob/main/core/sdr.py"
click node_cortex "https://github.com/tgakathunderr/bim-2/blob/main/core/sparse_cortex.py"
click node_hierarchy "https://github.com/tgakathunderr/bim-2/blob/main/core/hierarchy.py"
click node_error "https://github.com/tgakathunderr/bim-2/blob/main/learning/prediction_error.py"
click node_predictive "https://github.com/tgakathunderr/bim-2/blob/main/learning/sparse_predictive.py"
click node_reward "https://github.com/tgakathunderr/bim-2/blob/main/learning/reward.py"
click node_homeostasis "https://github.com/tgakathunderr/bim-2/blob/main/learning/homeostasis.py"
click node_concepts "https://github.com/tgakathunderr/bim-2/blob/main/learning/concepts.py"
click node_save_load "https://github.com/tgakathunderr/bim-2/blob/main/utils/save_load.py"
click node_metrics "https://github.com/tgakathunderr/bim-2/blob/main/utils/metrics.py"
click node_visualization "https://github.com/tgakathunderr/bim-2/blob/main/utils/visualization.py"
click node_config "https://github.com/tgakathunderr/bim-2/blob/main/config.py"

classDef toneNeutral fill:#f8fafc,stroke:#334155,stroke-width:1.5px,color:#0f172a
classDef toneBlue fill:#dbeafe,stroke:#2563eb,stroke-width:1.5px,color:#172554
classDef toneAmber fill:#fef3c7,stroke:#d97706,stroke-width:1.5px,color:#78350f
classDef toneMint fill:#dcfce7,stroke:#16a34a,stroke-width:1.5px,color:#14532d
classDef toneRose fill:#ffe4e6,stroke:#e11d48,stroke-width:1.5px,color:#881337
classDef toneIndigo fill:#e0e7ff,stroke:#4f46e5,stroke-width:1.5px,color:#312e81
classDef toneTeal fill:#ccfbf1,stroke:#0f766e,stroke-width:1.5px,color:#134e4a
class node_main,node_tokenizer,node_config toneBlue
class node_spatial_pooler,node_sdr,node_cortex,node_hierarchy toneAmber
class node_error,node_predictive,node_reward,node_homeostasis,node_concepts toneMint
class node_loop,node_memory toneRose
class node_save_load,node_metrics,node_visualization toneIndigo
```

## Components

### Entry & I/O

CLI dispatch and text/token boundaries.

- [Main](https://github.com/tgakathunderr/bim-2/blob/main/main.py): CLI dispatcher · Entry point that routes between interact, stats, and benchmark workflows. · `main.py`
- [Tokenizer](https://github.com/tgakathunderr/bim-2/blob/main/inference/tokenizer.py): word-level text · Converts user text to model tokens and decodes tokens back to text. · `inference/tokenizer.py`
- [Config](https://github.com/tgakathunderr/bim-2/blob/main/config.py): runtime settings · Holds system parameters that shape the online learning run. · `config.py`

### Core Model

Representation, cortex, and hierarchy.

- [Spatial pooler](https://github.com/tgakathunderr/bim-2/blob/main/core/spatial_pooler.py): token-to-SDR · Maps discrete tokens into sparse distributed representations. · `core/spatial_pooler.py`
- [SDR](https://github.com/tgakathunderr/bim-2/blob/main/core/sdr.py): sparse repr · Core sparse distributed representation data structures and operations. · `core/sdr.py`
- [Sparse cortex](https://github.com/tgakathunderr/bim-2/blob/main/core/sparse_cortex.py): predictive substrate · Main cortical substrate that predicts and learns from sparse activity. · `core/sparse_cortex.py`
- [Hierarchy](https://github.com/tgakathunderr/bim-2/blob/main/core/hierarchy.py): two-layer cortex · Coordinates lower sensory and upper abstract layers with top-down influence. · `core/hierarchy.py`

### Learning

Local adaptation, surprise, reward, and concept formation.

- [Prediction error](https://github.com/tgakathunderr/bim-2/blob/main/learning/prediction_error.py): surprise signal · Computes mismatch between predicted and actual SDRs. · `learning/prediction_error.py`
- [Predictive learning](https://github.com/tgakathunderr/bim-2/blob/main/learning/sparse_predictive.py): hebbian updates · Applies local potentiation and depression for sparse predictive learning. · `learning/sparse_predictive.py`
- [Reward](https://github.com/tgakathunderr/bim-2/blob/main/learning/reward.py): scalar modulation · Modulates learning using reward signals for previous and current winners. · `learning/reward.py`
- [Homeostasis](https://github.com/tgakathunderr/bim-2/blob/main/learning/homeostasis.py): synaptic scaling · Constrains permanence growth and keeps learning stable. · `learning/homeostasis.py`
- [Concept graph](https://github.com/tgakathunderr/bim-2/blob/main/learning/concepts.py): symbolic memory · Forms named concepts and co-occurrence links from repeated abstract patterns. · `learning/concepts.py`

### Interaction

Session loop and working memory.

- [Session loop](https://github.com/tgakathunderr/bim-2/blob/main/interaction/loop.py): online REPL · Orchestrates the turn-by-turn interaction and online teaching cycle. · `interaction/loop.py`
- [Working memory](https://github.com/tgakathunderr/bim-2/blob/main/interaction/memory.py): session buffer · Stores recent input, response, and surprise tuples with decay. · `interaction/memory.py`

### Utilities

Persistence, metrics, and visualization.

- [Checkpointing](https://github.com/tgakathunderr/bim-2/blob/main/utils/save_load.py): state persistence · Saves and restores full session and model state across runs. · `utils/save_load.py`
- [Metrics](https://github.com/tgakathunderr/bim-2/blob/main/utils/metrics.py): system stats · Computes repository-level measurements for inspection and stats mode. · `utils/metrics.py`
- [Visualization](https://github.com/tgakathunderr/bim-2/blob/main/utils/visualization.py): inspection · Renders internal structure and activity for debugging and analysis. · `utils/visualization.py`

## Connections

- Main → Session loop: interact · Dispatches the interactive online learning workflow.
- Main → Metrics: stats · Routes to system measurement and inspection.
- Main → Visualization: inspect · Can invoke visual diagnostics.
- Main → Checkpointing: checkpoint · Loads or saves session state around runs.
- Session loop → Tokenizer: text · Accepts user text and converts it for model processing.
- Tokenizer → Spatial pooler: tokens · Feeds discrete tokens into the representation boundary.
- Spatial pooler → SDR: encode · Produces sparse distributed representations.
- SDR → Sparse cortex: SDR flow · Provides sparse inputs to the predictive cortex.
- Sparse cortex → Hierarchy: layers · Organizes computation across sensory and abstract layers.
- Hierarchy → Prediction error: compare · Compares predicted and observed activity to form surprise.
- Prediction error → Predictive learning: scale · Surprise gates the magnitude of learning updates.
- Predictive learning → Sparse cortex: update · Adjusts permanences and local predictive state.
- Reward → Predictive learning: modulate · Biases learning using reward information.
- Homeostasis → Predictive learning: stabilize · Normalizes growth to prevent runaway adaptation.
- Hierarchy → Concept graph: abstract patterns · Feeds stable higher-level patterns into concept formation.
- Session loop → Working memory: store turns · Records recent exchanges and surprise for context.
- Working memory → Session loop: context · Provides recent session history back to the interaction loop.
- Checkpointing → Session loop: restore · Rehydrates session state for continued learning.
- Sparse cortex → Checkpointing: state · Persists learned structure and context across runs.
- Metrics → Visualization: report · Feeds measured state into inspection views.
- Config → Main: params · Supplies runtime configuration for CLI execution.
- Config → Sparse cortex: tuning · Shapes core model behavior through parameters.
