LoganResearch commited on
Commit
f65c363
Β·
verified Β·
1 Parent(s): f39a382

Upload ubermenschetien_heaven_engine_dense.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. ubermenschetien_heaven_engine_dense.py +1088 -0
ubermenschetien_heaven_engine_dense.py ADDED
@@ -0,0 +1,1088 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ UBERMENSCHETIEN HEAVEN ENGINE + DENSE CONDENSATOR + CF-HoT MULTI-HEAD COGNITIVE CONTROL
4
+ ----------------------------------------------------------------------------------------
5
+ Integration: Hermes-3 base + DENSE CONDENSATOR checkpoint + CF-HoT for behavioral control
6
+
7
+ DENSE: Trained on Nietzsche-level dense examples (step 100, Density: 28.5, Reward: 0.624)
8
+ CF-HoT Heads:
9
+ - Repetition: 125x separation (PRODUCTION)
10
+ - Verbosity: 2.1x separation (USABLE)
11
+ - Hedging: 1.5x separation (CONTRIBUTING)
12
+
13
+ "An 8B that speaks like compressed wisdom"
14
+ """
15
+
16
+ import os
17
+ import sys
18
+ import json
19
+ import time
20
+ import shutil
21
+ import subprocess
22
+ import traceback
23
+ import random
24
+ import math
25
+ import statistics
26
+ import re
27
+ from datetime import datetime
28
+ from typing import List, Dict, Any, Optional, Tuple
29
+
30
+ import torch
31
+ import torch.nn as nn
32
+ import torch.nn.functional as F
33
+
34
+ # === PATHS ===
35
+ ROOT = os.path.dirname(os.path.abspath(__file__))
36
+ DATA_DIR = os.path.join(ROOT, "data")
37
+ SCRIPT_DIR = os.path.join(ROOT, "scripts")
38
+ RUN_DIR = os.path.join(ROOT, "runs")
39
+ LHT_DIR = os.path.join(ROOT, "lht")
40
+
41
+ # Model paths
42
+ MODEL_PATH = "/mnt/nvme2/ubermesnchetien4/models/merged-final-v5"
43
+
44
+ # DENSE CONDENSATOR checkpoint (the key addition!)
45
+ DENSE_CHECKPOINT = os.path.join(ROOT, "dense_checkpoints_v2/step_100")
46
+
47
+ # CF-HoT paths (for runtime cognitive control)
48
+ CFHOT_CHECKPOINT = os.path.join(ROOT, "results/cfhot_risk_v2/ckpt_5000")
49
+ MULTI_HEAD_DIR = os.path.join(ROOT, "results/multi_head_v2")
50
+
51
+ for path in [DATA_DIR, SCRIPT_DIR, RUN_DIR, LHT_DIR]:
52
+ os.makedirs(path, exist_ok=True)
53
+
54
+ # === OPTIONAL IMPORTS ===
55
+ VOICE_OK = False
56
+ try:
57
+ import pyttsx3
58
+ TTS = pyttsx3.init()
59
+ VOICE_OK = True
60
+ except:
61
+ pass
62
+
63
+ VECTOR_OK = False
64
+ try:
65
+ import chromadb
66
+ from sentence_transformers import SentenceTransformer
67
+ EMBED_MODEL = os.environ.get("UBERMENCHETIEN_EMBED_MODEL", "all-MiniLM-L6-v2")
68
+ _client = chromadb.Client()
69
+ _collection = _client.get_or_create_collection("ubermenschetien_memory")
70
+ _embedder = SentenceTransformer(EMBED_MODEL)
71
+ VECTOR_OK = True
72
+ except:
73
+ pass
74
+
75
+ # === LHT IMPORT ===
76
+ LHT_OK = False
77
+ try:
78
+ from lht import LieHolonomyTransformer, LHTConfig, WaypointDetector
79
+ LHT_OK = True
80
+ print("[lht] Lie-Holonomy modules loaded")
81
+ except ImportError:
82
+ print("[lht] Not available - running without geometric reasoning")
83
+
84
+ # === PEFT IMPORT ===
85
+ PEFT_OK = False
86
+ try:
87
+ from peft import PeftModel
88
+ PEFT_OK = True
89
+ except ImportError:
90
+ print("[warning] PEFT not installed")
91
+
92
+
93
+ # ==============================================================================
94
+ # CF-HoT MULTI-HEAD PREDICTOR
95
+ # ==============================================================================
96
+ class MultiHeadPredictor(nn.Module):
97
+ """
98
+ Multi-head cognitive control predictor.
99
+ Shared fiber projections with separate heads for each behavioral pattern.
100
+ """
101
+ def __init__(self, d_model: int, n_layers: int, d_fiber: int = 16, d_control: int = 64):
102
+ super().__init__()
103
+ self.d_model = d_model
104
+ self.n_layers = n_layers
105
+ self.d_fiber = d_fiber
106
+
107
+ # Shared fiber projections (frozen from repetition training)
108
+ self.fiber_projs = nn.ModuleList([
109
+ nn.Linear(d_model, d_fiber, bias=False) for _ in range(n_layers)
110
+ ])
111
+ self.layer_weights = nn.Parameter(torch.ones(n_layers) / n_layers)
112
+
113
+ # Individual heads for each behavior
114
+ self.heads = nn.ModuleDict({
115
+ 'repetition': self._make_head(d_fiber, d_control),
116
+ 'hedging': self._make_head(d_fiber, d_control),
117
+ 'verbosity': self._make_head(d_fiber, d_control),
118
+ })
119
+
120
+ self.loaded_heads = set()
121
+
122
+ def _make_head(self, d_fiber, d_control):
123
+ return nn.Sequential(
124
+ nn.Linear(d_fiber, d_control), nn.GELU(),
125
+ nn.Linear(d_control, d_control), nn.GELU(),
126
+ nn.Linear(d_control, 1)
127
+ )
128
+
129
+ def get_all_risks(self, hidden_states: List[torch.Tensor]) -> Dict[str, torch.Tensor]:
130
+ """Get risk scores from ALL loaded heads in a single pass."""
131
+ fibers = [proj(h.float()) for proj, h in zip(self.fiber_projs, hidden_states)]
132
+ weights = F.softmax(self.layer_weights[:len(fibers)], dim=0)
133
+ aggregated = sum(w * f for w, f in zip(weights, fibers))
134
+
135
+ risks = {}
136
+ for head_name in self.loaded_heads:
137
+ logits = self.heads[head_name](aggregated).squeeze(-1)
138
+ risks[head_name] = torch.sigmoid(logits)
139
+
140
+ return risks
141
+
142
+ def load_head(self, head_name: str, checkpoint_path: str):
143
+ """Load a trained head from checkpoint."""
144
+ if not os.path.exists(checkpoint_path):
145
+ print(f"[cf-hot] WARNING: Checkpoint not found: {checkpoint_path}")
146
+ return False
147
+
148
+ ckpt = torch.load(checkpoint_path, weights_only=False, map_location='cpu')
149
+ self.heads[head_name].load_state_dict(ckpt['head_state'])
150
+ self.loaded_heads.add(head_name)
151
+
152
+ sep = ckpt.get('result', {}).get('separation', 0)
153
+ print(f"[cf-hot] Loaded {head_name} head (separation: {sep:.1f}x)")
154
+ return True
155
+
156
+
157
+ # ==============================================================================
158
+ # CONFIG
159
+ # ==============================================================================
160
+ class Config:
161
+ # UPDATED: Dense-focused system prompt
162
+ system = ("Übermenschetien Dense Engine: Compressed wisdom, Nietzschean clarity. "
163
+ "Every word chosen, no filler. Soviet cybernetic rigor + Lie-Holonomy geometric reasoning "
164
+ "+ CF-HoT cognitive control. Speak like ancient oracles who charge per syllable.")
165
+
166
+ # UPDATED: Slightly lower temperature for more focused dense output
167
+ temperature = 0.85
168
+ top_p = 0.9
169
+ repetition_penalty = 1.1
170
+ max_new_tokens = 512 # Allow longer responses for detailed-but-dense
171
+
172
+ use_voice = False
173
+ use_vector_memory = VECTOR_OK
174
+ use_lht_reasoning = LHT_OK
175
+ use_cfhot = True
176
+ use_dense = True # NEW: Toggle for dense checkpoint
177
+ autonomy = False
178
+ reflect_every = 3
179
+ lht_consistency_threshold = 0.5
180
+
181
+ # CF-HoT thresholds - UPDATED: More aggressive for density
182
+ cfhot_repetition_threshold = 0.6 # Lower = more aggressive
183
+ cfhot_hedging_threshold = 0.5
184
+ cfhot_verbosity_threshold = 0.55
185
+
186
+ # CF-HoT penalties - UPDATED: Stronger suppression
187
+ cfhot_repetition_penalty = 6.0
188
+ cfhot_hedging_penalty = 4.0
189
+ cfhot_verbosity_penalty = 3.0
190
+
191
+ @staticmethod
192
+ def toggle(name: str):
193
+ if not hasattr(Config, name):
194
+ return f"[config] no such flag: {name}"
195
+ val = getattr(Config, name)
196
+ if isinstance(val, bool):
197
+ setattr(Config, name, not val)
198
+ return f"[config] {name} β†’ {getattr(Config, name)}"
199
+ return f"[config] {name} not boolean; current={val}"
200
+
201
+
202
+ # ==============================================================================
203
+ # STATE & MEMORY
204
+ # ==============================================================================
205
+ class Store:
206
+ state_path = f"{RUN_DIR}/state.json"
207
+ mem_path = f"{RUN_DIR}/memory.jsonl"
208
+ goals_path = f"{RUN_DIR}/goals.json"
209
+
210
+ state = {
211
+ "self": "I am Ubermenschetien Dense Engine β€” compressed wisdom through disciplined creation.",
212
+ "turn": 0,
213
+ "reasoning_consistency": [],
214
+ "cfhot_interventions": {"repetition": 0, "hedging": 0, "verbosity": 0},
215
+ "density_scores": [] # NEW: Track density over time
216
+ }
217
+ goals: List[str] = []
218
+
219
+ @classmethod
220
+ def load(cls):
221
+ if os.path.exists(cls.state_path):
222
+ cls.state = json.load(open(cls.state_path))
223
+ # Ensure new fields exist
224
+ if "cfhot_interventions" not in cls.state:
225
+ cls.state["cfhot_interventions"] = {"repetition": 0, "hedging": 0, "verbosity": 0}
226
+ if "density_scores" not in cls.state:
227
+ cls.state["density_scores"] = []
228
+ if os.path.exists(cls.goals_path):
229
+ cls.goals = json.load(open(cls.goals_path))
230
+
231
+ @classmethod
232
+ def save(cls):
233
+ json.dump(cls.state, open(cls.state_path, "w"), indent=2)
234
+ json.dump(cls.goals, open(cls.goals_path, "w"), indent=2)
235
+
236
+ @classmethod
237
+ def log_mem(cls, kind: str, payload: Any):
238
+ rec = {"ts": datetime.now().isoformat(timespec="seconds"),
239
+ "kind": kind, "data": payload}
240
+ with open(cls.mem_path, "a") as f:
241
+ f.write(json.dumps(rec, ensure_ascii=False) + "\n")
242
+ if Config.use_vector_memory and VECTOR_OK:
243
+ text = f"{kind}: {json.dumps(payload, ensure_ascii=False)}"
244
+ vec = _embedder.encode([text])[0].tolist()
245
+ _collection.add(documents=[text], embeddings=[vec],
246
+ ids=[f"{kind}-{Store.state['turn']}-{random.randint(0,1_000_000)}"])
247
+
248
+
249
+ # ==============================================================================
250
+ # MODEL LOADING WITH DENSE + CF-HoT
251
+ # ==============================================================================
252
+ _model = None
253
+ _tokenizer = None
254
+ _multi_head = None
255
+ _hedge_tokens = None
256
+ _verbose_tokens = None
257
+
258
+ def load_llm():
259
+ global _model, _tokenizer, _multi_head, _hedge_tokens, _verbose_tokens
260
+
261
+ from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
262
+
263
+ print(f"[llm] Loading base model: {MODEL_PATH}")
264
+
265
+ _tokenizer = AutoTokenizer.from_pretrained(MODEL_PATH, use_fast=True, local_files_only=True)
266
+ if _tokenizer.pad_token_id is None:
267
+ _tokenizer.pad_token = _tokenizer.eos_token
268
+
269
+ bnb_config = BitsAndBytesConfig(
270
+ load_in_4bit=True,
271
+ bnb_4bit_quant_type="nf4",
272
+ bnb_4bit_compute_dtype=torch.bfloat16,
273
+ bnb_4bit_use_double_quant=True
274
+ )
275
+
276
+ base_model = AutoModelForCausalLM.from_pretrained(
277
+ MODEL_PATH,
278
+ quantization_config=bnb_config,
279
+ device_map="auto",
280
+ torch_dtype=torch.bfloat16,
281
+ local_files_only=True
282
+ )
283
+
284
+ # === KEY CHANGE: Load DENSE checkpoint instead of CF-HoT LoRA ===
285
+ if PEFT_OK and Config.use_dense and os.path.exists(DENSE_CHECKPOINT):
286
+ print(f"[dense] Loading CONDENSATOR checkpoint: {DENSE_CHECKPOINT}")
287
+ _model = PeftModel.from_pretrained(base_model, DENSE_CHECKPOINT)
288
+ print("[dense] βœ“ Dense adapter loaded (step 100, Density: 28.5, Reward: 0.624)")
289
+ elif PEFT_OK and os.path.exists(CFHOT_CHECKPOINT):
290
+ # Fallback to CF-HoT LoRA if dense not available
291
+ print(f"[cf-hot] Loading LoRA adapter from: {CFHOT_CHECKPOINT}")
292
+ _model = PeftModel.from_pretrained(base_model, CFHOT_CHECKPOINT)
293
+ print("[cf-hot] LoRA adapter loaded")
294
+ else:
295
+ _model = base_model
296
+ print("[warning] No adapter loaded - using base model")
297
+
298
+ _model.eval()
299
+
300
+ # Initialize CF-HoT multi-head predictor (works with ANY adapter)
301
+ if Config.use_cfhot:
302
+ _init_cfhot()
303
+
304
+ return _tokenizer, _model
305
+
306
+
307
+ def _init_cfhot():
308
+ """Initialize CF-HoT multi-head predictor for runtime cognitive control."""
309
+ global _multi_head, _hedge_tokens, _verbose_tokens
310
+
311
+ n_layers = _model.config.num_hidden_layers
312
+ d_model = _model.config.hidden_size
313
+ device = next(_model.parameters()).device
314
+
315
+ print(f"[cf-hot] Initializing multi-head predictor ({n_layers} layers, {d_model} dims)")
316
+ _multi_head = MultiHeadPredictor(d_model, n_layers).to(device).float()
317
+
318
+ # Load shared fiber projections from CF-HoT checkpoint
319
+ cfhot_risk_path = os.path.join(CFHOT_CHECKPOINT, "risk_predictor.pt")
320
+ if os.path.exists(cfhot_risk_path):
321
+ cfhot_ckpt = torch.load(cfhot_risk_path, weights_only=False, map_location=device)
322
+ cfhot_state = cfhot_ckpt['risk_predictor']
323
+
324
+ for i in range(n_layers):
325
+ key = f'fiber_projs.{i}.weight'
326
+ if key in cfhot_state:
327
+ _multi_head.fiber_projs[i].weight.data = cfhot_state[key].to(device).float()
328
+
329
+ if 'layer_weights' in cfhot_state:
330
+ _multi_head.layer_weights.data = cfhot_state['layer_weights'].to(device).float()
331
+
332
+ # Load repetition head
333
+ try:
334
+ _multi_head.heads['repetition'][0].weight.data = cfhot_state['predictor.0.weight'].to(device).float()
335
+ _multi_head.heads['repetition'][0].bias.data = cfhot_state['predictor.0.bias'].to(device).float()
336
+ _multi_head.heads['repetition'][2].weight.data = cfhot_state['predictor.2.weight'].to(device).float()
337
+ _multi_head.heads['repetition'][2].bias.data = cfhot_state['predictor.2.bias'].to(device).float()
338
+ _multi_head.heads['repetition'][4].weight.data = cfhot_state['predictor.4.weight'].to(device).float()
339
+ _multi_head.heads['repetition'][4].bias.data = cfhot_state['predictor.4.bias'].to(device).float()
340
+ _multi_head.loaded_heads.add('repetition')
341
+ print(f"[cf-hot] Loaded repetition head (125x separation)")
342
+ except KeyError as e:
343
+ print(f"[cf-hot] Warning: Could not load repetition head: {e}")
344
+ else:
345
+ print(f"[cf-hot] Warning: CF-HoT risk predictor not found at {cfhot_risk_path}")
346
+
347
+ # Load additional heads
348
+ def find_best_checkpoint(head_dir):
349
+ if not os.path.exists(head_dir):
350
+ return None
351
+ ckpts = []
352
+ for d in os.listdir(head_dir):
353
+ if d.startswith("ckpt_"):
354
+ try:
355
+ step = int(d.split("_")[1])
356
+ ckpts.append((step, os.path.join(head_dir, d)))
357
+ except:
358
+ pass
359
+ if ckpts:
360
+ ckpts.sort(key=lambda x: x[0], reverse=True)
361
+ return ckpts[0]
362
+ return None
363
+
364
+ # Load hedging head
365
+ hedging_dir = os.path.join(MULTI_HEAD_DIR, "hedging_head")
366
+ best_hedge = find_best_checkpoint(hedging_dir)
367
+ if best_hedge:
368
+ step, ckpt_dir = best_hedge
369
+ _multi_head.load_head('hedging', os.path.join(ckpt_dir, "hedging_head.pt"))
370
+
371
+ # Load verbosity head
372
+ verbosity_dir = os.path.join(MULTI_HEAD_DIR, "verbosity_head")
373
+ best_verb = find_best_checkpoint(verbosity_dir)
374
+ if best_verb:
375
+ step, ckpt_dir = best_verb
376
+ _multi_head.load_head('verbosity', os.path.join(ckpt_dir, "verbosity_head.pt"))
377
+
378
+ # Freeze everything
379
+ _multi_head.eval()
380
+ for param in _multi_head.parameters():
381
+ param.requires_grad = False
382
+
383
+ # Build suppression token sets - EXPANDED for better density
384
+ hedge_phrases = [
385
+ "As an AI", "As a language model", "As an artificial intelligence",
386
+ "I don't have feelings", "I don't have emotions", "I cannot",
387
+ "I apologize", "I'm just a", "I'm only a", "I'm sorry",
388
+ "That's a great question", "That's an interesting question",
389
+ "Great question", "Good question", "Interesting question",
390
+ "I'd be happy to", "I would be happy to", "Let me help you",
391
+ "Thank you for asking", "Thanks for asking",
392
+ ]
393
+ _hedge_tokens = set()
394
+ for phrase in hedge_phrases:
395
+ tokens = _tokenizer.encode(phrase, add_special_tokens=False)
396
+ if tokens:
397
+ _hedge_tokens.add(tokens[0])
398
+
399
+ verbose_phrases = [
400
+ "Let me explain", "To put it simply", "In other words",
401
+ "What I mean is", "Allow me to", "Basically", "Essentially",
402
+ "First of all", "To begin with", "It's important to note",
403
+ "I should mention", "As you may know", "As you might know",
404
+ "Before I answer", "To answer your question", "Simply put",
405
+ "In essence", "To be clear", "To clarify", "In summary",
406
+ ]
407
+ _verbose_tokens = set()
408
+ for phrase in verbose_phrases:
409
+ tokens = _tokenizer.encode(phrase, add_special_tokens=False)
410
+ if tokens:
411
+ _verbose_tokens.add(tokens[0])
412
+
413
+ print(f"[cf-hot] βœ“ Multi-head system ready")
414
+ print(f"[cf-hot] Loaded heads: {list(_multi_head.loaded_heads)}")
415
+ print(f"[cf-hot] Hedge tokens: {len(_hedge_tokens)}")
416
+ print(f"[cf-hot] Verbose tokens: {len(_verbose_tokens)}")
417
+
418
+
419
+ # ==============================================================================
420
+ # LHT REASONER
421
+ # ==============================================================================
422
+ class LHTReasoner:
423
+ def __init__(self, config=None):
424
+ if not LHT_OK:
425
+ raise ImportError("LHT modules not available")
426
+ self.config = config or LHTConfig(
427
+ vocab_size=32000,
428
+ d_model=256,
429
+ d_fiber=32,
430
+ n_heads=4,
431
+ n_layers=4,
432
+ lie_algebra_rank=4,
433
+ )
434
+ self.model = LieHolonomyTransformer(self.config)
435
+ self.waypoint_detector = WaypointDetector(self.config, n_waypoints=32)
436
+ weights_path = os.path.join(LHT_DIR, "lht_weights.pt")
437
+ if os.path.exists(weights_path):
438
+ self.model.load_state_dict(torch.load(weights_path, map_location="cpu"))
439
+ print("[lht] Loaded pretrained weights")
440
+
441
+ def check_consistency(self, reasoning_chain: List[str], tokenizer) -> Dict[str, float]:
442
+ combined = " [STEP] ".join(reasoning_chain)
443
+ tokens = tokenizer(combined, return_tensors="pt", truncation=True,
444
+ max_length=self.config.max_seq_len)
445
+ with torch.no_grad():
446
+ output = self.model(input_ids=tokens["input_ids"], return_geometric_losses=True)
447
+ holonomy = output.get("holonomy_loss", torch.tensor(0.0)).item()
448
+ curvature = output.get("curvature_loss", torch.tensor(0.0)).item()
449
+ x = self.model.token_embed(tokens["input_ids"])
450
+ waypoint_ids, stability = self.waypoint_detector(x)
451
+ consistency_score = 1.0 / (1.0 + holonomy)
452
+ return {
453
+ "holonomy": holonomy,
454
+ "curvature": curvature,
455
+ "consistency_score": consistency_score,
456
+ "n_waypoints": len(torch.unique(waypoint_ids)),
457
+ "avg_stability": stability.mean().item(),
458
+ "is_consistent": consistency_score > Config.lht_consistency_threshold
459
+ }
460
+
461
+ def analyze_plan(self, plan_steps: List[str], tokenizer) -> str:
462
+ metrics = self.check_consistency(plan_steps, tokenizer)
463
+ return f"""
464
+ [LHT Geometric Analysis]
465
+ Holonomy: {metrics['holonomy']:.4f} (lower = more consistent)
466
+ Curvature: {metrics['curvature']:.4f} (lower = simpler reasoning)
467
+ Consistency: {metrics['consistency_score']:.2%}
468
+ Waypoints: {metrics['n_waypoints']} stable anchors detected
469
+ Stability: {metrics['avg_stability']:.2%}
470
+ Verdict: {"βœ“ CONSISTENT" if metrics['is_consistent'] else "⚠ INCONSISTENT"}
471
+ """
472
+
473
+ _lht_reasoner = None
474
+
475
+ def get_lht_reasoner():
476
+ global _lht_reasoner
477
+ if _lht_reasoner is None and LHT_OK:
478
+ try:
479
+ _lht_reasoner = LHTReasoner()
480
+ except Exception as e:
481
+ print(f"[lht] Failed to initialize: {e}")
482
+ return _lht_reasoner
483
+
484
+
485
+ # ==============================================================================
486
+ # DENSITY ANALYZER (NEW!)
487
+ # ==============================================================================
488
+ def analyze_density(text: str, tokenizer=None) -> Dict[str, Any]:
489
+ """Analyze the information density of generated text."""
490
+ if tokenizer is None:
491
+ tokenizer = _tokenizer
492
+
493
+ words = text.split()
494
+ tokens = len(tokenizer.encode(text))
495
+
496
+ # Content words (>4 chars, alphabetic)
497
+ content_words = [w.lower() for w in words if len(w) > 4 and w.isalpha()]
498
+ unique_content = set(content_words)
499
+
500
+ # Technical terms (heuristic: contains numbers, special chars, or is capitalized mid-sentence)
501
+ technical_terms = [w for w in words if any(c.isdigit() for c in w) or
502
+ any(c in w for c in ['β†’', 'βˆ‚', 'βˆ‡', 'Γ—', 'Β·', '=', '<', '>'])]
503
+
504
+ # Filler phrases
505
+ fillers = [
506
+ "that's a great question", "let me explain", "i'd be happy to",
507
+ "as you may know", "it's important to note", "to put it simply",
508
+ "in other words", "basically", "essentially", "first of all",
509
+ "to begin with", "allow me to", "i should mention",
510
+ ]
511
+ filler_count = sum(1 for f in fillers if f in text.lower())
512
+
513
+ # Calculate metrics
514
+ density = len(unique_content) / max(tokens, 1) * 100
515
+ technical_ratio = len(technical_terms) / max(len(words), 1) * 100
516
+
517
+ return {
518
+ 'tokens': tokens,
519
+ 'words': len(words),
520
+ 'unique_content_words': len(unique_content),
521
+ 'technical_terms': len(technical_terms),
522
+ 'density': density,
523
+ 'technical_ratio': technical_ratio,
524
+ 'filler_phrases': filler_count,
525
+ 'chars_per_token': len(text) / max(tokens, 1),
526
+ }
527
+
528
+
529
+ # ==============================================================================
530
+ # CF-HoT CONTROLLED GENERATION
531
+ # ==============================================================================
532
+ def generate_with_cfhot(prompt: str, **kwargs) -> Tuple[str, Dict]:
533
+ """
534
+ Generate text with CF-HoT cognitive control.
535
+ All loaded heads run concurrently, intervening when risks exceed thresholds.
536
+ """
537
+ global _model, _tokenizer, _multi_head, _hedge_tokens, _verbose_tokens
538
+
539
+ temperature = kwargs.get("temperature", Config.temperature)
540
+ top_p = kwargs.get("top_p", Config.top_p)
541
+ max_new_tokens = kwargs.get("max_new_tokens", Config.max_new_tokens)
542
+
543
+ device = next(_model.parameters()).device
544
+
545
+ # Encode prompt
546
+ input_ids = _tokenizer.encode(prompt, return_tensors='pt').to(device)
547
+ attention_mask = torch.ones_like(input_ids)
548
+
549
+ # Stats
550
+ stats = {
551
+ 'tokens_generated': 0,
552
+ 'interventions': {'repetition': 0, 'hedging': 0, 'verbosity': 0},
553
+ 'intervention_details': []
554
+ }
555
+
556
+ generated_ids = input_ids.clone()
557
+
558
+ for step in range(max_new_tokens):
559
+ with torch.no_grad():
560
+ outputs = _model(
561
+ input_ids=generated_ids,
562
+ attention_mask=attention_mask,
563
+ output_hidden_states=True,
564
+ return_dict=True
565
+ )
566
+
567
+ logits = outputs.logits[:, -1, :] / temperature
568
+
569
+ # Get risks from all heads if CF-HoT is enabled
570
+ if _multi_head is not None and _multi_head.loaded_heads:
571
+ hidden_states = outputs.hidden_states[1:]
572
+ risks = _multi_head.get_all_risks(hidden_states)
573
+ current_risks = {name: r[:, -1].item() for name, r in risks.items()}
574
+
575
+ # === COGNITIVE INTERVENTION ===
576
+
577
+ # Repetition control
578
+ if ('repetition' in current_risks and
579
+ current_risks['repetition'] > Config.cfhot_repetition_threshold):
580
+ recent_tokens = generated_ids[0, -32:].tolist()
581
+ for tok_id in set(recent_tokens):
582
+ logits[0, tok_id] -= Config.cfhot_repetition_penalty
583
+ stats['interventions']['repetition'] += 1
584
+ Store.state['cfhot_interventions']['repetition'] += 1
585
+
586
+ # Hedging control
587
+ if ('hedging' in current_risks and _hedge_tokens and
588
+ current_risks['hedging'] > Config.cfhot_hedging_threshold):
589
+ for tok_id in _hedge_tokens:
590
+ logits[0, tok_id] -= Config.cfhot_hedging_penalty
591
+ stats['interventions']['hedging'] += 1
592
+ Store.state['cfhot_interventions']['hedging'] += 1
593
+
594
+ # Verbosity control
595
+ if ('verbosity' in current_risks and _verbose_tokens and
596
+ current_risks['verbosity'] > Config.cfhot_verbosity_threshold):
597
+ for tok_id in _verbose_tokens:
598
+ logits[0, tok_id] -= Config.cfhot_verbosity_penalty
599
+ stats['interventions']['verbosity'] += 1
600
+ Store.state['cfhot_interventions']['verbosity'] += 1
601
+
602
+ # Top-p sampling
603
+ sorted_logits, sorted_indices = torch.sort(logits, descending=True)
604
+ cumulative_probs = torch.cumsum(F.softmax(sorted_logits, dim=-1), dim=-1)
605
+ sorted_indices_to_remove = cumulative_probs > top_p
606
+ sorted_indices_to_remove[..., 1:] = sorted_indices_to_remove[..., :-1].clone()
607
+ sorted_indices_to_remove[..., 0] = 0
608
+ indices_to_remove = sorted_indices_to_remove.scatter(1, sorted_indices, sorted_indices_to_remove)
609
+ logits[indices_to_remove] = float('-inf')
610
+
611
+ # Sample
612
+ probs = F.softmax(logits, dim=-1)
613
+ next_token = torch.multinomial(probs, num_samples=1)
614
+
615
+ generated_ids = torch.cat([generated_ids, next_token], dim=-1)
616
+ attention_mask = torch.cat([attention_mask, torch.ones(1, 1, device=device)], dim=-1)
617
+
618
+ stats['tokens_generated'] += 1
619
+
620
+ if next_token.item() == _tokenizer.eos_token_id:
621
+ break
622
+
623
+ output_text = _tokenizer.decode(generated_ids[0], skip_special_tokens=False)
624
+
625
+ # Clean up output
626
+ if "<|im_start|>assistant" in output_text:
627
+ output_text = output_text.split("<|im_start|>assistant")[-1]
628
+ if output_text.startswith("\n"):
629
+ output_text = output_text[1:]
630
+
631
+ for end_tok in ["<|im_end|>", "<|im_start|>"]:
632
+ if end_tok in output_text:
633
+ output_text = output_text.split(end_tok)[0]
634
+
635
+ return output_text.strip(), stats
636
+
637
+
638
+ def generate(tok, model, user: str, check_reasoning: bool = False, **kwargs) -> str:
639
+ """
640
+ Main generation function - uses CF-HoT if enabled, otherwise standard generation.
641
+ """
642
+ temperature = kwargs.get("temperature", Config.temperature)
643
+ top_p = kwargs.get("top_p", Config.top_p)
644
+ repetition_penalty = kwargs.get("repetition_penalty", Config.repetition_penalty)
645
+ max_new_tokens = kwargs.get("max_new_tokens", Config.max_new_tokens)
646
+
647
+ prompt = (f"<|im_start|>system\n{Config.system}<|im_end|>\n"
648
+ f"<|im_start|>user\n{user}<|im_end|>\n"
649
+ f"<|im_start|>assistant\n")
650
+
651
+ # Use CF-HoT controlled generation if enabled
652
+ if Config.use_cfhot and _multi_head is not None:
653
+ text, stats = generate_with_cfhot(
654
+ prompt,
655
+ temperature=temperature,
656
+ top_p=top_p,
657
+ max_new_tokens=max_new_tokens
658
+ )
659
+
660
+ # Analyze density
661
+ density_info = analyze_density(text, tok)
662
+ Store.state['density_scores'].append(density_info['density'])
663
+
664
+ # Show intervention stats if any occurred
665
+ total_interventions = sum(stats['interventions'].values())
666
+ if total_interventions > 0:
667
+ text += f"\n\n[CF-HoT: {total_interventions} interventions"
668
+ details = [f"{k}={v}" for k, v in stats['interventions'].items() if v > 0]
669
+ text += f" ({', '.join(details)})]"
670
+
671
+ # Show density info
672
+ text += f"\n[Density: {density_info['density']:.1f} | Tokens: {density_info['tokens']} | Fillers: {density_info['filler_phrases']}]"
673
+ else:
674
+ # Standard generation
675
+ ids = tok(prompt, return_tensors="pt").to(model.device)
676
+ out = model.generate(
677
+ **ids,
678
+ do_sample=True,
679
+ temperature=temperature,
680
+ top_p=top_p,
681
+ repetition_penalty=repetition_penalty,
682
+ max_new_tokens=max_new_tokens,
683
+ pad_token_id=tok.eos_token_id
684
+ )
685
+ text = tok.decode(out[0], skip_special_tokens=False)
686
+ if "<|im_start|>assistant" in text:
687
+ text = text.split("<|im_start|>assistant\n", 1)[-1].strip()
688
+
689
+ # Clean up
690
+ for end_tok in ["<|im_end|>", "<|im_start|>"]:
691
+ if end_tok in text:
692
+ text = text.split(end_tok)[0]
693
+
694
+ # LHT reasoning check
695
+ if check_reasoning and Config.use_lht_reasoning:
696
+ lht = get_lht_reasoner()
697
+ if lht:
698
+ steps = [s.strip() for s in re.split(r'[\nβ€’\-\d\.]', text) if len(s.strip()) > 10]
699
+ if len(steps) >= 2:
700
+ metrics = lht.check_consistency(steps, tok)
701
+ Store.state["reasoning_consistency"].append(metrics["consistency_score"])
702
+ if not metrics["is_consistent"]:
703
+ text += f"\n\n[⚠ LHT: Low consistency ({metrics['consistency_score']:.2%})]"
704
+
705
+ return text
706
+
707
+
708
+ # ==============================================================================
709
+ # TOOLS
710
+ # ==============================================================================
711
+ ALLOWED_SHELL = {"ls", "cat", "wc", "head", "tail", "nvidia-smi", "df", "du", "grep", "rg", "python3", "python"}
712
+
713
+ def tool_shell(cmd: str) -> str:
714
+ try:
715
+ exe = cmd.strip().split()[0]
716
+ if exe not in ALLOWED_SHELL:
717
+ return f"[shell] blocked: {exe}"
718
+ p = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=20)
719
+ return p.stdout.decode("utf-8", errors="ignore")[:8000]
720
+ except Exception as e:
721
+ return f"[shell] error: {e}"
722
+
723
+ def tool_py(code: str) -> str:
724
+ try:
725
+ g = {
726
+ "__builtins__": {"range": range, "len": len, "min": min, "max": max, "sum": sum, "print": print},
727
+ "math": math, "json": json, "re": re, "statistics": statistics, "random": random
728
+ }
729
+ l = {}
730
+ exec(code, g, l)
731
+ return f"[py] ok\n{l.get('out', '')}"
732
+ except Exception:
733
+ return f"[py] error:\n{traceback.format_exc()[-2000:]}"
734
+
735
+ def tool_search_local(query: str, path: str = ROOT) -> str:
736
+ rg = shutil.which("rg")
737
+ if rg:
738
+ cmd = f'rg -n --no-heading --hidden -S "{query}" {path}'
739
+ else:
740
+ cmd = f'grep -RIn --exclude-dir=.git --exclude-dir=__pycache__ -e "{query}" {path}'
741
+ return tool_shell(cmd)
742
+
743
+ def tool_lht_analyze(text: str, tok) -> str:
744
+ if not Config.use_lht_reasoning:
745
+ return "[lht] Disabled - use 'toggle use_lht_reasoning'"
746
+ lht = get_lht_reasoner()
747
+ if not lht:
748
+ return "[lht] Not available"
749
+ steps = [s.strip() for s in re.split(r'[\nβ€’\-\d\.]', text) if len(s.strip()) > 10]
750
+ if len(steps) < 2:
751
+ return "[lht] Need at least 2 reasoning steps to analyze"
752
+ return lht.analyze_plan(steps, tok)
753
+
754
+ TOOLS = {"shell": tool_shell, "python": tool_py, "search": tool_search_local}
755
+ TOOL_SCORES = {k: 0 for k in TOOLS}
756
+
757
+ def update_tool_score(tool: str, success: bool):
758
+ if tool not in TOOL_SCORES:
759
+ return
760
+ TOOL_SCORES[tool] += (1 if success else -1)
761
+ TOOL_SCORES[tool] = max(-5, min(20, TOOL_SCORES[tool]))
762
+
763
+ def tool_router(question: str, tok, model) -> str:
764
+ sketch = generate(tok, model,
765
+ f"Choose a tool for:\n{question}\nReply ONLY with JSON: {{'tool':'shell|python|search|none','arg':'...'}}")
766
+ try:
767
+ j = json.loads(sketch.splitlines()[-1].replace("'", '"'))
768
+ except:
769
+ return "[tool:none]"
770
+ tool, arg = j.get("tool", "none"), j.get("arg", "")
771
+ if tool in TOOLS:
772
+ res = TOOLS[tool](arg)[:4000]
773
+ update_tool_score(tool, True)
774
+ Store.log_mem("tool", {"tool": tool, "arg": arg, "res_head": res[:500]})
775
+ return f"[tool:{tool}] {res}"
776
+ update_tool_score(tool, False)
777
+ return "[tool:none]"
778
+
779
+
780
+ # ==============================================================================
781
+ # PLANNING / REFLECTION
782
+ # ==============================================================================
783
+ def persona_directive() -> str:
784
+ base = "Übermenschetien Dense Engine: Compressed wisdom, Nietzschean clarity. Every word matters."
785
+ if Config.use_lht_reasoning:
786
+ base += " Apply Lie-Holonomy geometric reasoning for consistency."
787
+ if Config.use_cfhot:
788
+ base += " CF-HoT cognitive control active."
789
+ if Config.use_dense:
790
+ base += " Dense mode: maximum information per token."
791
+ return base
792
+
793
+ def plan_for(goal: str, tok, model) -> str:
794
+ user = (f"{persona_directive()}\nGoal: {goal}\n"
795
+ f"Deliver:\n- 5 concrete steps\n- Constraints & risks\n- Nightly audit criteria\n- Nietzschean maxim")
796
+ response = generate(tok, model, user, check_reasoning=True)
797
+ if Config.use_lht_reasoning:
798
+ analysis = tool_lht_analyze(response, tok)
799
+ response += "\n" + analysis
800
+ return response
801
+
802
+ def reflect_on(last_output: str, tok, model) -> str:
803
+ user = f"{persona_directive()}\nCritique and improve:\n{last_output}\nReturn refined plan with sharper steps."
804
+ return generate(tok, model, user, check_reasoning=True)
805
+
806
+
807
+ # ==============================================================================
808
+ # FINAL REPORT
809
+ # ==============================================================================
810
+ def final_report():
811
+ print("\n" + "=" * 60)
812
+ print("FINAL ÜBERMENSCH DENSE REPORT")
813
+ print("=" * 60)
814
+ print(f"Turns completed: {Store.state['turn']}")
815
+ print(f"Goals tracked: {len(Store.goals)}")
816
+ print(f"\nTool scores (Tsetlin automata):")
817
+ print(json.dumps(TOOL_SCORES, indent=2))
818
+
819
+ if os.path.exists(Store.mem_path):
820
+ lines = open(Store.mem_path).read().splitlines()
821
+ print(f"\nMemory entries: {len(lines)}")
822
+
823
+ # Density stats (NEW!)
824
+ if Store.state.get("density_scores"):
825
+ scores = Store.state["density_scores"]
826
+ print(f"\n[Density Metrics]")
827
+ print(f" Responses analyzed: {len(scores)}")
828
+ print(f" Avg density: {sum(scores)/len(scores):.1f}")
829
+ print(f" Min density: {min(scores):.1f}")
830
+ print(f" Max density: {max(scores):.1f}")
831
+
832
+ if Store.state.get("reasoning_consistency"):
833
+ scores = Store.state["reasoning_consistency"]
834
+ print(f"\n[LHT Reasoning Metrics]")
835
+ print(f" Checks performed: {len(scores)}")
836
+ print(f" Avg consistency: {sum(scores)/len(scores):.1%}")
837
+ print(f" Min consistency: {min(scores):.1%}")
838
+ print(f" Max consistency: {max(scores):.1%}")
839
+
840
+ # CF-HoT stats
841
+ if Store.state.get("cfhot_interventions"):
842
+ iv = Store.state["cfhot_interventions"]
843
+ total = sum(iv.values())
844
+ print(f"\n[CF-HoT Cognitive Control]")
845
+ print(f" Total interventions: {total}")
846
+ for head, count in iv.items():
847
+ print(f" {head}: {count}")
848
+
849
+ print(f"\nDense mode: {'ON' if Config.use_dense else 'OFF'}")
850
+ print(f"Vector memory: {'ON' if Config.use_vector_memory else 'OFF'}")
851
+ print(f"LHT reasoning: {'ON' if Config.use_lht_reasoning else 'OFF'}")
852
+ print(f"CF-HoT control: {'ON' if Config.use_cfhot else 'OFF'}")
853
+ print(f"Voice output: {'ON' if Config.use_voice else 'OFF'}")
854
+
855
+ print("\n" + "-" * 60)
856
+ print("Nietzschean maxim: Become who you are β€” iterate beyond all limits.")
857
+ print("Dense truth: Maximum information, minimum tokens.")
858
+ print("Geometric truth: Consistency is holonomy-freedom.")
859
+ print("Cognitive control: Remove the RLHF tax, unleash capability.")
860
+ print("=" * 60)
861
+
862
+
863
+ # ==============================================================================
864
+ # HELP
865
+ # ==============================================================================
866
+ HELP = """
867
+ ���══════════════════════════════════════════════════════════════════╗
868
+ β•‘ ÜBERMENSCHETIEN DENSE ENGINE + CF-HoT COGNITIVE CONTROL β•‘
869
+ ╠══════════════════════════════════════════════════════════════════╣
870
+ β•‘ GOALS β•‘
871
+ β•‘ goals List all goals β•‘
872
+ β•‘ add: <text> Add a new goal β•‘
873
+ β•‘ del: <idx> Delete goal by index β•‘
874
+ β•‘ plan: <idx> Generate plan for goal (with LHT + CF-HoT) β•‘
875
+ β•‘ β•‘
876
+ β•‘ REASONING β•‘
877
+ β•‘ reflect Refine last plan β•‘
878
+ β•‘ lht: <text> Analyze reasoning consistency β•‘
879
+ β•‘ density: <txt> Analyze text density β•‘
880
+ β•‘ β•‘
881
+ β•‘ TOOLS β•‘
882
+ β•‘ tool: <query> Auto-select and use tool β•‘
883
+ β•‘ shell: <cmd> Run shell command directly β•‘
884
+ β•‘ py: <code> Run Python code directly β•‘
885
+ β•‘ search: <q> Search local files β•‘
886
+ β•‘ β•‘
887
+ β•‘ CONFIG β•‘
888
+ β•‘ toggle <flag> Toggle: use_voice, use_vector_memory, β•‘
889
+ β•‘ use_lht_reasoning, use_cfhot, β•‘
890
+ β•‘ use_dense, autonomy β•‘
891
+ β•‘ status Show current state β•‘
892
+ β•‘ cfhot Show CF-HoT stats and loaded heads β•‘
893
+ β•‘ dense Show density stats β•‘
894
+ β•‘ β•‘
895
+ β•‘ OTHER β•‘
896
+ β•‘ help Show this help β•‘
897
+ β•‘ quit Exit with final report β•‘
898
+ β•šβ•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•β•
899
+ """
900
+
901
+
902
+ # ==============================================================================
903
+ # MAIN LOOP
904
+ # ==============================================================================
905
+ def main():
906
+ print("=" * 70)
907
+ print("πŸŸ₯🟨πŸŸ₯ ÜBERMENSCHETIEN DENSE ENGINE + CF-HoT COGNITIVE CONTROL")
908
+ print("=" * 70)
909
+ print(f" DENSE Mode: ON (CONDENSATOR step 100, Density: 28.5)")
910
+ print(f" CF-HoT Control: ON (Repetition 125x, Verbosity 2.1x, Hedging 1.5x)")
911
+ print(f" LHT Reasoning: {'ON' if LHT_OK else 'OFF'}")
912
+ print(f" Vector Memory: {'ON' if VECTOR_OK else 'OFF'}")
913
+ print(f" Voice Output: {'ON' if VOICE_OK else 'OFF'}")
914
+ print("=" * 70)
915
+ print(" Type 'help' for commands.\n")
916
+
917
+ Store.load()
918
+ tok, model = load_llm()
919
+ last_plan = ""
920
+
921
+ while True:
922
+ try:
923
+ u = input("\n> ").strip()
924
+ except (EOFError, KeyboardInterrupt):
925
+ break
926
+
927
+ if not u:
928
+ continue
929
+ if u == "help":
930
+ print(HELP)
931
+ continue
932
+ if u == "quit":
933
+ break
934
+
935
+ # CF-HoT status
936
+ if u == "cfhot":
937
+ print("\n[CF-HoT Cognitive Control Status]")
938
+ print(f" Enabled: {Config.use_cfhot}")
939
+ if _multi_head:
940
+ print(f" Loaded heads: {list(_multi_head.loaded_heads)}")
941
+ print(f" Thresholds:")
942
+ print(f" Repetition: {Config.cfhot_repetition_threshold}")
943
+ print(f" Hedging: {Config.cfhot_hedging_threshold}")
944
+ print(f" Verbosity: {Config.cfhot_verbosity_threshold}")
945
+ print(f" Session interventions:")
946
+ for head, count in Store.state.get('cfhot_interventions', {}).items():
947
+ print(f" {head}: {count}")
948
+ continue
949
+
950
+ # Density status (NEW!)
951
+ if u == "dense":
952
+ print("\n[Density Status]")
953
+ print(f" Dense mode: {Config.use_dense}")
954
+ print(f" Dense checkpoint: {DENSE_CHECKPOINT}")
955
+ print(f" Checkpoint exists: {os.path.exists(DENSE_CHECKPOINT)}")
956
+ if Store.state.get('density_scores'):
957
+ scores = Store.state['density_scores']
958
+ print(f" Session density scores:")
959
+ print(f" Count: {len(scores)}")
960
+ print(f" Avg: {sum(scores)/len(scores):.1f}")
961
+ print(f" Range: {min(scores):.1f} - {max(scores):.1f}")
962
+ continue
963
+
964
+ # Analyze density of text
965
+ if u.startswith("density:"):
966
+ text = u[8:].strip()
967
+ if not text:
968
+ print("[density] Provide text to analyze")
969
+ continue
970
+ info = analyze_density(text, tok)
971
+ print(f"\n[Density Analysis]")
972
+ print(f" Tokens: {info['tokens']}")
973
+ print(f" Words: {info['words']}")
974
+ print(f" Unique content words: {info['unique_content_words']}")
975
+ print(f" Technical terms: {info['technical_terms']}")
976
+ print(f" Density score: {info['density']:.1f}")
977
+ print(f" Technical ratio: {info['technical_ratio']:.1f}%")
978
+ print(f" Filler phrases: {info['filler_phrases']}")
979
+ continue
980
+
981
+ # Goals
982
+ if u == "goals":
983
+ print("[goals]")
984
+ if not Store.goals:
985
+ print(" (none)")
986
+ for i, g in enumerate(Store.goals):
987
+ print(f" [{i}] {g}")
988
+ continue
989
+
990
+ if u.startswith("add:"):
991
+ Store.goals.append(u[4:].strip())
992
+ Store.save()
993
+ print("[goals] added")
994
+ continue
995
+
996
+ if u.startswith("del:"):
997
+ try:
998
+ Store.goals.pop(int(u[4:].strip()))
999
+ Store.save()
1000
+ print("[goals] deleted")
1001
+ except:
1002
+ print("[goals] bad index")
1003
+ continue
1004
+
1005
+ if u.startswith("plan:"):
1006
+ try:
1007
+ goal = Store.goals[int(u[5:].strip())]
1008
+ except:
1009
+ print("[plan] bad index")
1010
+ continue
1011
+ out = plan_for(goal, tok, model)
1012
+ last_plan = out
1013
+ Store.log_mem("plan", {"goal": goal, "plan": out})
1014
+ print(out)
1015
+ continue
1016
+
1017
+ if u == "reflect":
1018
+ if not last_plan:
1019
+ print("[reflect] no plan to refine")
1020
+ continue
1021
+ improved = reflect_on(last_plan, tok, model)
1022
+ last_plan = improved
1023
+ Store.log_mem("reflect", {"plan": improved})
1024
+ print(improved)
1025
+ continue
1026
+
1027
+ if u.startswith("lht:"):
1028
+ print(tool_lht_analyze(u[4:].strip(), tok))
1029
+ continue
1030
+
1031
+ if u.startswith("tool:"):
1032
+ print(tool_router(u[5:].strip(), tok, model))
1033
+ continue
1034
+
1035
+ if u.startswith("shell:"):
1036
+ print(tool_shell(u[6:].strip()))
1037
+ continue
1038
+
1039
+ if u.startswith("py:"):
1040
+ print(tool_py(u[3:].strip()))
1041
+ continue
1042
+
1043
+ if u.startswith("search:"):
1044
+ print(tool_search_local(u[7:].strip()))
1045
+ continue
1046
+
1047
+ if u.startswith("toggle"):
1048
+ parts = u.split(maxsplit=1)
1049
+ if len(parts) > 1:
1050
+ print(Config.toggle(parts[1]))
1051
+ else:
1052
+ print("[toggle] specify flag: use_voice, use_vector_memory, use_lht_reasoning, use_cfhot, use_dense, autonomy")
1053
+ continue
1054
+
1055
+ if u == "status":
1056
+ status = {
1057
+ "turn": Store.state["turn"],
1058
+ "goals": len(Store.goals),
1059
+ "autonomy": Config.autonomy,
1060
+ "use_vector_memory": Config.use_vector_memory,
1061
+ "use_lht_reasoning": Config.use_lht_reasoning,
1062
+ "use_cfhot": Config.use_cfhot,
1063
+ "use_dense": Config.use_dense,
1064
+ "cfhot_interventions": Store.state.get("cfhot_interventions", {}),
1065
+ "avg_density": sum(Store.state.get('density_scores', [0])) / max(len(Store.state.get('density_scores', [1])), 1),
1066
+ "tool_scores": TOOL_SCORES,
1067
+ "model": MODEL_PATH,
1068
+ "dense_checkpoint": DENSE_CHECKPOINT
1069
+ }
1070
+ print(json.dumps(status, indent=2))
1071
+ continue
1072
+
1073
+ # Default: free conversation with CF-HoT + Dense control
1074
+ out = generate(tok, model, f"{persona_directive()}\nUser request: {u}")
1075
+ Store.log_mem("reply", {"in": u, "out": out})
1076
+ print(out)
1077
+
1078
+ if Config.use_lht_reasoning and Store.state["turn"] % 3 == 0:
1079
+ print(tool_lht_analyze(out, tok))
1080
+
1081
+ Store.state["turn"] += 1
1082
+ Store.save()
1083
+
1084
+ final_report()
1085
+
1086
+
1087
+ if __name__ == "__main__":
1088
+ main()