dual-loop-controller 2.0.0a3__tar.gz → 2.2.1__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.
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/LICENSE +7 -0
- dual_loop_controller-2.2.1/PKG-INFO +252 -0
- dual_loop_controller-2.2.1/README.md +220 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/__init__.py +38 -3
- dual_loop_controller-2.2.1/dual_loop/adapters/__init__.py +8 -0
- dual_loop_controller-2.2.1/dual_loop/adapters/latent_adapter.py +438 -0
- dual_loop_controller-2.2.1/dual_loop/adapters/qwen_adapter.py +502 -0
- dual_loop_controller-2.2.1/dual_loop/benchmarks/benchmark_qwen_reasoning.py +414 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/benchmarks/comprehensive_suite.py +16 -4
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/benchmarks/graph_reasoning.py +11 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/benchmarks/halting_audit.py +1 -1
- dual_loop_controller-2.2.1/dual_loop/controller.py +403 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/decoder.py +151 -22
- dual_loop_controller-2.2.1/dual_loop/evidential.py +122 -0
- dual_loop_controller-2.2.1/dual_loop/halting.py +359 -0
- dual_loop_controller-2.2.1/dual_loop/matrix_helper.py +161 -0
- dual_loop_controller-2.2.1/dual_loop/memory.py +202 -0
- dual_loop_controller-2.2.1/dual_loop/open_concept.py +99 -0
- dual_loop_controller-2.2.1/dual_loop/plasticity.py +183 -0
- dual_loop_controller-2.2.1/dual_loop/verification.py +627 -0
- dual_loop_controller-2.2.1/dual_loop_controller.egg-info/PKG-INFO +252 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop_controller.egg-info/SOURCES.txt +17 -1
- dual_loop_controller-2.2.1/dual_loop_controller.egg-info/requires.txt +10 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/pyproject.toml +9 -5
- dual_loop_controller-2.2.1/tests/test_episodic_self_correction.py +80 -0
- dual_loop_controller-2.2.1/tests/test_hypothesis_verification.py +100 -0
- dual_loop_controller-2.2.1/tests/test_matrix_helper.py +69 -0
- dual_loop_controller-2.2.1/tests/test_metacognitive_loop.py +175 -0
- dual_loop_controller-2.2.1/tests/test_plasticity_and_evidential.py +186 -0
- dual_loop_controller-2.2.1/tests/test_qwen_adapter.py +178 -0
- dual_loop_controller-2.2.1/tests/test_security_and_runtime.py +316 -0
- dual_loop_controller-2.2.1/tests/test_smart_brain_architecture.py +110 -0
- dual_loop_controller-2.2.1/tests/test_surprise_and_ddm.py +209 -0
- dual_loop_controller-2.0.0a3/PKG-INFO +0 -165
- dual_loop_controller-2.0.0a3/README.md +0 -136
- dual_loop_controller-2.0.0a3/dual_loop/adapters/__init__.py +0 -3
- dual_loop_controller-2.0.0a3/dual_loop/adapters/latent_adapter.py +0 -108
- dual_loop_controller-2.0.0a3/dual_loop/controller.py +0 -176
- dual_loop_controller-2.0.0a3/dual_loop/halting.py +0 -71
- dual_loop_controller-2.0.0a3/dual_loop/memory.py +0 -55
- dual_loop_controller-2.0.0a3/dual_loop_controller.egg-info/PKG-INFO +0 -165
- dual_loop_controller-2.0.0a3/dual_loop_controller.egg-info/requires.txt +0 -6
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/benchmarks/__init__.py +0 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/benchmarks/initiative_benchmark.py +0 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop/checkpoints/checkpoint_trained_dualloop.pt +0 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop_controller.egg-info/dependency_links.txt +0 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/dual_loop_controller.egg-info/top_level.txt +0 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/setup.cfg +0 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/tests/test_adapter_integration.py +0 -0
- {dual_loop_controller-2.0.0a3 → dual_loop_controller-2.2.1}/tests/test_dual_loop.py +0 -0
|
@@ -19,3 +19,10 @@ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
|
19
19
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
20
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
21
|
SOFTWARE.
|
|
22
|
+
|
|
23
|
+
---
|
|
24
|
+
|
|
25
|
+
THIRD-PARTY NOTICES:
|
|
26
|
+
This project interfaces with open-source software libraries and foundation models
|
|
27
|
+
(including Hugging Face Transformers, PyTorch, EleutherAI LM-Eval, and Qwen architectures).
|
|
28
|
+
For complete license details, copyrights, and academic citations, see ATTRIBUTION.md.
|
|
@@ -0,0 +1,252 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: dual-loop-controller
|
|
3
|
+
Version: 2.2.1
|
|
4
|
+
Summary: A hardware-aligned, manifold-preserving latent deliberation framework for Transformers
|
|
5
|
+
Author: Ch3nOff
|
|
6
|
+
License-Expression: MIT
|
|
7
|
+
Project-URL: Homepage, https://github.com/Ch3nOff/dual-loop-controller
|
|
8
|
+
Project-URL: Repository, https://github.com/Ch3nOff/dual-loop-controller.git
|
|
9
|
+
Project-URL: Bug Tracker, https://github.com/Ch3nOff/dual-loop-controller/issues
|
|
10
|
+
Keywords: deep-learning,transformers,latent-reasoning,cognitive-architecture,system-2-thinking,pytorch
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
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
|
+
Requires-Python: >=3.9
|
|
21
|
+
Description-Content-Type: text/markdown
|
|
22
|
+
License-File: LICENSE
|
|
23
|
+
Requires-Dist: torch<3.0.0,>=2.0.0
|
|
24
|
+
Requires-Dist: numpy<3.0.0,>=1.24.0
|
|
25
|
+
Provides-Extra: dev
|
|
26
|
+
Requires-Dist: build; extra == "dev"
|
|
27
|
+
Requires-Dist: twine; extra == "dev"
|
|
28
|
+
Provides-Extra: llm
|
|
29
|
+
Requires-Dist: transformers<5.0.0,>=4.40.0; extra == "llm"
|
|
30
|
+
Requires-Dist: accelerate<2.0.0,>=0.28.0; extra == "llm"
|
|
31
|
+
Dynamic: license-file
|
|
32
|
+
|
|
33
|
+
<p align="center">
|
|
34
|
+
English | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_id.md">Bahasa Indonesia</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_zh.md">简体中文</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ja.md">日本語</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ko.md">한국어</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_es.md">Español</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_fr.md">Français</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_de.md">Deutsch</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ru.md">Русский</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ar.md">العربية</a>
|
|
35
|
+
</p>
|
|
36
|
+
|
|
37
|
+
<h1 align="center">Dual-Loop Cognitive Controller</h1>
|
|
38
|
+
<h3 align="center">State-of-the-Art Latent Deliberation & Cognitive Reasoning Framework for Any Transformer Model</h3>
|
|
39
|
+
|
|
40
|
+
<p align="center">
|
|
41
|
+
<a href="https://pypi.org/project/dual-loop-controller/"><img src="https://img.shields.io/pypi/v/dual-loop-controller.svg?color=blue" alt="PyPI version"></a>
|
|
42
|
+
<a href="https://pypi.org/project/dual-loop-controller/"><img src="https://img.shields.io/pypi/pyversions/dual-loop-controller.svg" alt="Python Versions"></a>
|
|
43
|
+
<a href="https://pytorch.org/"><img src="https://img.shields.io/badge/PyTorch-2.0%2B-ee4c2c.svg" alt="PyTorch"></a>
|
|
44
|
+
<a href="https://huggingface.co/CH3NDev/dual-loop-qwen3.5-2b"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Adapter%20Weights-yellow.svg" alt="Hugging Face"></a>
|
|
45
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License"></a>
|
|
46
|
+
<a href="tests/"><img src="https://img.shields.io/badge/tests-73%20passed-brightgreen.svg" alt="Unit Tests"></a>
|
|
47
|
+
</p>
|
|
48
|
+
|
|
49
|
+
---
|
|
50
|
+
|
|
51
|
+
## What is Dual-Loop Cognitive Controller?
|
|
52
|
+
|
|
53
|
+
Standard autoregressive Transformers perform uniform $O(1)$ computation per token regardless of task complexity. While Chain-of-Thought (CoT) prompting enables multi-step reasoning, it consumes heavy output token bandwidth, creates severe serial latency, and exposes models to prompt distraction. Conversely, naive recurrent pondering suffers from **overthinking** (corrupting commonsense intuition) and **the unsupervised falsification trap** (second-guessing correct initial predictions).
|
|
54
|
+
|
|
55
|
+
**Dual-Loop Cognitive Controller** is a universal model-enhancement framework that equips **any Transformer architecture** with dual-process System 1 (intuitive) and System 2 (deliberative) reasoning:
|
|
56
|
+
|
|
57
|
+
* **Outer Loop (System 2 / Latent Deliberation)**: Executes recursive mental simulation in continuous latent space without emitting intermediate discrete tokens.
|
|
58
|
+
* **Inner Loop (System 1 / Generation)**: Decodes high-fidelity tokens conditioned on converged thought vectors.
|
|
59
|
+
* **Cognitive Matrix Helper (Tversky Elimination-by-Aspects)**: Screens candidate options in Bench 1, eliminates distractor *wrong logs*, and focuses deliberation strictly on surviving contenders in Bench 2.
|
|
60
|
+
* **Hippocampal Episodic Virtual Memory**: Stores verified reasoning traces as Settled Anchors, enabling instant ($<0.01\text{s}$) zero-compute shortcut recall.
|
|
61
|
+
* **Directional Safety Projection**: Mathematically shields confident predictions from degradation, guaranteeing **Zero Negative Drift**.
|
|
62
|
+
|
|
63
|
+
---
|
|
64
|
+
|
|
65
|
+
## Universal Compatibility: Works with Any Transformer
|
|
66
|
+
|
|
67
|
+
`dual-loop-controller` attaches seamlessly via non-invasive PyTorch forward hooks to any standard causal language model. No modifications to your underlying model weights are required:
|
|
68
|
+
|
|
69
|
+
| Model Family | Supported Architectures | Example Checkpoints |
|
|
70
|
+
| :--- | :--- | :--- |
|
|
71
|
+
| **Meta LLaMA** | LLaMA-2, LLaMA-3, LLaMA-3.1, LLaMA-3.2, CodeLlama | `meta-llama/Meta-Llama-3-8B-Instruct`, `meta-llama/Llama-3.2-3B` |
|
|
72
|
+
| **Mistral AI** | Mistral-7B, Mixtral-8x7B, Ministral | `mistralai/Mistral-7B-Instruct-v0.3`, `mistralai/Mixtral-8x7B-v0.1` |
|
|
73
|
+
| **Qwen** | Qwen-1.5, Qwen-2, Qwen-2.5, Qwen-3.5 | `Qwen/Qwen2.5-7B-Instruct`, `Qwen/Qwen3.5-2B` |
|
|
74
|
+
| **Google Gemma** | Gemma, Gemma-2 | `google/gemma-2-2b-it`, `google/gemma-2-9b-it` |
|
|
75
|
+
| **DeepSeek** | DeepSeek-V2, DeepSeek-V3, DeepSeek-R1-Distill | `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` |
|
|
76
|
+
| **Microsoft Phi**| Phi-2, Phi-3, Phi-3.5 | `microsoft/Phi-3-mini-4k-instruct` |
|
|
77
|
+
| **Generic Transformers** | GPT-2, GPT-NeoX, Falcon, Bloom, StarCoder | Any Hugging Face `PreTrainedModel` with decoder layers |
|
|
78
|
+
|
|
79
|
+
---
|
|
80
|
+
|
|
81
|
+
## Installation
|
|
82
|
+
|
|
83
|
+
Works with Python 3.9+ and [PyTorch](https://pytorch.org/get-started/locally/) 2.0+.
|
|
84
|
+
|
|
85
|
+
### With `pip`:
|
|
86
|
+
```bash
|
|
87
|
+
pip install dual-loop-controller
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
### With `uv`:
|
|
91
|
+
```bash
|
|
92
|
+
uv pip install dual-loop-controller
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
### Install with LLM dependencies (Transformers & Accelerate):
|
|
96
|
+
```bash
|
|
97
|
+
pip install "dual-loop-controller[llm]"
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
### Install from Source:
|
|
101
|
+
```bash
|
|
102
|
+
git clone https://github.com/Ch3nOff/dual-loop-controller.git
|
|
103
|
+
cd dual-loop-controller
|
|
104
|
+
pip install -e .
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
---
|
|
108
|
+
|
|
109
|
+
## Quickstart
|
|
110
|
+
|
|
111
|
+
### 1. Attach Dual-Loop to ANY Hugging Face Model in 3 Lines
|
|
112
|
+
|
|
113
|
+
You can attach the controller to **any** model family (`Llama`, `Mistral`, `Qwen`, `Gemma`, etc.) using the universal `attach_dual_loop` factory:
|
|
114
|
+
|
|
115
|
+
```python
|
|
116
|
+
import torch
|
|
117
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
118
|
+
from dual_loop import attach_dual_loop
|
|
119
|
+
|
|
120
|
+
# Step 1: Load your favorite Hugging Face model
|
|
121
|
+
model_id = "meta-llama/Meta-Llama-3-8B-Instruct" # or "mistralai/Mistral-7B-v0.3", "Qwen/Qwen2.5-7B", "google/gemma-2-9b"
|
|
122
|
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
|
123
|
+
base_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="auto")
|
|
124
|
+
|
|
125
|
+
# Step 2: Attach Dual-Loop Cognitive Controller
|
|
126
|
+
# layer_idx defaults to the optimal midpoint layer automatically
|
|
127
|
+
model = attach_dual_loop(base_model, k_steps=2)
|
|
128
|
+
|
|
129
|
+
# Step 3: Run inference with latent System 2 pondering
|
|
130
|
+
prompt = "Question: Under an inverted buoyancy physics law, denser objects float. If lead and cork drop in water, which floats?\nAnswer:"
|
|
131
|
+
inputs = tokenizer(prompt, return_tensors="pt").to(base_model.device)
|
|
132
|
+
|
|
133
|
+
# Model deliberates in latent space before generating output tokens
|
|
134
|
+
output = model.generate(**inputs, max_new_tokens=64)
|
|
135
|
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
|
136
|
+
```
|
|
137
|
+
|
|
138
|
+
---
|
|
139
|
+
|
|
140
|
+
### 2. Multi-Choice Solving with 2-Bench Cognitive Matrix Helper
|
|
141
|
+
|
|
142
|
+
For challenging multiple-choice tasks (medical diagnosis, science QA, legal entailment), use `CognitiveMatrixHelper` to eliminate distractor options (*wrong logs*) and focus System 2 attention on surviving contenders:
|
|
143
|
+
|
|
144
|
+
```python
|
|
145
|
+
import numpy as np
|
|
146
|
+
from dual_loop import CognitiveMatrixHelper
|
|
147
|
+
|
|
148
|
+
# Initialize helper with adaptive distractor cutoff
|
|
149
|
+
matrix_helper = CognitiveMatrixHelper(elimination_threshold=0.12, min_survivors=2)
|
|
150
|
+
|
|
151
|
+
# Bench 1: Raw candidate scores from base model
|
|
152
|
+
scores_bench1 = [-9.1488, -9.2891, -9.5007, -11.0977, -10.9492]
|
|
153
|
+
labels = ["D", "E", "F", "A", "B"]
|
|
154
|
+
|
|
155
|
+
# Step 1: Populate Cognitive Evidence Matrix & prune distractors
|
|
156
|
+
matrix = matrix_helper.build_evidence_matrix(scores_bench1, labels=labels)
|
|
157
|
+
print("Pruned Distractor Logs :", matrix["eliminated_labels"]) # -> ['A', 'B'] (Noise eliminated)
|
|
158
|
+
print("Surviving Contenders :", matrix["survivor_labels"]) # -> ['D', 'E', 'F'] (Viable dilemma)
|
|
159
|
+
|
|
160
|
+
# Bench 2: System 2 deliberates strictly on surviving candidates [D, E, F]
|
|
161
|
+
scores_delib_survivors = [-6.9465, -5.8747, -4.4858]
|
|
162
|
+
|
|
163
|
+
# Step 2: Fuse scores (eliminated distractors are locked to -infinity)
|
|
164
|
+
final_scores = matrix_helper.fuse_scores(
|
|
165
|
+
scores_base=scores_bench1,
|
|
166
|
+
scores_delib_survivors=scores_delib_survivors,
|
|
167
|
+
survivor_indices=matrix["survivors"],
|
|
168
|
+
lambda_delib=0.85
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
best_idx = np.argmax(final_scores)
|
|
172
|
+
print("Final Rescued Decision :", labels[best_idx]) # -> 'F' (Correct Answer!)
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
### 3. Accelerated Reasoning with Hippocampal Virtual Memory
|
|
178
|
+
|
|
179
|
+
Enable human-like memory consolidation where familiar queries bypass deliberation with **instant $<0.01\text{s}$ retrieval (3,146x speedup)**:
|
|
180
|
+
|
|
181
|
+
```python
|
|
182
|
+
import torch
|
|
183
|
+
from dual_loop import CognitiveWorkingMemory
|
|
184
|
+
from dual_loop.memory import EpisodicMemoryBuffer
|
|
185
|
+
|
|
186
|
+
# Initialize continuous key-value memory bank
|
|
187
|
+
memory = EpisodicMemoryBuffer(d_model=2048, capacity=512, sim_threshold=0.95)
|
|
188
|
+
|
|
189
|
+
# Store verified reasoning trace
|
|
190
|
+
query_vector = torch.randn(1, 2048)
|
|
191
|
+
thought_vector = torch.randn(1, 2048)
|
|
192
|
+
|
|
193
|
+
memory.store(
|
|
194
|
+
key=query_vector,
|
|
195
|
+
thought=thought_vector,
|
|
196
|
+
margin=0.45,
|
|
197
|
+
meta={"answer": "F", "task": "colored_objects"},
|
|
198
|
+
is_settled=True
|
|
199
|
+
)
|
|
200
|
+
|
|
201
|
+
# Recall instantly on subsequent encounters (Zero FLOPs, Zero Token Waste)
|
|
202
|
+
match = memory.recall_settled(query_vector, sim_threshold=0.95)
|
|
203
|
+
if match:
|
|
204
|
+
print("Instant Memory Recall:", match["metadata"]["answer"])
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## Why Should I Use Dual-Loop Controller?
|
|
210
|
+
|
|
211
|
+
* **Universal Compatibility**: Works with Llama, Mistral, Qwen, Gemma, DeepSeek, and any causal LM.
|
|
212
|
+
* **Zero Output Token Waste**: Deliberates in continuous latent thought space instead of generating hundreds of CoT scratchpad tokens.
|
|
213
|
+
* **Distractor Elimination (Amos Tversky EBA)**: Solves multi-choice attention dilution by filtering superficial distractor options.
|
|
214
|
+
* **Zero Negative Drift Guarantee**: Directional Safety Projection ensures confident intuitive answers are never degraded.
|
|
215
|
+
* **Hardware-Aligned & Cache-Friendly**: Cognitive Working Memory (CWM) fits directly inside GPU SRAM / L2 cache, eliminating redundant KV-cache lookups.
|
|
216
|
+
* **100% Offline & Private**: Runs entirely locally on your machine or server. Zero external API bills, zero data leakage.
|
|
217
|
+
|
|
218
|
+
---
|
|
219
|
+
|
|
220
|
+
## When Shouldn't I Use Dual-Loop Controller?
|
|
221
|
+
|
|
222
|
+
* **Pure Embedding Models**: Dual-Loop is designed for generative causal autoregressive decoders, not encoder-only models (like BERT) without generation heads.
|
|
223
|
+
* **Ultra-Low Latency Sub-5ms Audio Streams**: Latent pondering adds a small computational budget ($K$ iterations) at an intermediate layer, suited for high-accuracy reasoning rather than hard real-time streaming audio.
|
|
224
|
+
|
|
225
|
+
---
|
|
226
|
+
|
|
227
|
+
## Benchmark Suite & Empirical Research
|
|
228
|
+
|
|
229
|
+
For comprehensive benchmarks (including ARC-Challenge, Big-Bench Hard, 20-Task Macro Suites, and procedural stress tests), please consult [`BENCHMARKS.md`](BENCHMARKS.md) and [`eval_results/`](eval_results/).
|
|
230
|
+
|
|
231
|
+
---
|
|
232
|
+
|
|
233
|
+
## Citation
|
|
234
|
+
|
|
235
|
+
If you use `dual-loop-controller` in your research or production systems, please cite:
|
|
236
|
+
|
|
237
|
+
```bibtex
|
|
238
|
+
@software{chen2026dualloop,
|
|
239
|
+
author = {Matthew Chen and Contributors},
|
|
240
|
+
title = {Dual-Loop Cognitive Controller: Hardware-Aligned Latent Deliberation & Memory Architecture for Transformers},
|
|
241
|
+
year = {2026},
|
|
242
|
+
publisher = {PyPI},
|
|
243
|
+
version = {2.2.1},
|
|
244
|
+
url = {https://github.com/Ch3nOff/dual-loop-controller}
|
|
245
|
+
}
|
|
246
|
+
```
|
|
247
|
+
|
|
248
|
+
---
|
|
249
|
+
|
|
250
|
+
## License
|
|
251
|
+
|
|
252
|
+
This project is licensed under the [MIT License](LICENSE).
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
<p align="center">
|
|
2
|
+
English | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_id.md">Bahasa Indonesia</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_zh.md">简体中文</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ja.md">日本語</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ko.md">한국어</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_es.md">Español</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_fr.md">Français</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_de.md">Deutsch</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ru.md">Русский</a> | <a href="https://github.com/Ch3nOff/dual-loop-controller/blob/main/docs/README_ar.md">العربية</a>
|
|
3
|
+
</p>
|
|
4
|
+
|
|
5
|
+
<h1 align="center">Dual-Loop Cognitive Controller</h1>
|
|
6
|
+
<h3 align="center">State-of-the-Art Latent Deliberation & Cognitive Reasoning Framework for Any Transformer Model</h3>
|
|
7
|
+
|
|
8
|
+
<p align="center">
|
|
9
|
+
<a href="https://pypi.org/project/dual-loop-controller/"><img src="https://img.shields.io/pypi/v/dual-loop-controller.svg?color=blue" alt="PyPI version"></a>
|
|
10
|
+
<a href="https://pypi.org/project/dual-loop-controller/"><img src="https://img.shields.io/pypi/pyversions/dual-loop-controller.svg" alt="Python Versions"></a>
|
|
11
|
+
<a href="https://pytorch.org/"><img src="https://img.shields.io/badge/PyTorch-2.0%2B-ee4c2c.svg" alt="PyTorch"></a>
|
|
12
|
+
<a href="https://huggingface.co/CH3NDev/dual-loop-qwen3.5-2b"><img src="https://img.shields.io/badge/%F0%9F%A4%97%20Hugging%20Face-Adapter%20Weights-yellow.svg" alt="Hugging Face"></a>
|
|
13
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-green.svg" alt="License"></a>
|
|
14
|
+
<a href="tests/"><img src="https://img.shields.io/badge/tests-73%20passed-brightgreen.svg" alt="Unit Tests"></a>
|
|
15
|
+
</p>
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## What is Dual-Loop Cognitive Controller?
|
|
20
|
+
|
|
21
|
+
Standard autoregressive Transformers perform uniform $O(1)$ computation per token regardless of task complexity. While Chain-of-Thought (CoT) prompting enables multi-step reasoning, it consumes heavy output token bandwidth, creates severe serial latency, and exposes models to prompt distraction. Conversely, naive recurrent pondering suffers from **overthinking** (corrupting commonsense intuition) and **the unsupervised falsification trap** (second-guessing correct initial predictions).
|
|
22
|
+
|
|
23
|
+
**Dual-Loop Cognitive Controller** is a universal model-enhancement framework that equips **any Transformer architecture** with dual-process System 1 (intuitive) and System 2 (deliberative) reasoning:
|
|
24
|
+
|
|
25
|
+
* **Outer Loop (System 2 / Latent Deliberation)**: Executes recursive mental simulation in continuous latent space without emitting intermediate discrete tokens.
|
|
26
|
+
* **Inner Loop (System 1 / Generation)**: Decodes high-fidelity tokens conditioned on converged thought vectors.
|
|
27
|
+
* **Cognitive Matrix Helper (Tversky Elimination-by-Aspects)**: Screens candidate options in Bench 1, eliminates distractor *wrong logs*, and focuses deliberation strictly on surviving contenders in Bench 2.
|
|
28
|
+
* **Hippocampal Episodic Virtual Memory**: Stores verified reasoning traces as Settled Anchors, enabling instant ($<0.01\text{s}$) zero-compute shortcut recall.
|
|
29
|
+
* **Directional Safety Projection**: Mathematically shields confident predictions from degradation, guaranteeing **Zero Negative Drift**.
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## Universal Compatibility: Works with Any Transformer
|
|
34
|
+
|
|
35
|
+
`dual-loop-controller` attaches seamlessly via non-invasive PyTorch forward hooks to any standard causal language model. No modifications to your underlying model weights are required:
|
|
36
|
+
|
|
37
|
+
| Model Family | Supported Architectures | Example Checkpoints |
|
|
38
|
+
| :--- | :--- | :--- |
|
|
39
|
+
| **Meta LLaMA** | LLaMA-2, LLaMA-3, LLaMA-3.1, LLaMA-3.2, CodeLlama | `meta-llama/Meta-Llama-3-8B-Instruct`, `meta-llama/Llama-3.2-3B` |
|
|
40
|
+
| **Mistral AI** | Mistral-7B, Mixtral-8x7B, Ministral | `mistralai/Mistral-7B-Instruct-v0.3`, `mistralai/Mixtral-8x7B-v0.1` |
|
|
41
|
+
| **Qwen** | Qwen-1.5, Qwen-2, Qwen-2.5, Qwen-3.5 | `Qwen/Qwen2.5-7B-Instruct`, `Qwen/Qwen3.5-2B` |
|
|
42
|
+
| **Google Gemma** | Gemma, Gemma-2 | `google/gemma-2-2b-it`, `google/gemma-2-9b-it` |
|
|
43
|
+
| **DeepSeek** | DeepSeek-V2, DeepSeek-V3, DeepSeek-R1-Distill | `deepseek-ai/DeepSeek-R1-Distill-Qwen-1.5B` |
|
|
44
|
+
| **Microsoft Phi**| Phi-2, Phi-3, Phi-3.5 | `microsoft/Phi-3-mini-4k-instruct` |
|
|
45
|
+
| **Generic Transformers** | GPT-2, GPT-NeoX, Falcon, Bloom, StarCoder | Any Hugging Face `PreTrainedModel` with decoder layers |
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## Installation
|
|
50
|
+
|
|
51
|
+
Works with Python 3.9+ and [PyTorch](https://pytorch.org/get-started/locally/) 2.0+.
|
|
52
|
+
|
|
53
|
+
### With `pip`:
|
|
54
|
+
```bash
|
|
55
|
+
pip install dual-loop-controller
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
### With `uv`:
|
|
59
|
+
```bash
|
|
60
|
+
uv pip install dual-loop-controller
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
### Install with LLM dependencies (Transformers & Accelerate):
|
|
64
|
+
```bash
|
|
65
|
+
pip install "dual-loop-controller[llm]"
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
### Install from Source:
|
|
69
|
+
```bash
|
|
70
|
+
git clone https://github.com/Ch3nOff/dual-loop-controller.git
|
|
71
|
+
cd dual-loop-controller
|
|
72
|
+
pip install -e .
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## Quickstart
|
|
78
|
+
|
|
79
|
+
### 1. Attach Dual-Loop to ANY Hugging Face Model in 3 Lines
|
|
80
|
+
|
|
81
|
+
You can attach the controller to **any** model family (`Llama`, `Mistral`, `Qwen`, `Gemma`, etc.) using the universal `attach_dual_loop` factory:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
import torch
|
|
85
|
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
|
86
|
+
from dual_loop import attach_dual_loop
|
|
87
|
+
|
|
88
|
+
# Step 1: Load your favorite Hugging Face model
|
|
89
|
+
model_id = "meta-llama/Meta-Llama-3-8B-Instruct" # or "mistralai/Mistral-7B-v0.3", "Qwen/Qwen2.5-7B", "google/gemma-2-9b"
|
|
90
|
+
tokenizer = AutoTokenizer.from_pretrained(model_id)
|
|
91
|
+
base_model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype=torch.bfloat16, device_map="auto")
|
|
92
|
+
|
|
93
|
+
# Step 2: Attach Dual-Loop Cognitive Controller
|
|
94
|
+
# layer_idx defaults to the optimal midpoint layer automatically
|
|
95
|
+
model = attach_dual_loop(base_model, k_steps=2)
|
|
96
|
+
|
|
97
|
+
# Step 3: Run inference with latent System 2 pondering
|
|
98
|
+
prompt = "Question: Under an inverted buoyancy physics law, denser objects float. If lead and cork drop in water, which floats?\nAnswer:"
|
|
99
|
+
inputs = tokenizer(prompt, return_tensors="pt").to(base_model.device)
|
|
100
|
+
|
|
101
|
+
# Model deliberates in latent space before generating output tokens
|
|
102
|
+
output = model.generate(**inputs, max_new_tokens=64)
|
|
103
|
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
---
|
|
107
|
+
|
|
108
|
+
### 2. Multi-Choice Solving with 2-Bench Cognitive Matrix Helper
|
|
109
|
+
|
|
110
|
+
For challenging multiple-choice tasks (medical diagnosis, science QA, legal entailment), use `CognitiveMatrixHelper` to eliminate distractor options (*wrong logs*) and focus System 2 attention on surviving contenders:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
import numpy as np
|
|
114
|
+
from dual_loop import CognitiveMatrixHelper
|
|
115
|
+
|
|
116
|
+
# Initialize helper with adaptive distractor cutoff
|
|
117
|
+
matrix_helper = CognitiveMatrixHelper(elimination_threshold=0.12, min_survivors=2)
|
|
118
|
+
|
|
119
|
+
# Bench 1: Raw candidate scores from base model
|
|
120
|
+
scores_bench1 = [-9.1488, -9.2891, -9.5007, -11.0977, -10.9492]
|
|
121
|
+
labels = ["D", "E", "F", "A", "B"]
|
|
122
|
+
|
|
123
|
+
# Step 1: Populate Cognitive Evidence Matrix & prune distractors
|
|
124
|
+
matrix = matrix_helper.build_evidence_matrix(scores_bench1, labels=labels)
|
|
125
|
+
print("Pruned Distractor Logs :", matrix["eliminated_labels"]) # -> ['A', 'B'] (Noise eliminated)
|
|
126
|
+
print("Surviving Contenders :", matrix["survivor_labels"]) # -> ['D', 'E', 'F'] (Viable dilemma)
|
|
127
|
+
|
|
128
|
+
# Bench 2: System 2 deliberates strictly on surviving candidates [D, E, F]
|
|
129
|
+
scores_delib_survivors = [-6.9465, -5.8747, -4.4858]
|
|
130
|
+
|
|
131
|
+
# Step 2: Fuse scores (eliminated distractors are locked to -infinity)
|
|
132
|
+
final_scores = matrix_helper.fuse_scores(
|
|
133
|
+
scores_base=scores_bench1,
|
|
134
|
+
scores_delib_survivors=scores_delib_survivors,
|
|
135
|
+
survivor_indices=matrix["survivors"],
|
|
136
|
+
lambda_delib=0.85
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
best_idx = np.argmax(final_scores)
|
|
140
|
+
print("Final Rescued Decision :", labels[best_idx]) # -> 'F' (Correct Answer!)
|
|
141
|
+
```
|
|
142
|
+
|
|
143
|
+
---
|
|
144
|
+
|
|
145
|
+
### 3. Accelerated Reasoning with Hippocampal Virtual Memory
|
|
146
|
+
|
|
147
|
+
Enable human-like memory consolidation where familiar queries bypass deliberation with **instant $<0.01\text{s}$ retrieval (3,146x speedup)**:
|
|
148
|
+
|
|
149
|
+
```python
|
|
150
|
+
import torch
|
|
151
|
+
from dual_loop import CognitiveWorkingMemory
|
|
152
|
+
from dual_loop.memory import EpisodicMemoryBuffer
|
|
153
|
+
|
|
154
|
+
# Initialize continuous key-value memory bank
|
|
155
|
+
memory = EpisodicMemoryBuffer(d_model=2048, capacity=512, sim_threshold=0.95)
|
|
156
|
+
|
|
157
|
+
# Store verified reasoning trace
|
|
158
|
+
query_vector = torch.randn(1, 2048)
|
|
159
|
+
thought_vector = torch.randn(1, 2048)
|
|
160
|
+
|
|
161
|
+
memory.store(
|
|
162
|
+
key=query_vector,
|
|
163
|
+
thought=thought_vector,
|
|
164
|
+
margin=0.45,
|
|
165
|
+
meta={"answer": "F", "task": "colored_objects"},
|
|
166
|
+
is_settled=True
|
|
167
|
+
)
|
|
168
|
+
|
|
169
|
+
# Recall instantly on subsequent encounters (Zero FLOPs, Zero Token Waste)
|
|
170
|
+
match = memory.recall_settled(query_vector, sim_threshold=0.95)
|
|
171
|
+
if match:
|
|
172
|
+
print("Instant Memory Recall:", match["metadata"]["answer"])
|
|
173
|
+
```
|
|
174
|
+
|
|
175
|
+
---
|
|
176
|
+
|
|
177
|
+
## Why Should I Use Dual-Loop Controller?
|
|
178
|
+
|
|
179
|
+
* **Universal Compatibility**: Works with Llama, Mistral, Qwen, Gemma, DeepSeek, and any causal LM.
|
|
180
|
+
* **Zero Output Token Waste**: Deliberates in continuous latent thought space instead of generating hundreds of CoT scratchpad tokens.
|
|
181
|
+
* **Distractor Elimination (Amos Tversky EBA)**: Solves multi-choice attention dilution by filtering superficial distractor options.
|
|
182
|
+
* **Zero Negative Drift Guarantee**: Directional Safety Projection ensures confident intuitive answers are never degraded.
|
|
183
|
+
* **Hardware-Aligned & Cache-Friendly**: Cognitive Working Memory (CWM) fits directly inside GPU SRAM / L2 cache, eliminating redundant KV-cache lookups.
|
|
184
|
+
* **100% Offline & Private**: Runs entirely locally on your machine or server. Zero external API bills, zero data leakage.
|
|
185
|
+
|
|
186
|
+
---
|
|
187
|
+
|
|
188
|
+
## When Shouldn't I Use Dual-Loop Controller?
|
|
189
|
+
|
|
190
|
+
* **Pure Embedding Models**: Dual-Loop is designed for generative causal autoregressive decoders, not encoder-only models (like BERT) without generation heads.
|
|
191
|
+
* **Ultra-Low Latency Sub-5ms Audio Streams**: Latent pondering adds a small computational budget ($K$ iterations) at an intermediate layer, suited for high-accuracy reasoning rather than hard real-time streaming audio.
|
|
192
|
+
|
|
193
|
+
---
|
|
194
|
+
|
|
195
|
+
## Benchmark Suite & Empirical Research
|
|
196
|
+
|
|
197
|
+
For comprehensive benchmarks (including ARC-Challenge, Big-Bench Hard, 20-Task Macro Suites, and procedural stress tests), please consult [`BENCHMARKS.md`](BENCHMARKS.md) and [`eval_results/`](eval_results/).
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## Citation
|
|
202
|
+
|
|
203
|
+
If you use `dual-loop-controller` in your research or production systems, please cite:
|
|
204
|
+
|
|
205
|
+
```bibtex
|
|
206
|
+
@software{chen2026dualloop,
|
|
207
|
+
author = {Matthew Chen and Contributors},
|
|
208
|
+
title = {Dual-Loop Cognitive Controller: Hardware-Aligned Latent Deliberation & Memory Architecture for Transformers},
|
|
209
|
+
year = {2026},
|
|
210
|
+
publisher = {PyPI},
|
|
211
|
+
version = {2.2.1},
|
|
212
|
+
url = {https://github.com/Ch3nOff/dual-loop-controller}
|
|
213
|
+
}
|
|
214
|
+
```
|
|
215
|
+
|
|
216
|
+
---
|
|
217
|
+
|
|
218
|
+
## License
|
|
219
|
+
|
|
220
|
+
This project is licensed under the [MIT License](LICENSE).
|
|
@@ -6,16 +6,34 @@ for Transformer architectures.
|
|
|
6
6
|
"""
|
|
7
7
|
|
|
8
8
|
from .memory import CognitiveWorkingMemory
|
|
9
|
-
from .halting import EntropyHaltingUnit
|
|
10
|
-
from .controller import RecurrentLatentController, TopKCapacityCrossAttention
|
|
9
|
+
from .halting import EntropyHaltingUnit, LearnedHaltingGate, DriftDiffusionHalting
|
|
10
|
+
from .controller import RecurrentLatentController, TopKCapacityCrossAttention, LatentCritiqueRefinementUnit
|
|
11
|
+
from .plasticity import PlasticFastWeightUnit
|
|
12
|
+
from .evidential import EvidentialEpistemicGate
|
|
13
|
+
from .open_concept import OpenConceptSynthesizer
|
|
14
|
+
from .verification import (
|
|
15
|
+
HypothesisVerificationGate,
|
|
16
|
+
UncertaintySurpriseGate,
|
|
17
|
+
ContrastiveEvidenceAccumulator,
|
|
18
|
+
DirectionalSafetyProjection,
|
|
19
|
+
AdaptiveSurpriseThreshold
|
|
20
|
+
)
|
|
21
|
+
from .matrix_helper import CognitiveMatrixHelper
|
|
11
22
|
from .decoder import DualLoopTransformer
|
|
12
23
|
from .adapters.latent_adapter import LatentDeliberationAdapter
|
|
24
|
+
from .adapters.qwen_adapter import (
|
|
25
|
+
DualLoopQwenModel,
|
|
26
|
+
DualLoopTransformerModel,
|
|
27
|
+
attach_dual_loop_to_qwen,
|
|
28
|
+
attach_dual_loop,
|
|
29
|
+
attach_dual_loop_to_model
|
|
30
|
+
)
|
|
13
31
|
|
|
14
32
|
import os
|
|
15
33
|
import torch
|
|
16
34
|
from typing import Optional
|
|
17
35
|
|
|
18
|
-
__version__ = "2.
|
|
36
|
+
__version__ = "2.2.1"
|
|
19
37
|
|
|
20
38
|
def get_default_checkpoint_path() -> Optional[str]:
|
|
21
39
|
"""
|
|
@@ -57,10 +75,27 @@ def load_trained_checkpoint(model: Optional[DualLoopTransformer] = None, checkpo
|
|
|
57
75
|
__all__ = [
|
|
58
76
|
"CognitiveWorkingMemory",
|
|
59
77
|
"EntropyHaltingUnit",
|
|
78
|
+
"LearnedHaltingGate",
|
|
79
|
+
"DriftDiffusionHalting",
|
|
60
80
|
"RecurrentLatentController",
|
|
61
81
|
"TopKCapacityCrossAttention",
|
|
82
|
+
"LatentCritiqueRefinementUnit",
|
|
83
|
+
"PlasticFastWeightUnit",
|
|
84
|
+
"EvidentialEpistemicGate",
|
|
85
|
+
"OpenConceptSynthesizer",
|
|
86
|
+
"HypothesisVerificationGate",
|
|
87
|
+
"UncertaintySurpriseGate",
|
|
88
|
+
"ContrastiveEvidenceAccumulator",
|
|
89
|
+
"DirectionalSafetyProjection",
|
|
90
|
+
"AdaptiveSurpriseThreshold",
|
|
91
|
+
"CognitiveMatrixHelper",
|
|
62
92
|
"DualLoopTransformer",
|
|
63
93
|
"LatentDeliberationAdapter",
|
|
94
|
+
"DualLoopQwenModel",
|
|
95
|
+
"DualLoopTransformerModel",
|
|
96
|
+
"attach_dual_loop_to_qwen",
|
|
97
|
+
"attach_dual_loop",
|
|
98
|
+
"attach_dual_loop_to_model",
|
|
64
99
|
"get_default_checkpoint_path",
|
|
65
100
|
"load_trained_checkpoint",
|
|
66
101
|
]
|