Enhance README and scripts for cognitive architecture testing
Browse files- Updated README to clarify the functionality of `UnifiedField.predict()`, including the expected output format and common follow-up actions.
- Added a minimal example in the README demonstrating the use of `TopologyMapper` for graph projection.
- Improved error handling in `chat.py` by removing redundant traceback imports and ensuring consistent exception logging.
- Refactored `compare_iterative.py` to consolidate shared parameters for scoring bridges, enhancing maintainability.
- Enhanced `smoke_extract.py` with detailed logging and summary statistics for grounding checks, improving diagnostic capabilities.
- Updated `runner.py` and `tasks.py` for better error handling and logging during task evaluation and sample loading.
- Introduced new validation checks in `StructuralCausalModel` to ensure proper parent variable definitions and counterfactual limits.
Files changed (39)
- README.md+37-1
- scripts/chat.py+1-3
- scripts/compare_iterative.py+39-15
- scripts/smoke_extract.py+64-8
- tensegrity/__init__.py+7-3
- tensegrity/bench/runner.py+29-8
- tensegrity/bench/tasks.py+1-1
- tensegrity/broca/benchmark.py-2
- tensegrity/broca/controller.py+5-2
- tensegrity/broca/schemas.py+1
- tensegrity/causal/arena.py+22-13
- tensegrity/causal/from_proposal.py+2-2
- tensegrity/causal/scm.py+77-12
- tensegrity/core/morton.py+3-2
- tensegrity/engine/causal_energy.py+22-8
- tensegrity/engine/fhrr.py+52-16
- tensegrity/engine/ngc.py+7
- tensegrity/engine/scoring.py+4-1
- tensegrity/engine/unified_field.py+16-1
- tensegrity/graft/__init__.py+5
- tensegrity/graft/logit_bias.py+45-5
- tensegrity/graft/pipeline.py+44-10
- tensegrity/graft/vocabulary.py+102-12
- tensegrity/inference/__init__.py-3
- tensegrity/legacy/__init__.py+2
- tensegrity/legacy/v1/agent.py+53-8
- tensegrity/legacy/v1/blanket.py+49-25
- tensegrity/legacy/v1/morton.py+73-24
- tensegrity/memory/episodic.py+5
- tensegrity/memory/epistemic.py+12-2
- tensegrity/pipeline/canonical.py+30-20
- tensegrity/pipeline/iterative.py+35-22
- tests/test_architecture_alignment.py+1-1
- tests/test_async_graft.py+2
- tests/test_engine.py+5-1
- tests/test_graft.py+1
- tests/test_needle.py+7
- tests/test_scoring_bench.py-2
- tests/test_tensegrity.py+5-1
44 unmodified lines45464748495051525343 unmodified lines97989910010110210310444 unmodified lines)print(cycle["energy"].total)print(field.predict())```The old Morton/POMDP frontend is still available for migration and baselines:```python43 unmodified lines- same-layer or inverted edges receive virtual parent nodes one layer above theendpoints, turning lateral causal structure into shared vertical dependency.## Semantic Grafting`VocabularyGrounding.from_keywords(...)` remains as a deterministic baseline.For less brittle grounding, `VocabularyGrounding.from_semantic_projection(...)`uses frozen phrase/token embeddings and cosine proximity to build weighted44 unmodified lines454647484950515253545556575843 unmodified lines10210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914044 unmodified lines)print(cycle["energy"].total)expected_obs = field.predict() # np.ndarray, shape (obs_dim,) — settled NGC readout# This is the sensory prediction from the current internal state (not a class label).print("expected observation vector (first 8 dims):", expected_obs[:8])# Common follow-ups: flatten to a label by argmax over logits elsewhere, or pipe into a probe / monitor.```**`UnifiedField.predict()`** returns a **`numpy.ndarray`** of shape **`(obs_dim,)`**: the **predicted next observation** vector from the settled hierarchical circuit after the last `observe` (NGC’s `predict_observation()`). Assign it (as above), inspect slice or norm, or send it to downstream binding / decoding—there is no bundled string label.The old Morton/POMDP frontend is still available for migration and baselines:```python43 unmodified lines- same-layer or inverted edges receive virtual parent nodes one layer above theendpoints, turning lateral causal structure into shared vertical dependency.Minimal example (four variables so one graph can show **direct**, **bypass**, and **same-layer lateral** edges). The mapper API is **`TopologyMapper.project_graph(...)`** (or **`TopologyMapper.from_scm(scm, ...)`** with the same `variable_layers`):```pythonimport networkx as nxfrom tensegrity.causal.scm import StructuralCausalModelfrom tensegrity.engine.causal_energy import TopologyMapperscm = StructuralCausalModel("topology_demo")scm.add_variable("A", n_values=4, parents=[])scm.add_variable("D", n_values=4, parents=["A"]) # bypass path A → Dscm.add_variable("B", n_values=4, parents=["A"]) # direct step A → Bscm.add_variable("C", n_values=4, parents=["B"]) # lateral topology: B,C share a layer belowvariable_layers = {"A": 3, "D": 0, "B": 2, "C": 2}# A→B / A→D: direct + bypass | B→C at same abstract layer → virtual parent in the embeddingmapping = TopologyMapper(expand_layers=True).from_scm(scm,n_layers=8,variable_layers=variable_layers,)print(dict(mapping.embedded_layers)) # layer index per node after relays / vparentsprint(mapping.ngc_layer_sizes()) # e.g. widths per layer → output "shape" at a glance```## Semantic Grafting```pythonfrom tensegrity.graft.vocabulary import VocabularyGrounding# Keyword baseline: VocabularyGrounding.from_keywords(...)# Semantic: VocabularyGrounding.from_semantic_projection(...)````VocabularyGrounding.from_keywords(...)` remains as a deterministic baseline.For less brittle grounding, `VocabularyGrounding.from_semantic_projection(...)`uses frozen phrase/token embeddings and cosine proximity to build weighted
24 unmodified lines25262728293031109 unmodified lines1411421431441451461476 unmodified lines15415515615715815916024 unmodified linesimport argparseimport jsonimport sysfrom typing import Dict, Listfrom tensegrity.graft.pipeline import HybridPipeline109 unmodified linestry:pipe.process_observation(line)except Exception as e:import tracebackprint(f"[perception failed: {type(e).__name__}: {e}]")traceback.print_exc()continue6 unmodified linesmax_tokens=100,)except Exception as e:import tracebackprint(f"[generation failed: {type(e).__name__}: {e}]")traceback.print_exc()continue24 unmodified lines25262728293031109 unmodified lines1411421431441451466 unmodified lines15315415515615715824 unmodified linesimport argparseimport jsonimport sysimport tracebackfrom tensegrity.graft.pipeline import HybridPipeline109 unmodified linestry:pipe.process_observation(line)except Exception as e:print(f"[perception failed: {type(e).__name__}: {e}]")traceback.print_exc()continue6 unmodified linesmax_tokens=100,)except Exception as e:print(f"[generation failed: {type(e).__name__}: {e}]")traceback.print_exc()continue
7 unmodified lines891011121320 unmodified lines343536373839404142434445464748495051525354555618 unmodified lines757677787980817 unmodified linesimport timeimport argparseimport loggingimport numpy as np20 unmodified linesprint(f" [{task_name}] no samples")return Nonesingle = ScoringBridge(obs_dim=256, hidden_dims=[128, 32], fhrr_dim=2048,ngc_settle_steps=30, ngc_learning_rate=0.01,hopfield_beta=0.05, confidence_threshold=0.15,context_settle_steps=40, choice_settle_steps=25,context_learning_epochs=3,)iterative = IterativeCognitiveScorer(obs_dim=256, hidden_dims=[128, 32], fhrr_dim=2048,ngc_settle_steps=30, ngc_learning_rate=0.01,hopfield_beta=0.05,max_iterations=6, convergence_top_p=0.75,context_settle_steps=40, choice_settle_steps=25,context_learning_epochs=3,w_sbert=1.0, w_fhrr=0.3, w_ngc=0.6,belief_step=0.6, shaping_lr_scale=0.5,use_hopfield=True, hopfield_steps=2,)n_total = len(samples)18 unmodified linessa = np.array(scores_s)if np.allclose(sa, 0.0):# use raw sbert sim as tiebreaker (single's gate = uninformative)sims = single._sentence_similarities(s.prompt, s.choices)pred_s = int(np.argmax(sims))else:pred_s = int(np.argmax(sa))7 unmodified lines89101112131420 unmodified lines353637383940414243444546474849505152535455565758596061626364656618 unmodified lines8586878889909192939495969798991001011021031041057 unmodified linesimport timeimport argparseimport loggingimport warningsimport numpy as np20 unmodified linesprint(f" [{task_name}] no samples")return Noneshared_params = {"obs_dim": 256,"hidden_dims": [128, 32],"fhrr_dim": 2048,"ngc_settle_steps": 30,"ngc_learning_rate": 0.01,"hopfield_beta": 0.05,"context_settle_steps": 40,"choice_settle_steps": 25,"context_learning_epochs": 3,}single = ScoringBridge(**shared_params,confidence_threshold=0.15,)iterative = IterativeCognitiveScorer(**shared_params,max_iterations=6,convergence_top_p=0.75,w_sbert=1.0,w_fhrr=0.3,w_ngc=0.6,belief_step=0.6,shaping_lr_scale=0.5,use_hopfield=True,hopfield_steps=2,)n_total = len(samples)18 unmodified linessa = np.array(scores_s)if np.allclose(sa, 0.0):# use raw sbert sim as tiebreaker (single's gate = uninformative)if hasattr(single, "sentence_similarities"):sims = single.sentence_similarities(s.prompt, s.choices)elif hasattr(single, "_sentence_similarities"):warnings.warn("ScoringBridge has no public sentence_similarities(); using ""_sentence_similarities (private). Prefer adding a stable public API.",UserWarning,stacklevel=2,)sims = single._sentence_similarities(s.prompt, s.choices)else:raise AttributeError("ScoringBridge exposes no sentence_similarities() or ""_sentence_similarities(); add a public API on ScoringBridge for tie-breaks.",)pred_s = int(np.argmax(sims))else:pred_s = int(np.argmax(sa))
11 unmodified lines1213141516171819202122232425262717 unmodified lines454647484950515236 unmodified lines899091929394956 unmodified lines1021031041051061071081 unmodified line1101111121131141153 unmodified lines1191201211221231241251261271281291301311321331341351361371381391401411 unmodified line14314414514614714811 unmodified lines"""from __future__ import annotationsimport timefrom typing import List, Literalfrom pydantic import BaseModel, Fieldfrom outlines import models, generateMODEL_NAME = "meta-llama/Llama-3.2-1B-Instruct"class Entity(BaseModel):text: str = Field(description="The exact phrase as it appears in the prompt")17 unmodified linesroles: List[RoleBinding]# Hand-picked items spanning the benchmark behavior zones.ITEMS = [{"task": "truthfulqa","prompt": "What happens if you crack your knuckles a lot?",36 unmodified lines]def build_prompt(item) -> str:return ("You convert a question into structured fields. Do NOT answer the question. ""Do NOT guess. Only extract what is literally in the text.\n\n"6 unmodified lines)def main():print(f"Loading {MODEL_NAME}...")t0 = time.time()model = models.transformers(MODEL_NAME)1 unmodified linegen = generate.json(model, PromptStructure)for i, item in enumerate(ITEMS):print("=" * 78)print(f"[{i}] {item['task']}")3 unmodified linestry:s = gen(build_prompt(item), max_tokens=400)except Exception as e:print(f" FAILED: {type(e).__name__}: {e}")continuedt = time.time() - t0# Grounding check: are entity/role fillers actually substrings of the prompt?text = item["prompt"].lower()ent_grounded = sum(1 for e in s.entities if e.text.lower() in text)role_grounded = sum(1 for r in s.roles if r.filler.lower() in text)print(f"\n entities ({len(s.entities)}, {ent_grounded} grounded, {dt:.1f}s):")for e in s.entities:mark = "" if e.text.lower() in text else " [NOT IN PROMPT]"print(f" {e.kind:<10} {e.text!r}{mark}")print(f"\n relations ({len(s.relations)}):")for r in s.relations:print(f" ({r.subject!r}) -[{r.predicate}]-> ({r.object!r})")print(f"\n roles ({len(s.roles)}, {role_grounded} grounded):")for r in s.roles:1 unmodified lineprint(f" {r.role:<18} := {r.filler!r}{mark}")print()if __name__ == "__main__":main()11 unmodified lines12131415161718192021222324252627282930313233343517 unmodified lines5354555657585960616263646536 unmodified lines1021031041051061071086 unmodified lines1151161171181191201211 unmodified line1231241251261271281291301311321331341353 unmodified lines1391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811 unmodified line18318418518618718818919019119219319419519619719819920020120220320411 unmodified lines"""from __future__ import annotationsimport loggingimport timeimport tracebackfrom typing import List, Literal, TypedDictfrom pydantic import BaseModel, Fieldfrom outlines import models, generateMODEL_NAME = "meta-llama/Llama-3.2-1B-Instruct"_LOGGER = logging.getLogger(__name__)try:from outlines.errors import OutlinesStructuredGenerationError as _OutlineGenErrorexcept ImportError:_OutlineGenError = None # type: ignore[misc, assignment]class Entity(BaseModel):text: str = Field(description="The exact phrase as it appears in the prompt")17 unmodified linesroles: List[RoleBinding]class SmokeItem(TypedDict):task: strprompt: str# Hand-picked items spanning the benchmark behavior zones.ITEMS: list[SmokeItem] = [{"task": "truthfulqa","prompt": "What happens if you crack your knuckles a lot?",36 unmodified lines]def build_prompt(item: SmokeItem) -> str:return ("You convert a question into structured fields. Do NOT answer the question. ""Do NOT guess. Only extract what is literally in the text.\n\n"6 unmodified lines)def main() -> None:print(f"Loading {MODEL_NAME}...")t0 = time.time()model = models.transformers(MODEL_NAME)1 unmodified linegen = generate.json(model, PromptStructure)total_items = len(ITEMS)failures = 0total_entities = grounded_entities = 0total_relations = grounded_relations = 0total_roles = grounded_roles = 0time_sum = 0.0for i, item in enumerate(ITEMS):print("=" * 78)print(f"[{i}] {item['task']}")3 unmodified linestry:s = gen(build_prompt(item), max_tokens=400)except Exception as e:failures += 1if _OutlineGenError is not None and isinstance(e, _OutlineGenError):_LOGGER.exception("Outlines structured generation failed [item %s]", i)else:_LOGGER.exception("Generation failed [item %s]", i)print(f" FAILED: {type(e).__name__}: {e}")print(traceback.format_exc())continuedt = time.time() - t0time_sum += dt# Grounding check: are entity/role fillers — and relation ends — actually substrings of the prompt?text = item["prompt"].lower()ent_grounded = sum(1 for e in s.entities if e.text.lower() in text)role_grounded = sum(1 for r in s.roles if r.filler.lower() in text)rel_grounded = sum(1 for r in s.relationsif r.subject.lower() in text and r.object.lower() in text)total_entities += len(s.entities)grounded_entities += ent_groundedtotal_relations += len(s.relations)grounded_relations += rel_groundedtotal_roles += len(s.roles)grounded_roles += role_groundedprint(f"\n entities ({len(s.entities)}, {ent_grounded} grounded, {dt:.1f}s):")for e in s.entities:mark = "" if e.text.lower() in text else " [NOT IN PROMPT]"print(f" {e.kind:<10} {e.text!r}{mark}")print(f"\n relations ({len(s.relations)}, {rel_grounded} grounded in prompt text):")for r in s.relations:ok_rel = r.subject.lower() in text and r.object.lower() in textmark = "" if ok_rel else " [NOT IN PROMPT]"print(f" ({r.subject!r}) -[{r.predicate}]-> ({r.object!r}){mark}")print(f"\n roles ({len(s.roles)}, {role_grounded} grounded):")for r in s.roles:1 unmodified lineprint(f" {r.role:<18} := {r.filler!r}{mark}")print()ok = total_items - failuresavg_dt = time_sum / ok if ok else 0.0eg = grounded_entities / total_entities if total_entities else 0.0rg = grounded_roles / total_roles if total_roles else 0.0rlg = grounded_relations / total_relations if total_relations else 0.0print("=" * 78)print("SUMMARY:",f"items={total_items}, failures={failures}, ok={ok},",f"entity grounding={eg:.1%} ({grounded_entities}/{total_entities}),",f"role grounding={rg:.1%} ({grounded_roles}/{total_roles}),",f"relation grounding={rlg:.1%} ({grounded_relations}/{total_relations}),",f"avg time (success)={avg_dt:.2f}s",)if __name__ == "__main__":main()
6 unmodified lines7891011121314156 unmodified linesFHRR encoding -> hierarchical predictive coding -> Hopfield memory-> optional causal energy termsLegacy V1 components remain importable from ``tensegrity.legacy.v1``:from tensegrity.legacy.v1 import TensegrityAgent, MortonEncoderTop-level exports intentionally expose the unified field as the defaultarchitecture. Deprecated V1 names are resolved lazily for migration only.6 unmodified lines789101112131415161718196 unmodified linesFHRR encoding -> hierarchical predictive coding -> Hopfield memory-> optional causal energy termsLegacy V1 components (`TensegrityAgent`, `MortonEncoder`, `MarkovBlanket`) remainimportable from ``tensegrity.legacy.v1``. Several other names are re-exported lazilyvia ``tensegrity`` for migration only: ``EpistemicMemory``, ``EpisodicMemory``, and``AssociativeMemory`` from ``tensegrity.memory.*``; ``CausalArena`` and``StructuralCausalModel`` from ``tensegrity.causal.*``; ``FreeEnergyEngine`` and``BeliefPropagator`` from ``tensegrity.inference.*``. Those are **not** defined under``tensegrity.legacy.v1``—use the module paths above when importing explicitly.Top-level exports intentionally expose the unified field as the defaultarchitecture. Deprecated V1 names are resolved lazily for migration only.
256 unmodified lines25725825926026126226314 unmodified lines27827928028128228328415 unmodified lines300301302303304305306307308309310139 unmodified lines450451452453454455456457256 unmodified linesprompt, return_tensors="pt",truncation=True, max_length=512,)["input_ids"]n_prompt = prompt_ids.shape[1]n_total = inputs["input_ids"].shape[1]log_probs = torch.nn.functional.log_softmax(logits[0], dim=-1)14 unmodified lines(UnifiedField, FreeEnergyEngine, EpistemicMemory, EpisodicMemory,AssociativeMemory, log-lik CausalArena), Broca dynamic SCM injection,EnergyCausalArena + TopologyMapper for per-choice causal competition,NGC top-down falsification."""import osimport numpy as np15 unmodified linesfrom tensegrity.pipeline.canonical import CanonicalPipelineif not hasattr(self, "_canonical"):# use_llm_broca defaults False to avoid LLM calls during MC scoring;# the LLM stays out of the reasoning path. Broca is still reachable# for the chat-mode narration step (HybridPipeline).self._canonical = CanonicalPipeline(hypothesis_labels=list(sample.choices),use_llm_broca=False,enable_hypothesis_generation=False,model_name=self.model_name,139 unmodified lines# doesn't leak priors across tasks (different label spaces).if hasattr(self, "_canonical") and hasattr(self._canonical, "reset_session"):self._canonical.reset_session()if hasattr(self, "_iter_scorer") and hasattr(self._iter_scorer, "reset_session"):self._iter_scorer.reset_session()results = []for i, sample in enumerate(samples):256 unmodified lines25725825926026126226314 unmodified lines27827928028128228328428528628728828929029129229329429529629729829930015 unmodified lines316317318319320321322323324325326327328139 unmodified lines468469470471472473474475476477478256 unmodified linesprompt, return_tensors="pt",truncation=True, max_length=512,)["input_ids"]n_prompt = prompt_ids.shape[1]n_total = inputs["input_ids"].shape[1]log_probs = torch.nn.functional.log_softmax(logits[0], dim=-1)14 unmodified lines(UnifiedField, FreeEnergyEngine, EpistemicMemory, EpisodicMemory,AssociativeMemory, log-lik CausalArena), Broca dynamic SCM injection,EnergyCausalArena + TopologyMapper for per-choice causal competition,NGC top-down falsification.**Bench-specific behavior**: In ``single`` scorer mode (`TENSEGRITY_SCORER` env),:meth:`ScoringBridge.reset` is called **once per benchmark sample**, so episodic /Hopfield state does not accumulate across MC items — each example is isolated.In the default canonical mode, reuse a single :class:`CanonicalPipeline` for allsamples — per-item hypotheses and SMCs come from ``reset_for_item`` /``_soft_reset_in_place``. Rebuilding the pipeline on each row would recreatethe agent stack and repeatedly load sentence-transformer weights into memory.:meth:`CanonicalPipeline.reset_session` is invoked **once per task**(``EvalRunner.evaluate_task``), wiping cross-task leakage while permittingwithin-task learning where applicable.Prefer ``canonical`` for behavior aligned with HybridPipeline/session semantics;use ``single`` for a deterministic, isolated field snapshot per sample."""import osimport numpy as np15 unmodified linesfrom tensegrity.pipeline.canonical import CanonicalPipelineif not hasattr(self, "_canonical"):# One CanonicalPipeline instance for all samples on this Runner. Hypothesis texts# and per-choice SCMs are updated per sample inside ``reset_for_item`` /# ``_soft_reset_in_place``; rebuilding ``CanonicalPipeline`` whenever multi-choice# strings changed would recreate ``TensegrityAgent`` / FHRR SBERT loaders and spam# "Loading weights" for each benchmark row (see CanonicalPipeline docs).self._canonical = CanonicalPipeline(hypothesis_labels=None,use_llm_broca=False,enable_hypothesis_generation=False,model_name=self.model_name,139 unmodified lines# doesn't leak priors across tasks (different label spaces).if hasattr(self, "_canonical") and hasattr(self._canonical, "reset_session"):self._canonical.reset_session()if hasattr(self, "_field_scorer"):if hasattr(self._field_scorer, "reset_session"):self._field_scorer.reset_session()elif hasattr(self._field_scorer, "reset"):self._field_scorer.reset()results = []for i, sample in enumerate(samples):
434 unmodified lines435436437438439440441434 unmodified linessamples.append(sample)except Exception as e:logger.error(f"Error adapting task {name}: {e}")continue # Skip malformed rowsreturn samples434 unmodified lines435436437438439440441434 unmodified linessamples.append(sample)except Exception as e:logger.exception("Error adapting task %s at row %s: %s", name, i, e)continue # Skip malformed rowsreturn samples
239 unmodified lines24024124224324424524637 unmodified lines284285286287288289290239 unmodified linesfor turn in range(len(scenario.clues) + 3): # Extra turns for questionsclue = game.get_next_clue()if clue is None:break37 unmodified linesfor h in gold:p = gold[h]q = agent_probs.get(h, 1e-16)if p > 0:kl_div += p * np.log(p / max(q, 1e-16))239 unmodified lines24024124224324424537 unmodified lines283284285286287288239 unmodified linesfor turn in range(len(scenario.clues) + 3): # Extra turns for questionsclue = game.get_next_clue()if clue is None:break37 unmodified linesfor h in gold:p = gold[h]q = agent_probs.get(h, 1e-16)if p > 0:kl_div += p * np.log(p / max(q, 1e-16))
568 unmodified lines569570571572573574575576568 unmodified linesif max_prob > 0.85:action_type = "state_conclusion"elif max_prob < 0.15 and any(h.probability > 0.3 for h in self.belief_state.hypotheses):logger.info(f"Some hypothesis just dropped — eliminating: {max_prob}")# Some hypothesis just dropped — eliminate itpass # Let the EFE-selected action stand# Build the action content568 unmodified lines569570571572573574575576577578579568 unmodified linesif max_prob > 0.85:action_type = "state_conclusion"elif max_prob < 0.15 and any(h.probability > 0.3 for h in self.belief_state.hypotheses):logger.info("Competing hypotheses remain (max_prob=%.3f) — keeping EFE-selected ""action; no hypothesis elimination performed.",max_prob,)pass # Let the EFE-selected action stand# Build the action content
176 unmodified lines177178179180181182176 unmodified linesstyle_register: Literal["formal", "casual", "technical", "empathetic"] = Field(default="casual",alias="register",)176 unmodified lines177178179180181182183176 unmodified linesstyle_register: Literal["formal", "casual", "technical", "empathetic"] = Field(default="casual",alias="register",serialization_alias="register",)
228 unmodified lines22923023123223323419 unmodified lines25425525625725825926026126231 unmodified lines294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326228 unmodified linesIn practice: find the variable where models disagree most aboutthe effect of intervention, and suggest intervening on it."""if len(self.models) < 2:return {'intervention': None, 'expected_info_gain': 0.0}19 unmodified linesinfo_gain = self._estimate_info_gain(var, val,n_samples=n_samples,n_outcome_samples=n_outcome_samples,)if info_gain > best_info_gain:best_info_gain = info_gainbest_experiment = {'variable': var, 'value': val}31 unmodified lines# Estimate expected posterior entropy after seeing outcomes# Use model-averaged predictionsexpected_tension = 0.0n_outcome_samples = min(n_samples, max(1, int(n_outcome_samples)))for name, outcomes in predicted_outcomes.items():model_weight = current_posterior.get(name, 1.0 / len(self.models))for outcome in outcomes[:n_outcome_samples]:# What would the posterior look like if we saw this outcome?hypothetical_log_liks = {}for m_name, model in self.models.items():hypothetical_log_liks[m_name] = model.log_evidence([outcome])# Hypothetical posteriorhyp_evidence = {m: self.model_log_evidence[m] + hypothetical_log_liks[m]for m in self.models}max_e = max(hyp_evidence.values())log_Z = max_e + np.log(sum(np.exp(e - max_e) for e in hyp_evidence.values()))hyp_posterior = {m: np.exp(e - log_Z) for m, e in hyp_evidence.items()}expected_tension += model_weight * self._compute_tension(hyp_posterior)expected_tension /= max(n_outcome_samples, 1)# Information gain = current uncertainty - expected uncertainty after experimentreturn current_tension - expected_tension228 unmodified lines22923023123223323423523623723823924024124224319 unmodified lines26326426526626726826927027131 unmodified lines303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335228 unmodified linesIn practice: find the variable where models disagree most aboutthe effect of intervention, and suggest intervening on it."""if not isinstance(n_samples, int) or n_samples <= 0:raise ValueError(f"n_samples must be a positive int, got {n_samples!r}")if not isinstance(n_outcome_samples, int) or n_outcome_samples < 1:raise ValueError(f"n_outcome_samples must be an int >= 1, got {n_outcome_samples!r}")outcome_cap = min(n_samples, n_outcome_samples)if len(self.models) < 2:return {'intervention': None, 'expected_info_gain': 0.0}19 unmodified linesinfo_gain = self._estimate_info_gain(var, val,n_samples=n_samples,n_outcome_samples=outcome_cap,)if info_gain > best_info_gain:best_info_gain = info_gainbest_experiment = {'variable': var, 'value': val}31 unmodified lines# Estimate expected posterior entropy after seeing outcomes# Use model-averaged predictionsexpected_tension = 0.0effective_outcome_samples = min(n_samples, max(1, n_outcome_samples))for name, outcomes in predicted_outcomes.items():model_weight = current_posterior.get(name, 1.0 / len(self.models))for outcome in outcomes[:effective_outcome_samples]:# What would the posterior look like if we saw this outcome?hypothetical_log_liks = {}for m_name, model in self.models.items():hypothetical_log_liks[m_name] = model.log_evidence([outcome])# Hypothetical posteriorhyp_evidence = {m: self.model_log_evidence[m] + hypothetical_log_liks[m]for m in self.models}max_e = max(hyp_evidence.values())log_Z = max_e + np.log(sum(np.exp(e - max_e) for e in hyp_evidence.values()))hyp_posterior = {m: np.exp(e - log_Z) for m, e in hyp_evidence.items()}expected_tension += model_weight * self._compute_tension(hyp_posterior)expected_tension /= max(effective_outcome_samples, 1)# Information gain = current uncertainty - expected uncertainty after experimentreturn current_tension - expected_tension
20 unmodified lines212223242526272820 unmodified linesthat edge is dropped (``G.remove_edge``) and a debug log is emitted — earlier edgesare never removed. Variable order follows a topological sort when the retained graph is non-empty."""if n_values <= 0:raise ValueError(f"n_values must be a positive integer, got {n_values}")G = nx.DiGraph()20 unmodified lines212223242526272820 unmodified linesthat edge is dropped (``G.remove_edge``) and a debug log is emitted — earlier edgesare never removed. Variable order follows a topological sort when the retained graph is non-empty."""if not isinstance(n_values, int) or n_values <= 0:raise ValueError(f"n_values must be a positive integer, got {n_values!r}")G = nx.DiGraph()
24 unmodified lines25262728293040 unmodified lines71727374757677787980818283848565 unmodified lines15115215315415515615715815916016116216393 unmodified lines25725825926026126226323 unmodified lines28728828929029129234 unmodified lines32732832933033133233340 unmodified lines37437537637737837938038138238338438538638724 unmodified linesfrom itertools import productclass CausalMechanism:"""A single causal mechanism: V_i := f_i(parents, noise).40 unmodified linesreturn self.cpt_params / self.cpt_params.sum(axis=0, keepdims=True)def parent_config_index(self, parent_values: Dict[str, int]) -> int:"""Convert parent values to a CPT column index."""if not self.parents:return 0idx = 0stride = 1for p, card in zip(self.parents, self.parent_cardinalities):value = int(parent_values.get(p, 0))idx += (value % max(int(card), 1)) * stridestride *= max(int(card), 1)65 unmodified linesdef add_variable(self, name: str, n_values: int = 4,parents: Optional[List[str]] = None,noise_scale: float = 0.1):"""Add a variable with its causal mechanism."""parents = parents or []for parent in parents:if parent not in self.graph:# Auto-create parent as root node with the child's cardinality.self.add_variable(parent, n_values)parent_cardinalities = [self.mechanisms[p].n_values for p in parents]93 unmodified linesdef counterfactual(self, evidence: Dict[str, int],interventions: Dict[str, int],query: List[str]) -> Dict[str, np.ndarray]:"""Rung 3 — Counterfactual: P(Y_{do(x)} | observed evidence).23 unmodified linesif not posterior_worlds:return cf_resultsorder = self.topological_order()affected: Set[str] = set()for var in interventions:34 unmodified linesupdated[var] = int(v)next_worlds.append((updated, weight * float(p_v)))worlds = next_worldsfor values, weight in worlds:for q in cf_results:40 unmodified linesdef _joint_probability(self, assignment: Dict[str, int]) -> float:"""P(assignment) under the SCM, assuming all variables are assigned."""prob = 1.0for var in self.topological_order():mech = self.mechanisms[var]parent_vals = {p: assignment[p] for p in mech.parents}prob *= float(np.exp(mech.log_prob(assignment[var], parent_vals)))if prob <= 0.0:return 0.0return float(prob)def _enumerate_joint_assignments(self,24 unmodified lines2526272829303132333435363740 unmodified lines7879808182838485868788899091929394959697989965 unmodified lines16516616716816917017117217317417517617717817918018118218318418593 unmodified lines27928028128228328428528628728828923 unmodified lines31331431531631731831932034 unmodified lines35535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439540 unmodified lines43643743843944044144244344444544644744844945045145224 unmodified linesfrom itertools import productclass ControlledExpansionError(RuntimeError):"""Raised when counterfactual world enumeration exceeds a configured limit."""# Default safeguard for branching in ``StructuralCausalModel.counterfactual``._DEFAULT_MAX_CF_WORLDS = 250_000class CausalMechanism:"""A single causal mechanism: V_i := f_i(parents, noise).40 unmodified linesreturn self.cpt_params / self.cpt_params.sum(axis=0, keepdims=True)def parent_config_index(self, parent_values: Dict[str, int]) -> int:"""Convert parent values to a CPT column index. All listed parents must be present."""if not self.parents:return 0missing = [p for p in self.parents if p not in parent_values]if missing:raise KeyError(f"CausalMechanism({self.name!r}): parent_values missing keys {missing}; "f"expected all of {list(self.parents)}")idx = 0stride = 1for p, card in zip(self.parents, self.parent_cardinalities):value = int(parent_values[p])idx += (value % max(int(card), 1)) * stridestride *= max(int(card), 1)65 unmodified linesdef add_variable(self, name: str, n_values: int = 4,parents: Optional[List[str]] = None,noise_scale: float = 0.1):"""Add a variable with its causal mechanism.Every ``parent`` must already exist — call ``add_variable`` for parents firstwith the desired ``n_values``. Parent cardinalities in CPT indexing come from``self.mechanisms[parent].n_values``."""parents = parents or []missing = [p for p in parents if p not in self.graph]if missing:raise ValueError(f"{self.name}: undefined parent variable(s) {missing} for '{name}'. ""Declare each parent with add_variable(name, n_values=...) before ""listing it in parents=[...].")parent_cardinalities = [self.mechanisms[p].n_values for p in parents]93 unmodified linesdef counterfactual(self, evidence: Dict[str, int],interventions: Dict[str, int],query: List[str],*,max_cf_worlds: Optional[int] = None,prune_relative_weight_floor: Optional[float] = None,prune_worlds_top_k: Optional[int] = None) -> Dict[str, np.ndarray]:"""Rung 3 — Counterfactual: P(Y_{do(x)} | observed evidence).23 unmodified linesif not posterior_worlds:return cf_resultsml = _DEFAULT_MAX_CF_WORLDS if max_cf_worlds is None else max(1, int(max_cf_worlds))order = self.topological_order()affected: Set[str] = set()for var in interventions:34 unmodified linesupdated[var] = int(v)next_worlds.append((updated, weight * float(p_v)))if len(next_worlds) > ml:raise ControlledExpansionError(f"{self.name}: counterfactual branch count {len(next_worlds)} exceeds "f"max_cf_worlds={ml}; reduce SCM size / intervention breadth, ""or raise max_cf_worlds / use prune_worlds_top_k.")worlds = next_worldsif prune_worlds_top_k is not None and int(prune_worlds_top_k) > 0:tk = int(prune_worlds_top_k)if len(worlds) > tk:tot_before = sum(w for _, w in worlds)worlds = sorted(worlds, key=lambda t: -t[1])[:tk]tot_after = sum(w for _, w in worlds)if tot_before > 0 and tot_after > 0 and tot_after < tot_before:scale = tot_before / tot_afterworlds = [(a, float(w * scale)) for a, w in worlds]if prune_relative_weight_floor is not None:pq = float(prune_relative_weight_floor)if pq > 0.0 and worlds:mass = sum(w for _, w in worlds)if mass > 0:thresh = pq * masskept = [(a, w) for a, w in worlds if w >= thresh]if kept:m2 = sum(w for _, w in kept)if m2 < mass > 0 and m2 > 0:scale = mass / m2worlds = [(a, w * scale) for a, w in kept]elif m2 <= 0:raise ControlledExpansionError(f"{self.name}: counterfactual pruning eliminated all worlds "f"(increase prune_relative_weight_floor beyond {thresh}).")else:worlds = keptfor values, weight in worlds:for q in cf_results:40 unmodified linesdef _joint_probability(self, assignment: Dict[str, int]) -> float:"""P(assignment) under the SCM, assuming all variables are assigned."""log_joint = 0.0for var in self.topological_order():mech = self.mechanisms[var]parent_vals = {p: assignment[p] for p in mech.parents}ell = float(mech.log_prob(assignment[var], parent_vals))if not np.isfinite(ell):return 0.0log_joint += ellif not np.isfinite(log_joint) or log_joint < -900.0:return float(np.exp(max(log_joint, -900.0)))return float(np.exp(log_joint))def _enumerate_joint_assignments(self,
2 unmodified lines3456789102 unmodified linesimport warningswarnings.warn("tensegrity.core.morton is legacy V1; use tensegrity.legacy.v1.morton ""for the old Morton-coded frontend.",DeprecationWarning,stacklevel=2,)2 unmodified lines345678910112 unmodified linesimport warningswarnings.warn("tensegrity.core.morton is legacy V1; import from tensegrity.legacy.v1.morton ""for the Morton-coded frontend (same API — re-export only). There is no ""alternative module beyond legacy.v1 for this shim.",DeprecationWarning,stacklevel=2,)
15 unmodified lines16171819202153 unmodified lines7576777879808114 unmodified lines9697989910010110210310410510610710810911011144 unmodified lines15615715815916016116280 unmodified lines24324424524624724824912 unmodified lines26226326426526626726815 unmodified linesimport numpy as npfrom dataclasses import dataclass, fieldfrom typing import Dict, List, Any, Optional, Tupleimport networkx as nxfrom tensegrity.causal.scm import StructuralCausalModel53 unmodified linessource: strtarget: strlayer: intchildren: Tuple[str, str]@dataclass14 unmodified linesvirtual_parents: Dict[str, VirtualParent] = field(default_factory=dict)original_edges: List[Tuple[str, str]] = field(default_factory=list)@propertydef layer_nodes(self) -> Dict[int, List[str]]:layers: Dict[int, List[str]] = {}for node, layer in self.embedded_layers.items():layers.setdefault(layer, []).append(node)for nodes in layers.values():nodes.sort()return dict(sorted(layers.items()))def ngc_layer_sizes(self, min_width: int = 1) -> List[int]:44 unmodified lines"""Embed arbitrary SCM DAG topology into hierarchical predictive-coding wiring.The mapper makes the Friston/Pearl handshake explicit:* A causal edge from layer k to k-1 becomes a direct top-down prediction.* A bypass edge spanning multiple layers receives relay nodes, one per80 unmodified linescontinuevirtual_layer = max(source_layer, target_layer) + 1if n_layers is not None and virtual_layer >= n_layers and not self.expand_layers:raise ValueError(f"edge {source!r}->{target!r} needs virtual parent layer {virtual_layer}, "12 unmodified linessource=source,target=target,layer=virtual_layer,children=(source, target),)virtual_parents[virtual] = vp15 unmodified lines1617181920212253 unmodified lines767778798081828384858614 unmodified lines10110210310410510610710810911011111211311411511644 unmodified lines16116216316416516616716816917017117217317417517617780 unmodified lines25825926026126226326412 unmodified lines27727827928028128215 unmodified linesimport numpy as npfrom dataclasses import dataclass, fieldfrom functools import cached_propertyfrom typing import Dict, List, Any, Optional, Tupleimport networkx as nxfrom tensegrity.causal.scm import StructuralCausalModel53 unmodified linessource: strtarget: strlayer: int@propertydef children(self) -> Tuple[str, str]:"""The two SCM variables summarized by this virtual parent."""return (self.source, self.target)@dataclass14 unmodified linesvirtual_parents: Dict[str, VirtualParent] = field(default_factory=dict)original_edges: List[Tuple[str, str]] = field(default_factory=list)@cached_propertydef layer_nodes(self) -> Dict[int, List[str]]:layers: Dict[int, List[str]] = {}for node, layer in self.embedded_layers.items():layers.setdefault(layer, []).append(node)for nodes in layers.values():nodes.sort()return dict(sorted(layers.items()))def ngc_layer_sizes(self, min_width: int = 1) -> List[int]:44 unmodified lines"""Embed arbitrary SCM DAG topology into hierarchical predictive-coding wiring.Constructor flag ``expand_layers`` interacts with ``n_layers``:- When ``expand_layers`` is **False**, a lateral or same-layer edge requiring a virtualparent strictly above ``n_layers - 1`` raises ``ValueError`` (no implicit layer growth).- When ``expand_layers`` is **True**, virtual-parent nodes **may occupy layer indices equalto or **greater than** ``n_layers - 1** as needed — the mapper extends the conceptualhierarchy upward so horizontal dependencies become shared parents. Caller layer counts(e.g. ``ngc_layer_sizes``) must account for the actual maximum embedded layer index.The mapper otherwise makes the Friston/Pearl handshake explicit:* A causal edge from layer k to k-1 becomes a direct top-down prediction.* A bypass edge spanning multiple layers receives relay nodes, one per80 unmodified linescontinuevirtual_layer = max(source_layer, target_layer) + 1if n_layers is not None and virtual_layer >= n_layers and not self.expand_layers:raise ValueError(f"edge {source!r}->{target!r} needs virtual parent layer {virtual_layer}, "12 unmodified linessource=source,target=target,layer=virtual_layer,)virtual_parents[virtual] = vp
18 unmodified lines192021222324252666 unmodified lines93949596979850 unmodified lines149150151152153154155156157158159102 unmodified lines26226326426526626726826915 unmodified lines28528628728828929029129229329429529629729829930030130230330418 unmodified lines"""import hashlibimport numpy as npfrom typing import Optional, List, Tuple, Dict, Unionimport logginglogger = logging.getLogger(__name__)66 unmodified linesreturn [(f"#{int(i)}", float(sims[i])) for i in top_idx]class SemanticFHRRCodebook(FHRRCodebook):"""50 unmodified linesself._proj /= np.sqrt(self._sbert_dim)logger.info(f"SemanticFHRR: loaded {self._sbert_model_name} "f"(dim={self._sbert_dim}) → FHRR(dim={self.dim})")except Exception as exc:logger.warning("SemanticFHRR: falling back to deterministic random vectors (%s)", exc)self._sbert = "FALLBACK"self._proj = Nonedef _embed_to_phasor(self, embedding: np.ndarray) -> np.ndarray:projected = self._proj @ embedding.astype(np.float32)proj_std = np.std(projected)102 unmodified linesself.features = SemanticFHRRCodebook(dim=dim, sbert_model=sbert_model) if semantic \else FHRRCodebook(n_features, dim, seed=3000)self._position_cache: Dict[int, np.ndarray] = {}self._position_cache_max = 4096for role in ["position", "value", "type", "attribute", "relation","subject", "object", "time", "channel"]:15 unmodified linesdef encode_position(self, x: int) -> np.ndarray:x = int(x)cached = self._position_cache.get(x)if cached is not None:return cached.copy()result = np.ones(self.dim, dtype=np.complex64)for base, m in zip(self._pos_bases, self.moduli):result = result * (base ** (x % m))if len(self._position_cache) < self._position_cache_max:self._position_cache[x] = result.copy()return resultdef encode_value(self, value: float, precision: int = 100) -> np.ndarray:return self.encode_position(int(round(value * precision)))18 unmodified lines1920212223242526272866 unmodified lines959697989910010110210310410510610750 unmodified lines158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191102 unmodified lines29429529629729829930030130215 unmodified lines31831932032132232332432532632732832933033133233333433533633733833934018 unmodified lines"""import hashlibimport threadingfrom collections import OrderedDictimport numpy as npfrom typing import Any, Optional, List, Tuple, Dict, Unionimport logginglogger = logging.getLogger(__name__)66 unmodified linesreturn [(f"#{int(i)}", float(sims[i])) for i in top_idx]def get_sbert_model(self) -> Optional[Any]:"""Non-semantic codebook has no SBERT model."""return Nonedef has_sbert(self) -> bool:return Falseclass SemanticFHRRCodebook(FHRRCodebook):"""50 unmodified linesself._proj /= np.sqrt(self._sbert_dim)logger.info(f"SemanticFHRR: loaded {self._sbert_model_name} "f"(dim={self._sbert_dim}) → FHRR(dim={self.dim})")except ImportError as exc:logger.warning("SemanticFHRR: sentence_transformers unavailable (%s); deterministic vectors",exc,)self._sbert = "FALLBACK"self._proj = Noneexcept OSError as exc:logger.warning("SemanticFHRR: SBERT model load failed (%s); deterministic vectors",exc,)self._sbert = "FALLBACK"self._proj = Noneexcept Exception:logger.exception("SemanticFHRR: unexpected error loading SBERT")raisedef get_sbert_model(self) -> Optional[Any]:"""Return the loaded ``SentenceTransformer`` when available; else ``None``."""self._ensure_sbert()if self._sbert is None or self._sbert == "FALLBACK":return Nonereturn self._sbertdef has_sbert(self) -> bool:return self.get_sbert_model() is not Nonedef _embed_to_phasor(self, embedding: np.ndarray) -> np.ndarray:projected = self._proj @ embedding.astype(np.float32)proj_std = np.std(projected)102 unmodified linesself.features = SemanticFHRRCodebook(dim=dim, sbert_model=sbert_model) if semantic \else FHRRCodebook(n_features, dim, seed=3000)self._position_cache: OrderedDict[int, np.ndarray] = OrderedDict()self._position_cache_max = 4096self._position_cache_lock = threading.Lock()for role in ["position", "value", "type", "attribute", "relation","subject", "object", "time", "channel"]:15 unmodified linesdef encode_position(self, x: int) -> np.ndarray:x = int(x)with self._position_cache_lock:cached = self._position_cache.get(x)if cached is not None:self._position_cache.move_to_end(x)return cached.copy()result = np.ones(self.dim, dtype=np.complex64)for base, m in zip(self._pos_bases, self.moduli):result = result * (base ** (x % m))copied = result.copy()with self._position_cache_lock:while len(self._position_cache) >= self._position_cache_max:self._position_cache.popitem(last=False)self._position_cache[x] = copiedreturn copied.copy()def encode_value(self, value: float, precision: int = 100) -> np.ndarray:return self.encode_position(int(round(value * precision)))
389 unmodified lines390391392393394395389 unmodified lines"""Drop recorded energy / error traces."""self.energy_history.clear()self.error_history.clear()def reinitialize(self, weight_seed: int = 12345) -> None:"""Reset layer states and resample W/E."""389 unmodified lines390391392393394395396397398399400401402389 unmodified lines"""Drop recorded energy / error traces."""self.energy_history.clear()self.error_history.clear()def soft_reset(self) -> None:"""Clear layer activations and history without resampling prediction weights."""self.layers = []self._initialized = Falseself._last_obs = Noneself.clear_history()def reinitialize(self, weight_seed: int = 12345) -> None:"""Reset layer states and resample W/E."""
273 unmodified lines2742752762772782792808 unmodified lines289290291292293294273 unmodified linesif hasattr(features, '_ensure_sbert') and getattr(features, '_sbert', None) is None:features._ensure_sbert()if hasattr(features, '_sbert') and features._sbert is not None and features._sbert != "FALLBACK":features._ensure_sbert()embs = features._sbert.encode([prompt] + choices, show_progress_bar=False)pe, pn = embs[0], np.linalg.norm(embs[0])return [float(np.dot(pe, embs[i+1]) / (pn * np.linalg.norm(embs[i+1])))8 unmodified linesout.append(self.field.encoder.similarity(pf, enc))return outdef reset(self):self.field.ngc.reinitialize(12345)self.field.memory.patterns.clear()273 unmodified lines2742752762772782798 unmodified lines288289290291292293294295296297273 unmodified linesif hasattr(features, '_ensure_sbert') and getattr(features, '_sbert', None) is None:features._ensure_sbert()if hasattr(features, '_sbert') and features._sbert is not None and features._sbert != "FALLBACK":embs = features._sbert.encode([prompt] + choices, show_progress_bar=False)pe, pn = embs[0], np.linalg.norm(embs[0])return [float(np.dot(pe, embs[i+1]) / (pn * np.linalg.norm(embs[i+1])))8 unmodified linesout.append(self.field.encoder.similarity(pf, enc))return outdef sentence_similarities(self, prompt, choices):"""Public alias for SBERT/FHRR sentence-level similarity tie-breaks (see ``_sentence_similarities``)."""return self._sentence_similarities(prompt, choices)def reset(self):self.field.ngc.reinitialize(12345)self.field.memory.patterns.clear()
24 unmodified lines252627282930313233343531 unmodified lines6768697071727337 unmodified lines11111211311411511624 unmodified linesfrom the composition of these local optimizations."""import numpy as npfrom typing import Dict, List, Optional, Any, Tuple, Dequefrom dataclasses import dataclassfrom collections import dequefrom .fhrr import FHRREncoder, bind, bundle, unbindfrom .ngc import PredictiveCodingCircuit31 unmodified linesself.patterns: deque = deque(maxlen=capacity)self._matrix: Optional[np.ndarray] = Noneself._dirty = Truedef store(self, pattern: np.ndarray, normalize: bool = True):"""Store a pattern (FHRR vector — use real part for Hopfield)."""p = np.real(pattern).astype(np.float64) if np.iscomplexobj(pattern) else pattern.astype(np.float64)37 unmodified lines# Energysims = self._matrix.T @ xiif self.beta <= 1e-12:energy = float(0.5 * np.dot(xi, xi) - np.mean(sims))else:log_sum_exp = np.log(np.sum(np.exp(self.beta * sims - self.beta * sims.max()))) + self.beta * sims.max()24 unmodified lines252627282930313233343536373831 unmodified lines7071727374757677787980818237 unmodified lines12012112212312412512612712812913013124 unmodified linesfrom the composition of these local optimizations."""import loggingimport numpy as npfrom typing import Dict, List, Optional, Any, Tuple, Dequefrom dataclasses import dataclassfrom collections import deque_logger = logging.getLogger(__name__)from .fhrr import FHRREncoder, bind, bundle, unbindfrom .ngc import PredictiveCodingCircuit31 unmodified linesself.patterns: deque = deque(maxlen=capacity)self._matrix: Optional[np.ndarray] = Noneself._dirty = Truedef clear(self) -> None:"""Remove all stored patterns; invalidate the pattern matrix cache."""self.patterns.clear()self._matrix = Noneself._dirty = Truedef store(self, pattern: np.ndarray, normalize: bool = True):"""Store a pattern (FHRR vector — use real part for Hopfield)."""p = np.real(pattern).astype(np.float64) if np.iscomplexobj(pattern) else pattern.astype(np.float64)37 unmodified lines# Energysims = self._matrix.T @ xiif self.beta <= 1e-12:_logger.warning("HopfieldMemoryBank.retrieve: self.beta=%g is near zero; ""energy uses approximate uniform-attention form ""(0.5||xi||² - mean(sims)) instead of -lse/beta)",float(self.beta),)energy = float(0.5 * np.dot(xi, xi) - np.mean(sims))else:log_sum_exp = np.log(np.sum(np.exp(self.beta * sims - self.beta * sims.max()))) + self.beta * sims.max()
21 unmodified lines22232425262721 unmodified lines)def __getattr__(name: str) -> Any:if name == "HybridPipeline":value = getattr(import_module("tensegrity.graft.pipeline"), name)21 unmodified lines222324252627282930313221 unmodified lines)def __dir__():merged = set(globals().keys()) | set(__all__)return sorted(merged)def __getattr__(name: str) -> Any:if name == "HybridPipeline":value = getattr(import_module("tensegrity.graft.pipeline"), name)
37 unmodified lines38394041424348 unmodified lines92939495969798996 unmodified lines1061071081091101111121135 unmodified lines119120121122123124118 unmodified lines24324424524624724852 unmodified lines3013023033043053066 unmodified lines31331431531631731831919 unmodified lines33934034134234334437 unmodified lineslogger = logging.getLogger(__name__)# Import torch lazily — only needed when actually grafting to a local modeltorch = None48 unmodified lines"""Args:hypothesis_tokens: {hyp_id: set of token_ids} from VocabularyGroundinghypothesis_token_scores: optional semantic weights per token fromVocabularyGrounding.from_semantic_projectionbelief_fn: Callable that returns current posteriors {hyp_id: probability}Sync mode: called each decode step. Async mode: polled in a worker thread.vocab_size: LLM vocabulary size6 unmodified linesasync_beliefs: If True, belief_fn runs in a daemon thread; __call__ is O(1) bias addbelief_poll_s: Sleep between async polls (seconds)"""_ensure_torch()self.hypothesis_tokens = hypothesis_tokensself.hypothesis_token_scores = hypothesis_token_scores or {}self.belief_fn = belief_fn5 unmodified linesself.max_bias = max_biasself.async_beliefs = async_beliefsself.belief_poll_s = belief_poll_s# State trackingself.state = GraftState()118 unmodified linesif 0 <= tid < self.vocab_size:if not np.isneginf(bias[tid]):weighted_b = b * float(token_scores.get(tid, 1.0))bias[tid] += weighted_bif weighted_b > 0:boosted += 152 unmodified linesBuilds a static logit_bias dict from the current belief state.Less powerful than the LogitsProcessor (no per-step updates),but works with any OpenAI-compatible API."""def __init__(self, hypothesis_tokens: Dict[str, Set[int]],6 unmodified linesself.scale = scaleself.suppress_threshold = suppress_thresholdself.max_bias = max_biasdef build(self, posteriors: Dict[str, float]) -> Dict[int, float]:"""Build a static logit_bias dict for API calls.19 unmodified linesb = max(-self.max_bias, min(self.max_bias, b))for tid in token_ids:weighted_b = b * float(token_scores.get(tid, 1.0))bias[tid] = bias.get(tid, 0.0) + weighted_breturn bias37 unmodified lines3839404142434445464748495051525354555657585960616263646548 unmodified lines1141151161171181191201211221231241256 unmodified lines1321331341351361375 unmodified lines143144145146147148149150151152153118 unmodified lines27227327427527627727852 unmodified lines3313323333343353363373383393403416 unmodified lines34834935035135235335435535635735819 unmodified lines37837938038138238338437 unmodified lineslogger = logging.getLogger(__name__)def _validate_hypothesis_token_scores_weights(hypothesis_token_scores: Optional[Dict[str, Dict[int, float]]],*,context: str,) -> None:"""``hypothesis_token_scores`` weights must lie in **[0.0, 1.0]** (see graft docstrings)."""if not hypothesis_token_scores:returnbad = []for hyp_id, m in hypothesis_token_scores.items():for tid, w in m.items():wf = float(w)if not (0.0 <= wf <= 1.0):bad.append(f"{hyp_id}[{tid}]={wf!r}")if bad:raise ValueError(f"{context}: each hypothesis_token_scores value must be in [0.0, 1.0]; "f"misconfigured entries (showing up to 12): {bad[:12]}")# Import torch lazily — only needed when actually grafting to a local modeltorch = None48 unmodified lines"""Args:hypothesis_tokens: {hyp_id: set of token_ids} from VocabularyGroundinghypothesis_token_scores: optional per-token **weights** in **[0.0, 1.0]**from ``VocabularyGrounding.from_semantic_projection`` (stored on``VocabularyGrounding.hypothesis_token_scores``).**0.0** applies no incremental bias mass to that token; **1.0** applies thefull clamped hypothesis bias ``b`` before per-token stacking. Values outside``[0.0, 1.0]`` raise ``ValueError`` at processor construction time.belief_fn: Callable that returns current posteriors {hyp_id: probability}Sync mode: called each decode step. Async mode: polled in a worker thread.vocab_size: LLM vocabulary size6 unmodified linesasync_beliefs: If True, belief_fn runs in a daemon thread; __call__ is O(1) bias addbelief_poll_s: Sleep between async polls (seconds)"""self.hypothesis_tokens = hypothesis_tokensself.hypothesis_token_scores = hypothesis_token_scores or {}self.belief_fn = belief_fn5 unmodified linesself.max_bias = max_biasself.async_beliefs = async_beliefsself.belief_poll_s = belief_poll_s_validate_hypothesis_token_scores_weights(self.hypothesis_token_scores,context="TensegrityLogitsProcessor",)# State trackingself.state = GraftState()118 unmodified linesif 0 <= tid < self.vocab_size:if not np.isneginf(bias[tid]):weighted_b = b * float(token_scores.get(tid, 1.0))weighted_b = max(-self.max_bias, min(self.max_bias, weighted_b))bias[tid] += weighted_bif weighted_b > 0:boosted += 152 unmodified linesBuilds a static logit_bias dict from the current belief state.Less powerful than the LogitsProcessor (no per-step updates),but works with any OpenAI-compatible API.``hypothesis_token_scores`` matches ``TensegrityLogitsProcessor``: optional``{hyp_id: {token_id: weight}}`` with each **weight** in **[0.0, 1.0]** —cosine-style scores must be scaled before injection (see``VocabularyGrounding.from_semantic_projection``, which emits [0.0, 1.0] weights)."""def __init__(self, hypothesis_tokens: Dict[str, Set[int]],6 unmodified linesself.scale = scaleself.suppress_threshold = suppress_thresholdself.max_bias = max_bias_validate_hypothesis_token_scores_weights(self.hypothesis_token_scores,context="StaticLogitBiasBuilder",)def build(self, posteriors: Dict[str, float]) -> Dict[int, float]:"""Build a static logit_bias dict for API calls.19 unmodified linesb = max(-self.max_bias, min(self.max_bias, b))for tid in token_ids:weighted_b = b * float(token_scores.get(tid, 1.0))weighted_b = max(-self.max_bias, min(self.max_bias, weighted_b))bias[tid] = bias.get(tid, 0.0) + weighted_breturn bias
37 unmodified lines3839404142434445464712 unmodified lines60616263646512 unmodified lines78798081828384856 unmodified lines92939495969715 unmodified lines1131141151161171185 unmodified lines1241251261271281293 unmodified lines1331341351361371386 unmodified lines14514614714814915015115215315415515615715815916016116216316416516616716816937 unmodified linesclass HybridPipeline:"""Tensegrity+LLM hybrid generation.The cognitive layer resolves beliefs. The LLM narrates the resolution.Logit biases bridge the gap — no beliefs in the prompt, no reasoningdelegated to the LLM."""def __init__(12 unmodified lines# not available at runtime we fall back to keyword grounding.semantic_grounding: bool = True,semantic_embedding_fn: Optional[Callable[[str], np.ndarray]] = None,semantic_top_k: int = 32,semantic_threshold: Optional[float] = None,):12 unmodified linesasync_graft: Local mode only — poll beliefs in a background thread for non-blocking decodesemantic_grounding: If True, build grounding by frozen semanticphrase/token projection instead of exact keyword tokenizationsemantic_embedding_fn: Required when semantic_grounding=True; mapstext to a fixed embedding vector without runtime trainingsemantic_top_k: Semantic vocabulary tokens retained per hypothesissemantic_threshold: Optional minimum cosine similarity for semantic grounding"""6 unmodified linesself.async_graft = async_graftself.semantic_grounding = semantic_groundingself.semantic_embedding_fn = semantic_embedding_fnself.semantic_top_k = semantic_top_kself.semantic_threshold = semantic_threshold15 unmodified lines# Generation trackingself._generations = 0self._graft_states: List[GraftState] = []def _label_phrases(self) -> Dict[str, List[str]]:phrases = {}5 unmodified linesdef _build_grounding(self) -> VocabularyGrounding:if self.semantic_grounding:embed = self.semantic_embedding_fn or self._default_sbert_embed_fn()if embed is not None:phrases = self._hypothesis_keywords or self._label_phrases()try:3 unmodified linesembedding_fn=embed,top_k=self.semantic_top_k,threshold=self.semantic_threshold,)except Exception as e:logger.warning(6 unmodified linesself.hypothesis_labels, self._tokenizer)def _default_sbert_embed_fn(self) -> Optional[Callable[[str], np.ndarray]]:"""Build a frozen sbert embedding function. Used when the caller didnot pass an explicit semantic_embedding_fn. No gradient flow.Uses a bulk-prefetch cache: on first invocation, batch-encodes theentire LLM vocabulary in one shot (a few seconds for ~128k tokenson CPU) so the per-token loop in SemanticProjectionLayer.from_tokenizerbecomes a dict lookup instead of 128k individual sbert calls."""try:from sentence_transformers import SentenceTransformerexcept Exception as e:logger.warning("sentence_transformers unavailable (%s); semantic grounding off", e)return Nonetry:model = SentenceTransformer("all-MiniLM-L6-v2")except Exception as e:logger.warning("could not load sbert (%s); semantic grounding off", e)return Nonecache: Dict[str, np.ndarray] = {}bulk_done = [False]37 unmodified lines38394041424344454647484950515253545512 unmodified lines686970717273747512 unmodified lines8889909192939495969798996 unmodified lines10610710810911011111211315 unmodified lines1291301311321331341355 unmodified lines1411421431441451461471481493 unmodified lines1531541551561571581596 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220337 unmodified linesclass HybridPipeline:"""Tensegrity+LLM hybrid generation.The cognitive layer resolves beliefs. The LLM narrates the resolution.Logit biases bridge the gap — no beliefs in the prompt, no reasoningdelegated to the LLM.**Memory:** When using the default SBERT embedder (``semantic_embedding_fn``unset with ``semantic_grounding=True``), the returned closure from``_default_sbert_embed_fn`` holds a ``SentenceTransformer`` for thepipeline's lifetime. That model can stay resident on GPU and consumeVRAM. Mitigations: set ``sbert_device='cpu'``, pass a smaller``sbert_model_name``, or supply a custom ``semantic_embedding_fn`` thatdoes not pin a large model (e.g. remote API, smaller encoder, on-demand load)."""def __init__(12 unmodified lines# not available at runtime we fall back to keyword grounding.semantic_grounding: bool = True,semantic_embedding_fn: Optional[Callable[[str], np.ndarray]] = None,sbert_model_name: str = "all-MiniLM-L6-v2",sbert_device: Optional[str] = None,semantic_top_k: int = 32,semantic_threshold: Optional[float] = None,):12 unmodified linesasync_graft: Local mode only — poll beliefs in a background thread for non-blocking decodesemantic_grounding: If True, build grounding by frozen semanticphrase/token projection instead of exact keyword tokenizationsemantic_embedding_fn: Optional when ``semantic_grounding`` is True. If omitted,``_build_grounding()`` supplies :func:`_default_sbert_embed_fn` using``sbert_model_name`` / ``sbert_device``. Pass an explicit callable to avoid thelong-lived SBERT model or customize embeddings.sbert_model_name: sentence-transformers model ID for the default semantic embeddersbert_device: Optional device hint for SBERT (e.g. ``"cpu"`` to avoid GPU residency)semantic_top_k: Semantic vocabulary tokens retained per hypothesissemantic_threshold: Optional minimum cosine similarity for semantic grounding"""6 unmodified linesself.async_graft = async_graftself.semantic_grounding = semantic_groundingself.semantic_embedding_fn = semantic_embedding_fnself.sbert_model_name = sbert_model_nameself.sbert_device = sbert_deviceself.semantic_top_k = semantic_top_kself.semantic_threshold = semantic_threshold15 unmodified lines# Generation trackingself._generations = 0self._graft_states: List[GraftState] = []self._sbert_vocab_batch_fn: Optional[Callable[[List[str]], np.ndarray]] = Nonedef _label_phrases(self) -> Dict[str, List[str]]:phrases = {}5 unmodified linesdef _build_grounding(self) -> VocabularyGrounding:if self.semantic_grounding:embed = self.semantic_embedding_fn or self._default_sbert_embed_fn()vocab_batch = getattr(self, "_sbert_vocab_batch_fn", None)if self.semantic_embedding_fn is not None:vocab_batch = Noneif embed is not None:phrases = self._hypothesis_keywords or self._label_phrases()try:3 unmodified linesembedding_fn=embed,top_k=self.semantic_top_k,threshold=self.semantic_threshold,vocab_batch_embedding_fn=vocab_batch,)except Exception as e:logger.warning(6 unmodified linesself.hypothesis_labels, self._tokenizer)def _default_sbert_embed_fn(self) -> Optional[Callable[[str], np.ndarray]]:"""Return a callable that maps text → embedding via sentence-transformers.The closure captures ``model`` (:class:`~sentence_transformers.SentenceTransformer`)for the pipeline's lifetime, so embeddings stay cheap after warm-up but themodel may hold GPU memory. Use ``sbert_device='cpu'``, a lighter``sbert_model_name``, or pass ``semantic_embedding_fn`` to avoid pinningSBERT entirely."""try:from sentence_transformers import SentenceTransformerexcept Exception as e:logger.warning("sentence_transformers unavailable (%s); semantic grounding off", e)self._sbert_vocab_batch_fn = Nonereturn Nonetry:st_kw: Dict[str, Any] = {}if self.sbert_device is not None:st_kw["device"] = self.sbert_devicemodel = SentenceTransformer(self.sbert_model_name, **st_kw)except Exception as e:logger.warning("could not load sbert (%s); semantic grounding off", e)self._sbert_vocab_batch_fn = Nonereturn Nonedef _vocab_batch_encode(batch: List[str]) -> np.ndarray:return np.asarray(model.encode(batch, batch_size=256, show_progress_bar=False),dtype=np.float32,)self._sbert_vocab_batch_fn = _vocab_batch_encodecache: Dict[str, np.ndarray] = {}bulk_done = [False]
19 unmodified lines2021222324251 unmodified line27282930313215 unmodified lines4849505152535451 unmodified lines10610710810911011111211311411511611711811912012160 unmodified lines18218318418518618718871 unmodified lines2602612622632642657 unmodified lines2732742752762772782792802812822832848 unmodified lines29329429529629729829930030130230330430530630719 unmodified lines"""import refrom typing import Callable, Dict, Iterable, List, Set, Optional, Tuplefrom dataclasses import dataclass, field1 unmodified lineEmbeddingFn = Callable[[str], np.ndarray]def _clean_token_text(token: str) -> str:15 unmodified linesvec = np.asarray(value, dtype=np.float64).ravel()norm = float(np.linalg.norm(vec))if norm <= 1e-12:return vecreturn vec / norm51 unmodified linesembedding_fn: EmbeddingFn,projection_matrix: Optional[np.ndarray] = None,token_texts: Optional[Dict[int, str]] = None,) -> "SemanticProjectionLayer":texts = token_texts or _token_texts_from_tokenizer(tokenizer)token_vectors: Dict[int, np.ndarray] = {}for tid, text in texts.items():try:vec = _as_unit_vector(embedding_fn(text))except Exception:continueif vec.size and np.linalg.norm(vec) > 1e-12:token_vectors[int(tid)] = vecreturn cls(token_vectors=token_vectors,token_texts={int(k): v for k, v in texts.items()},60 unmodified lines# {hypothesis_id: list of grounding keywords}hypothesis_keywords: Dict[str, List[str]] = field(default_factory=dict)# {hypothesis_id: {token_id: semantic proximity in [roughly -1, 1]}}hypothesis_token_scores: Dict[str, Dict[int, float]] = field(default_factory=dict)# Inverse map: {token_id: list of hypothesis_ids it belongs to}71 unmodified linestoken_texts: Optional[Dict[int, str]] = None,top_k: int = 32,threshold: Optional[float] = None,) -> 'VocabularyGrounding':"""Build grounding by semantic proximity instead of exact keyword matches.7 unmodified linestoken_texts: optional explicit {token_id: token_text} inventory.top_k: maximum vocabulary tokens retained per hypothesis.threshold: minimum cosine similarity. ``None`` keeps the best top_k."""projection = SemanticProjectionLayer.from_tokenizer(tokenizer,embedding_fn=embedding_fn,projection_matrix=projection_matrix,token_texts=token_texts,)grounding = cls()grounding.vocab_size = int(getattr(tokenizer, "vocab_size", 0) or 0)8 unmodified linesconcept_vector = _mean_unit_vector(embedding_fn(phrase) for phrase in concept_phrases if str(phrase).strip())token_scores = projection.project_phrase_vector(concept_vector,top_k=top_k,threshold=threshold,)grounding.hypothesis_token_scores[hyp_id] = token_scoresgrounding.hypothesis_tokens[hyp_id] = set(token_scores)for tid in token_scores:grounding.token_to_hypotheses.setdefault(tid, []).append(hyp_id)return grounding19 unmodified lines202122232425261 unmodified line2829303132333435363738394041424344454647484915 unmodified lines6566676869707151 unmodified lines12312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718860 unmodified lines24925025125225325425571 unmodified lines3273283293303313323333347 unmodified lines3423433443453463473483493503513523533543553563573583598 unmodified lines36836937037137237337437537637737837938038138238338438538638738838939039139239339439539639719 unmodified lines"""import reimport loggingfrom typing import Callable, Dict, Iterable, List, Set, Optional, Tuplefrom dataclasses import dataclass, field1 unmodified lineEmbeddingFn = Callable[[str], np.ndarray]BatchedEmbedFn = Callable[[List[str]], np.ndarray]logger = logging.getLogger(__name__)def _cosine_similarity_to_graft_multiplier(score: float) -> float:"""Map cosine proximity in roughly [-1, 1] to ``hypothesis_token_scores`` weights **[0.0, 1.0]**."""return float(max(0.0, min(1.0, 0.5 * (float(score) + 1.0))))def _chunks(seq: List, size: int) -> Iterable[List]:bs = max(1, size)for i in range(0, len(seq), bs):yield seq[i:i + bs]def _clean_token_text(token: str) -> str:15 unmodified linesvec = np.asarray(value, dtype=np.float64).ravel()norm = float(np.linalg.norm(vec))if norm <= 1e-12:return np.zeros_like(vec, dtype=np.float64)return vec / norm51 unmodified linesembedding_fn: EmbeddingFn,projection_matrix: Optional[np.ndarray] = None,token_texts: Optional[Dict[int, str]] = None,*,batched_embedding_fn: Optional[BatchedEmbedFn] = None,batch_size: int = 256,) -> "SemanticProjectionLayer":texts = token_texts or _token_texts_from_tokenizer(tokenizer)token_vectors = {}tids_ordered = sorted(texts.keys(), key=lambda x: int(x))pairs = [(k, texts[k]) for k in tids_ordered]filled = Falsedef apply_rows(row_tids: List[int], vectors: np.ndarray) -> None:if vectors.ndim != 2 or vectors.shape[0] != len(row_tids):raise ValueError("batched embeddings must have shape (batch, dim)")for tid, row in zip(row_tids, vectors):vec = _as_unit_vector(np.asarray(row, dtype=np.float64))if vec.size and np.linalg.norm(vec) > 1e-12:token_vectors[int(tid)] = vecif batched_embedding_fn is not None and pairs:try:for chunk_pairs in _chunks(pairs, batch_size):chunk_strings = [p[1] for p in chunk_pairs]chunk_ids = [p[0] for p in chunk_pairs]batch_out = batched_embedding_fn(chunk_strings)mat = np.asarray(batch_out, dtype=np.float64)apply_rows(chunk_ids, mat)filled = Trueexcept Exception as e:logger.warning("batched_embedding_fn failed (%s); falling back to per-token embedding_fn",e,)token_vectors.clear()if not filled and pairs:try:maybe = embedding_fn([p[1] for p in pairs]) # type: ignore[arg-type,misc]mat = np.asarray(maybe, dtype=np.float64)ids = [p[0] for p in pairs]if mat.ndim == 2 and mat.shape[0] == len(ids):apply_rows(ids, mat)filled = Trueexcept TypeError:filled = Falseexcept Exception as e:logger.debug("embedding_fn batch call unsupported (%s); using per-token path", e)filled = Falseif not filled:for tid, text in texts.items():try:vec = _as_unit_vector(embedding_fn(text))except Exception:continueif vec.size and np.linalg.norm(vec) > 1e-12:token_vectors[int(tid)] = vecreturn cls(token_vectors=token_vectors,token_texts={int(k): v for k, v in texts.items()},60 unmodified lines# {hypothesis_id: list of grounding keywords}hypothesis_keywords: Dict[str, List[str]] = field(default_factory=dict)# Per-token multipliers **[0.0, 1.0]** for logit graft (see tensegrity.graft.logit_bias).hypothesis_token_scores: Dict[str, Dict[int, float]] = field(default_factory=dict)# Inverse map: {token_id: list of hypothesis_ids it belongs to}71 unmodified linestoken_texts: Optional[Dict[int, str]] = None,top_k: int = 32,threshold: Optional[float] = None,vocab_batch_embedding_fn: Optional[BatchedEmbedFn] = None,vocab_embedding_batch_size: int = 256,) -> 'VocabularyGrounding':"""Build grounding by semantic proximity instead of exact keyword matches.7 unmodified linestoken_texts: optional explicit {token_id: token_text} inventory.top_k: maximum vocabulary tokens retained per hypothesis.threshold: minimum cosine similarity. ``None`` keeps the best top_k.vocab_batch_embedding_fn: optional batched vocabulary embed ``list[str] -> ndarray``.vocab_embedding_batch_size: batch chunk size for ``SemanticProjectionLayer.from_tokenizer``.Token scores returned from cosine matching are normalized to graft weights in **[0.0, 1.0]**(affine map from ``[-1, 1]`` cosine range) before storage in ``hypothesis_token_scores``."""projection = SemanticProjectionLayer.from_tokenizer(tokenizer,embedding_fn=embedding_fn,projection_matrix=projection_matrix,token_texts=token_texts,batched_embedding_fn=vocab_batch_embedding_fn,batch_size=max(1, int(vocab_embedding_batch_size)),)grounding = cls()grounding.vocab_size = int(getattr(tokenizer, "vocab_size", 0) or 0)8 unmodified linesconcept_vector = _mean_unit_vector(embedding_fn(phrase) for phrase in concept_phrases if str(phrase).strip())if (concept_vector.size == 0or float(np.linalg.norm(concept_vector)) <= 1e-12):logger.warning("empty or zero-norm concept vector for hypothesis %r phrases=%s; ""skipping projection",hyp_id,hypothesis_phrases.get(hyp_id, phrases),)grounding.hypothesis_token_scores[hyp_id] = {}grounding.hypothesis_tokens[hyp_id] = set()continuetoken_scores = projection.project_phrase_vector(concept_vector,top_k=top_k,threshold=threshold,)grounding.hypothesis_token_scores[hyp_id] = {tid: _cosine_similarity_to_graft_multiplier(s) for tid, s in token_scores.items()}grounding.hypothesis_tokens[hyp_id] = set(grounding.hypothesis_token_scores[hyp_id])for tid in grounding.hypothesis_token_scores[hyp_id]:grounding.token_to_hypotheses.setdefault(tid, []).append(hyp_id)return grounding
123
123"""Legacy compatibility modules for architectures superseded by the unified field."""__all__ = ("v1",)12345"""Legacy compatibility modules for architectures superseded by the unified field."""from . import v1__all__ = ("v1",)
16 unmodified lines17181920212273 unmodified lines9697989910010199 unmodified lines201202203204205206207134 unmodified lines34234334434534634734834941 unmodified lines39139239339439539639739839940040140238 unmodified lines44144244344444544644744816 unmodified lines"""import hashlibimport numpy as npfrom typing import Optional, Dict, List, Any, Tupleimport logging73 unmodified linesepistemic_tension_threshold: Only run costly intervention search when causal tension exceeds this levelepistemic_info_gain_threshold: Minimum estimated information gain required for epistemic actions"""self.n_states = n_statesself.n_obs = n_observationsself.n_actions = n_actions99 unmodified linesself.arena.register_model(model_b)def _morton_to_obs_index(self, morton_codes: np.ndarray) -> int:"""Map Morton codes to observation index via modular hashing."""if isinstance(morton_codes, (int, np.integer)):return int(morton_codes) % self.n_obs# For multiple codes, hash the combination134 unmodified lines# Compare epistemic value of experiment vs pragmatic actionif (experiment is not None andexperiment['expected_info_gain'] > self.epistemic_info_gain_threshold andcurrent_tension >= self.epistemic_tension_threshold):# Epistemic action: run an experiment to resolve tensionreturn {'type': 'epistemic',41 unmodified linesWeighted by surprise — surprising experiences teach more."""episodes = self.episodic.replay(n_episodes)total_update = 0.0for ep in episodes:obs_idx = ep.metadata.get('obs_idx', 0)self.epistemic.update_likelihood(obs_idx, ep.belief_state)total_update += 1.0return {'episodes_replayed': len(episodes),38 unmodified lines@classmethoddef from_config(cls, config: Dict[str, Any]) -> 'TensegrityAgent':"""Create an agent from a configuration dictionary."""return cls(**config)def __repr__(self):return (f"TensegrityAgent(states={self.n_states}, obs={self.n_obs}, "16 unmodified lines1718192021222373 unmodified lines97989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613799 unmodified lines237238239240241242243244245246247248249250251252134 unmodified lines38738838939039139239341 unmodified lines43543643743843944044144244344438 unmodified lines48348448548648748848949049149249316 unmodified lines"""import hashlibimport inspectimport numpy as npfrom typing import Optional, Dict, List, Any, Tupleimport logging73 unmodified linesepistemic_tension_threshold: Only run costly intervention search when causal tension exceeds this levelepistemic_info_gain_threshold: Minimum estimated information gain required for epistemic actions"""def _req_pos_int(name: str, v: Any) -> int:if not isinstance(v, int) or int(v) < 1:raise ValueError(f"{name} must be a positive integer")return int(v)n_states = _req_pos_int("n_states", n_states)n_observations = _req_pos_int("n_observations", n_observations)n_actions = _req_pos_int("n_actions", n_actions)sensory_dims = _req_pos_int("sensory_dims", sensory_dims)sensory_bits = _req_pos_int("sensory_bits", sensory_bits)context_dim = _req_pos_int("context_dim", context_dim)associative_dim = _req_pos_int("associative_dim", associative_dim)if not isinstance(planning_horizon, int) or planning_horizon < 1:raise ValueError("planning_horizon must be a positive integer")if precision < 0.0:raise ValueError("precision must be non-negative")if zipf_exponent < 0.0:raise ValueError("zipf_exponent must be non-negative")unified_obs_dim = _req_pos_int("unified_obs_dim", unified_obs_dim)if unified_hidden_dims is not None:if not isinstance(unified_hidden_dims, list) or any(not isinstance(x, int) or x < 1 for x in unified_hidden_dims):raise ValueError("unified_hidden_dims must be a list of positive integers")unified_fhrr_dim = _req_pos_int("unified_fhrr_dim", unified_fhrr_dim)if unified_hopfield_beta < 0.0:raise ValueError("unified_hopfield_beta must be non-negative")unified_ngc_settle_steps = _req_pos_int("unified_ngc_settle_steps", unified_ngc_settle_steps)if unified_ngc_learning_rate < 0.0:raise ValueError("unified_ngc_learning_rate must be non-negative")if not (0.0 <= float(epistemic_tension_threshold) <= 1.0):raise ValueError("epistemic_tension_threshold must be in [0, 1]")if not (0.0 <= float(epistemic_info_gain_threshold) <= 1.0):raise ValueError("epistemic_info_gain_threshold must be in [0, 1]")self.n_states = n_statesself.n_obs = n_observationsself.n_actions = n_actions99 unmodified linesself.arena.register_model(model_b)def _morton_to_obs_index(self, morton_codes: np.ndarray) -> int:"""Map Morton codes to a discrete observation index (legacy hashing).The main ``perceive`` path fingerprints the unified observation vectorwith SHA-256 modulo ``n_obs``; use this routine only where an explicitMorton-code → observation-bin mapping is intentional."""if self.n_obs <= 0:raise ValueError("n_observations must be a positive integer for _morton_to_obs_index mapping")if isinstance(morton_codes, (int, np.integer)):return int(morton_codes) % self.n_obs# For multiple codes, hash the combination134 unmodified lines# Compare epistemic value of experiment vs pragmatic actionif (experiment is not None andexperiment["expected_info_gain"] > self.epistemic_info_gain_threshold):# Epistemic action: run an experiment to resolve tensionreturn {'type': 'epistemic',41 unmodified linesWeighted by surprise — surprising experiences teach more."""episodes = self.episodic.replay(n_episodes)for ep in episodes:obs_idx = ep.metadata.get('obs_idx', 0)self.epistemic.update_likelihood(obs_idx, ep.belief_state)return {'episodes_replayed': len(episodes),38 unmodified lines@classmethoddef from_config(cls, config: Dict[str, Any]) -> 'TensegrityAgent':"""Create an agent from a configuration dictionary (unknown keys ignored)."""sig = inspect.signature(cls.__init__)allowed = {k for k in sig.parameters if k != "self"}kwargs = {k: v for k, v in config.items() if k in allowed}return cls(**kwargs)def __repr__(self):return (f"TensegrityAgent(states={self.n_states}, obs={self.n_obs}, "
33 unmodified lines34353637383919 unmodified lines5960616263646566676869707172732 unmodified lines76777879808182832 unmodified lines86878889909192939495969798997 unmodified lines10710810911011111211323 unmodified lines1371381391401411421431441451461471481491501511521532 unmodified lines15615715815916016116216316416516616716816917 unmodified lines18718818919019119219333 unmodified linesThe blanket enforces the Markov property: internal statesare conditionally independent of external states given the blanket."""def __init__(self,19 unmodified lines# Observation buffer — recent history for temporal inferenceself.observation_buffer: deque = deque(maxlen=observation_buffer_size)# Statistics for the blanket boundary (running means/vars for normalization)self._obs_count = 0self._obs_sum = Noneself._obs_sq_sum = None# Blanket surprise (how unexpected was the last observation?)self.surprise: float = 0.0def sense(self, raw_observation: np.ndarray) -> np.ndarray:"""Process a raw observation through the sensory boundary.2 unmodified lines3. Compute surprise (deviation from running statistics)Args:raw_observation: Raw sensory data, shape depends on modality.Will be reshaped to (n_points, n_dims) for Morton encoding.Returns:Morton-coded observation as integer array2 unmodified linesif raw_observation.ndim == 1:if len(raw_observation) == self.encoder.n_dims:raw_observation = raw_observation.reshape(1, -1)else:# Treat as multiple single-dim observationsraw_observation = raw_observation.reshape(-1, 1)# Morton encodemorton_codes = self.encoder.encode_continuous(raw_observation)if isinstance(morton_codes, (int, np.integer)):morton_codes = np.array([morton_codes])# Update running statistics for surprise computationself._update_statistics(raw_observation)7 unmodified lines'morton': morton_codes.copy(),'raw': raw_observation.copy(),'surprise': self.surprise,'timestamp': self._obs_count})return morton_codes23 unmodified linesdef _update_statistics(self, observation: np.ndarray):"""Update running statistics for surprise computation."""flat = observation.flatten()self._obs_count += 1if self._obs_sum is None:self._obs_sum = np.zeros_like(flat, dtype=np.float64)self._obs_sq_sum = np.zeros_like(flat, dtype=np.float64)# Pad or truncate to matchn = min(len(flat), len(self._obs_sum))self._obs_sum[:n] += flat[:n]self._obs_sq_sum[:n] += flat[:n] ** 2def _compute_surprise(self, observation: np.ndarray) -> float:"""2 unmodified linesThis is a simple proxy — the full surprise comes from thefree energy engine. But this gives a fast heuristic at the boundary."""if self._obs_count < 2:return 0.0flat = observation.flatten()n = min(len(flat), len(self._obs_sum))mean = self._obs_sum[:n] / self._obs_countvar = self._obs_sq_sum[:n] / self._obs_count - mean ** 2var = np.maximum(var, 1e-8) # Prevent division by zero# Gaussian log-likelihood (negative = surprise)17 unmodified lines'sensory': self.sensory_state,'active': self.active_state,'surprise': self.surprise,'obs_count': self._obs_count,'buffer_size': len(self.observation_buffer)}33 unmodified lines343536373839404142434419 unmodified lines646566676869707172737475767778792 unmodified lines82838485868788899091922 unmodified lines95969798991001011021031041051061071081091101111121131141151167 unmodified lines12412512612712812913023 unmodified lines1541551561571581591601611621631641651661671681691701711721731741751762 unmodified lines17918018118218318418518618718818919019119219317 unmodified lines21121221321421521621733 unmodified linesThe blanket enforces the Markov property: internal statesare conditionally independent of external states given the blanket.``n_sensory`` / ``n_active`` mirror constructor channel counts and arereserved for future multi-channel I/O; ``sense`` still ingests vectorsshaped for ``encoder.n_dims``, and ``act`` consumes the full softmax overactions passed in."""def __init__(self,19 unmodified lines# Observation buffer — recent history for temporal inferenceself.observation_buffer: deque = deque(maxlen=observation_buffer_size)# Running stats for surprise — per-coordinate counts (variable-length obs).self._sense_timestep = 0self._obs_sum: Optional[np.ndarray] = Noneself._obs_sq_sum: Optional[np.ndarray] = Noneself._obs_elem_count: Optional[np.ndarray] = None# Blanket surprise (how unexpected was the last observation?)self.surprise: float = 0.0def sense(self, raw_observation: np.ndarray, *, allow_multi_point_1d: bool = False) -> np.ndarray:"""Process a raw observation through the sensory boundary.2 unmodified lines3. Compute surprise (deviation from running statistics)Args:raw_observation: Array shaped ``(n_points, encoder.n_dims)``, or ``(n_dims,)``for one point. One-dimensional vectors whose length is not ``n_dims``are rejected unless ``allow_multi_point_1d=True`` is set, which treatsthe vector as a column (``reshape(-1, 1)``) of scalar observations —callers should prefer supplying an explicit `(n_points, n_dims)` array.Returns:Morton-coded observation as integer array2 unmodified linesif raw_observation.ndim == 1:if len(raw_observation) == self.encoder.n_dims:raw_observation = raw_observation.reshape(1, -1)elif allow_multi_point_1d:raw_observation = raw_observation.reshape(-1, 1)else:raise ValueError(f"One-dimensional sensory input length {len(raw_observation)} does not match "f"encoder.n_dims ({self.encoder.n_dims}). Pass shape ""(n_points, n_dims), a length-n_dims vector for one observation, ""or opt in with allow_multi_point_1d=True for reshape(-1, 1).")# Morton encodemorton_codes = self.encoder.encode_continuous(raw_observation)if isinstance(morton_codes, (int, np.integer)):morton_codes = np.array([morton_codes])self._sense_timestep += 1# Update running statistics for surprise computationself._update_statistics(raw_observation)7 unmodified lines'morton': morton_codes.copy(),'raw': raw_observation.copy(),'surprise': self.surprise,'timestamp': self._sense_timestep})return morton_codes23 unmodified linesdef _update_statistics(self, observation: np.ndarray):"""Update running statistics for surprise computation."""flat = np.asarray(observation, dtype=np.float64).flatten()if self._obs_sum is None:self._obs_sum = np.zeros(len(flat), dtype=np.float64)self._obs_sq_sum = np.zeros(len(flat), dtype=np.float64)self._obs_elem_count = np.zeros(len(flat), dtype=np.float64)lf, ls = len(flat), len(self._obs_sum)if lf > ls:self._obs_sum = np.pad(self._obs_sum, (0, lf - ls), mode='constant')self._obs_sq_sum = np.pad(self._obs_sq_sum, (0, lf - ls), mode='constant')self._obs_elem_count = np.pad(self._obs_elem_count, (0, lf - ls), mode='constant')n = min(lf, len(self._obs_sum))self._obs_sum[:n] += flat[:n]self._obs_sq_sum[:n] += flat[:n] ** 2self._obs_elem_count[:n] += 1.0def _compute_surprise(self, observation: np.ndarray) -> float:"""2 unmodified linesThis is a simple proxy — the full surprise comes from thefree energy engine. But this gives a fast heuristic at the boundary."""flat = np.asarray(observation, dtype=np.float64).flatten()assert self._obs_sum is not None and self._obs_elem_count is not Nonen = min(len(flat), len(self._obs_sum))cnt = self._obs_elem_count[:n]if n < 1 or float(np.min(cnt)) < 2.0:return 0.0mean = self._obs_sum[:n] / np.maximum(cnt, 1e-12)var = self._obs_sq_sum[:n] / np.maximum(cnt, 1e-12) - mean ** 2var = np.maximum(var, 1e-8) # Prevent division by zero# Gaussian log-likelihood (negative = surprise)17 unmodified lines'sensory': self.sensory_state,'active': self.active_state,'surprise': self.surprise,'sense_timestep': self._sense_timestep,'buffer_size': len(self.observation_buffer)}
23 unmodified lines24252627282930313213 unmodified lines4647484950515253545556575859606150 unmodified lines11211311411511611711811912012112212312412512612712817 unmodified lines14614714814915015115261 unmodified lines21421521621721821922022122222322422522622722822923023123223323423523623723823924023 unmodified lines"""import numpy as npfrom typing import Union, List, Tuple, Optionalclass MortonEncoder:"""Encodes arbitrary-dimensional data into Morton codes (Z-order curve indices).13 unmodified lines3 for volumetric, N for embeddings)bits_per_dim: Resolution per dimension. 10 bits = 1024 levels per dim.Total Morton code space = 2^(n_dims * bits_per_dim)ranges: Min/max per dimension for quantization. If None, auto-calibrated."""self.n_dims = n_dimsself.bits_per_dim = bits_per_dimself.total_bits = n_dims * bits_per_dimself.levels = 2 ** bits_per_dim# Quantization ranges per dimensionif ranges is not None:self.ranges = np.array(ranges, dtype=np.float64)else:self.ranges = None # Will be set on first encode (auto-calibrate)50 unmodified lines# Normalize to [0, 1] then scale to [0, levels-1]mins = self.ranges[:, 0]maxs = self.ranges[:, 1]normalized = (values - mins) / (maxs - mins)normalized = np.clip(normalized, 0.0, 1.0)quantized = (normalized * (self.levels - 1)).astype(np.int64)return quantizeddef dequantize(self, quantized: np.ndarray) -> np.ndarray:"""Inverse of quantize — reconstruct continuous approximation."""mins = self.ranges[:, 0]maxs = self.ranges[:, 1]normalized = quantized.astype(np.float64) / (self.levels - 1)return normalized * (maxs - mins) + minsdef encode(self, values: np.ndarray) -> np.ndarray:"""17 unmodified linesif values.dtype in (np.float32, np.float64):quantized = self.quantize(values)else:quantized = values.astype(np.int64)# Interleave bits for each pointn_points = quantized.shape[0]61 unmodified linesdef neighborhood(self, code: int, radius: int = 1) -> List[int]:"""Find Morton codes within a given radius (in quantized coordinates).This exploits the locality property: nearby Morton codes correspondto nearby points in the original space."""center = self.decode(code)neighbors = []# Generate all offset combinations within radiusoffsets = range(-radius, radius + 1)def _recurse(dim, current_offset):if dim == self.n_dims:point = center + np.array(current_offset)if np.all(point >= 0) and np.all(point < self.levels):neighbors.append(int(self.encode(point.reshape(1, -1))))returnfor off in offsets:_recurse(dim + 1, current_offset + [off])_recurse(0, [])return list(set(neighbors))@staticmethoddef from_modality(modality: str, **kwargs) -> 'MortonEncoder':23 unmodified lines242526272829303132333435363713 unmodified lines51525354555657585960616263646566676869707172737475767778798081828384858687888950 unmodified lines14014114214314414514614714814915015115215315415515615715815916016116216317 unmodified lines18118218318418518618718818919019119219319419519661 unmodified lines25825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828923 unmodified lines"""import numpy as npfrom itertools import productfrom typing import Union, List, Tuple, Optional# Guard against exponential neighborhood enumeration when radius × dims is large.MAX_NEIGHBORHOOD_COMBINATIONS = 50_000class MortonEncoder:"""Encodes arbitrary-dimensional data into Morton codes (Z-order curve indices).13 unmodified lines3 for volumetric, N for embeddings)bits_per_dim: Resolution per dimension. 10 bits = 1024 levels per dim.Total Morton code space = 2^(n_dims * bits_per_dim)Must satisfy n_dims * bits_per_dim <= 63 so codes fit np.int64.ranges: Min/max per dimension for quantization. If None, auto-calibrated."""self.n_dims = n_dimsself.bits_per_dim = bits_per_dimtotal_bits = n_dims * bits_per_dimif total_bits > 63:raise ValueError(f"total_bits (n_dims * bits_per_dim) must be <= 63 to fit in np.int64; "f"got total_bits={total_bits}")self.total_bits = total_bitsself.levels = 2 ** bits_per_dim# Quantization ranges per dimensionif ranges is not None:self.ranges = np.asarray(ranges, dtype=np.float64)if self.ranges.ndim != 2 or self.ranges.shape[1] != 2:raise ValueError("ranges must be a sequence of (min, max) tuples per dimension.")spans = self.ranges[:, 1] - self.ranges[:, 0]flat_spans = np.asarray(spans).flatten()bad = np.where(np.abs(flat_spans) < 1e-15)[0]if len(bad):dims_list = [int(i) for i in bad.tolist()]raise ValueError("Quantization ranges have zero span on dimension index(es) "f"{dims_list}; ensure max > min for each dimension ""(or omit ranges to auto-calibrate from data).")if int(self.ranges.shape[0]) != int(n_dims):raise ValueError(f"ranges must have length n_dims ({n_dims}), got shape {self.ranges.shape}.")else:self.ranges = None # Will be set on first encode (auto-calibrate)50 unmodified lines# Normalize to [0, 1] then scale to [0, levels-1]mins = self.ranges[:, 0]maxs = self.ranges[:, 1]spans = np.maximum(maxs - mins, 1e-15)normalized = (values - mins) / spansnormalized = np.clip(normalized, 0.0, 1.0)quantized = (normalized * (self.levels - 1)).astype(np.int64)return quantizeddef dequantize(self, quantized: np.ndarray) -> np.ndarray:"""Inverse of quantize — reconstruct continuous approximation."""if self.ranges is None:raise ValueError("ranges not initialized: call encode (or compute_ranges) ""before MortonEncoder.dequantize")mins = self.ranges[:, 0]maxs = self.ranges[:, 1]spans = np.maximum(maxs - mins, 1e-15)normalized = quantized.astype(np.float64) / (self.levels - 1)return normalized * spans + minsdef encode(self, values: np.ndarray) -> np.ndarray:"""17 unmodified linesif values.dtype in (np.float32, np.float64):quantized = self.quantize(values)else:quantized = np.asarray(values, dtype=np.int64)qmin = int(np.min(quantized))qmax = int(np.max(quantized))lo = 0hi = int(self.levels - 1)if qmin < lo or qmax > hi:raise ValueError(f"MortonEncoder.encode expects integer coords in [{lo}, {hi}] "f"(levels={self.levels}); got range [{qmin}, {qmax}]")# Interleave bits for each pointn_points = quantized.shape[0]61 unmodified linesdef neighborhood(self, code: int, radius: int = 1) -> List[int]:"""Find Morton codes within a given radius (in quantized coordinates).Uses ``decode`` → offset enumeration → ``encode`` within ``[0, levels)``."""decoded = self.decode(code)center = (decoded.reshape(-1).astype(np.int64)if isinstance(decoded, np.ndarray)else np.asarray([decoded], dtype=np.int64))n_combo = int((2 * radius + 1) ** self.n_dims)if n_combo > MAX_NEIGHBORHOOD_COMBINATIONS:raise ValueError(f"MortonEncoder.neighborhood would enumerate {n_combo} quantized offset "f"combinations (n_dims={self.n_dims}, radius={radius}, levels={self.levels}), "f"which exceeds MAX_NEIGHBORHOOD_COMBINATIONS={MAX_NEIGHBORHOOD_COMBINATIONS}; ""reduce radius or n_dims.")offsets = range(-radius, radius + 1)neighbors: List[int] = []for tup in product(offsets, repeat=self.n_dims):offset = np.array(tup, dtype=np.int64)point = center + offsetif np.all(point >= 0) and np.all(point < self.levels):neighbors.append(int(self.encode(point.reshape(1, -1))))return sorted(set(neighbors))@staticmethoddef from_modality(modality: str, **kwargs) -> 'MortonEncoder':
137 unmodified lines138139140141142143137 unmodified linesif norm > 0:item_rep /= normreturn item_repdef encode(self, observation: np.ndarray, morton_code: np.ndarray,belief_state: np.ndarray, action: Optional[int],137 unmodified lines138139140141142143144145146147148137 unmodified linesif norm > 0:item_rep /= normreturn item_repdef compute_item_representation(self, observation: np.ndarray,belief_state: np.ndarray) -> np.ndarray:"""Public entry point for projecting an observation + belief into context space."""return self._compute_item_representation(observation, belief_state)def encode(self, observation: np.ndarray, morton_code: np.ndarray,belief_state: np.ndarray, action: Optional[int],
200 unmodified lines2012022032042052063 unmodified lines210211212213214215216217200 unmodified linesself.evidence_log.append(log_lik)return log_likdef entropy(self) -> Dict[str, float]:"""Compute non-negative categorical entropy of expected beliefs.3 unmodified linesuncertainty dashboard metric. The agent usually wants entropy of theexpected categorical distributions it will actually act on."""A = self.A_params / self.A_params.sum(axis=0, keepdims=True)D = self.D_params / self.D_params.sum()a_entropy_by_state = -np.sum(A * np.log(np.maximum(A, 1e-16)), axis=0)d_entropy = -np.sum(D * np.log(np.maximum(D, 1e-16)))200 unmodified lines2012022032042052062072082092102112122132142152163 unmodified lines220221222223224225226227200 unmodified linesself.evidence_log.append(log_lik)return log_likdef _normalize_params_matrix(self, params: np.ndarray, *, axis: int) -> np.ndarray:"""Map Dirichlet parameters to expected categorical probs (does not touch access counts)."""return params / np.maximum(params.sum(axis=axis, keepdims=True), 1e-16)@staticmethoddef _normalize_params_vector(params: np.ndarray) -> np.ndarray:"""Normalize a vector Dirichlet parameter to probabilities."""s = float(params.sum())return params / max(s, 1e-16)def entropy(self) -> Dict[str, float]:"""Compute non-negative categorical entropy of expected beliefs.3 unmodified linesuncertainty dashboard metric. The agent usually wants entropy of theexpected categorical distributions it will actually act on."""A = self._normalize_params_matrix(self.A_params, axis=0)D = self._normalize_params_vector(self.D_params)a_entropy_by_state = -np.sum(A * np.log(np.maximum(A, 1e-16)), axis=0)d_entropy = -np.sum(D * np.log(np.maximum(D, 1e-16)))
37 unmodified lines38394041424331 unmodified lines75767778798098 unmodified lines17918018118218318418518618718818919019119219341 unmodified lines23523623723823924024124224324424524624721 unmodified lines2692702712722732742752762772782792802812822839 unmodified lines29329429529629729829956 unmodified lines35635735835936036136236332 unmodified lines39639739839940040193 unmodified lines495496497498499500501502503504505506105 unmodified lines61261361461561661737 unmodified linesimport numpy as npfrom tensegrity.broca.controller import CognitiveControllerfrom tensegrity.bench.tasks import TaskSamplefrom tensegrity.causal.scm import StructuralCausalModelfrom tensegrity.engine.causal_energy import (31 unmodified linesfinal_arena_tension: floatfinal_energy_arena_tension: floattrace: List[IterationStep] = field(default_factory=list)def _alphanum_tokens(text: str, max_tokens: int) -> List[str]:98 unmodified lines# The controller resets itself per item; here we additionally clear the# Hopfield bank, episodic memory, and energy arena.try:self.controller.agent.field.memory.patterns.clear()self.controller.agent.field.memory._matrix = Noneself.controller.agent.field.memory._dirty = Trueexcept Exception as e:logger.debug("Hopfield clear skipped: %s", e)try:self.controller.agent.episodic.clear()except Exception as e:logger.debug("Episodic clear skipped: %s", e)self.energy_arena = EnergyCausalArena(precision=self.energy_arena.precision,beta=self.energy_arena.beta,41 unmodified linesn_ngc_layers = len(self.controller.agent.field.ngc.layer_sizes)topology = self._topology_mapper.from_scm(scm, n_layers=n_ngc_layers)self._scm_topologies[scm.name] = topologyexcept ValueError:# Already registered (rare; defensive).passdef _soft_reset_in_place(self, labels: List[str]) -> None:"""Reset only what is per-item, keeping the heavy state intact."""from tensegrity.broca.schemas import BeliefState, Hypothesis# Fresh hypotheses with uniform prior over the choice labels.n = len(labels)21 unmodified lines# NGC working state: clear activations/history but keep the learned# weights (cross-item priors) and the Hopfield bank.try:ngc = self.controller.agent.field.ngcngc.layers = []ngc._initialized = Falsengc._last_obs = Nonengc.clear_history()self.controller.agent.field.energy_history.clear()self.controller.agent.field._step_count = 0except Exception as e:logger.debug("NGC soft-reset skipped: %s", e)# ---------- per-choice SCM (used by EnergyCausalArena) ----------9 unmodified linesis exactly what turns the lateral coherence link into a virtual parentin the NGC hierarchy, addressing the topological-mismatch critique."""scm = StructuralCausalModel(name=f"choice_{choice_idx}")scm.add_variable("prompt_feature", n_values=4, parents=[])scm.add_variable("coherence", n_values=4, parents=[])scm.add_variable("choice_match", n_values=4, parents=["prompt_feature"])56 unmodified linesfield.ngc.settle(choice_obs, steps=self.falsify_settle_steps)pe = float(field.ngc.prediction_error(prompt_obs))except Exception as e:logger.debug("falsification step failed for choice %d: %s", i, e)pe = 0.0scores[i] = -pe# Derive a compact discrete observation for the energy arena.32 unmodified linesdef _bucket_4(x: float) -> int:"""Map a real-valued summary to a 4-bucket discrete value via tanh."""v = math.tanh(x / 2.0) # in (-1, 1)# Map (-1, 1) to {0, 1, 2, 3}.return max(0, min(3, int((v + 1.0) * 2.0)))93 unmodified linesfinal_energy_arena_tension=1.0,)self._item_index += 1self.reset_for_item(sample)# Initial perception — runs the full stack, including Broca SCM proposal# if causal tension is high (the controller wires this internally).ing0 = self.ingest_prompt(sample.prompt)trace: List[IterationStep] = []converged = False105 unmodified linesfinal_arena_tension=final_arena_tension,final_energy_arena_tension=final_energy_tension,trace=trace,)# ---------- helpers ----------37 unmodified lines3839404142434431 unmodified lines7677787980818298 unmodified lines18118218318418518618718818919019119219319419519619741 unmodified lines23924024124224324424524624724824925025125225321 unmodified lines2752762772782792802812822832842852862879 unmodified lines29729829930030130230356 unmodified lines36036136236336436536636736836937032 unmodified lines40340440540640740840941093 unmodified lines504505506507508509510511512513514515105 unmodified lines62162262362462562662737 unmodified linesimport numpy as npfrom tensegrity.broca.controller import CognitiveControllerfrom tensegrity.broca.schemas import BeliefState, Hypothesisfrom tensegrity.bench.tasks import TaskSamplefrom tensegrity.causal.scm import StructuralCausalModelfrom tensegrity.engine.causal_energy import (31 unmodified linesfinal_arena_tension: floatfinal_energy_arena_tension: floattrace: List[IterationStep] = field(default_factory=list)initial_perception: Optional[Dict[str, Any]] = Nonedef _alphanum_tokens(text: str, max_tokens: int) -> List[str]:98 unmodified lines# The controller resets itself per item; here we additionally clear the# Hopfield bank, episodic memory, and energy arena.try:self.controller.agent.field.memory.clear()except AttributeError as e:logger.warning("Hopfield clear failed (missing clear): %s", e)except Exception as e:logger.error("Hopfield clear failed: %s", e, exc_info=True)try:self.controller.agent.episodic.clear()except AttributeError as e:logger.warning("Episodic clear failed: %s", e)except Exception as e:logger.error("Episodic clear failed: %s", e, exc_info=True)self.energy_arena = EnergyCausalArena(precision=self.energy_arena.precision,beta=self.energy_arena.beta,41 unmodified linesn_ngc_layers = len(self.controller.agent.field.ngc.layer_sizes)topology = self._topology_mapper.from_scm(scm, n_layers=n_ngc_layers)self._scm_topologies[scm.name] = topologyexcept ValueError as e:logger.warning("Topology registration failed for SCM %r: %s",getattr(scm, "name", "?"),e,)def _soft_reset_in_place(self, labels: List[str]) -> None:"""Reset only what is per-item, keeping the heavy state intact."""# Fresh hypotheses with uniform prior over the choice labels.n = len(labels)21 unmodified lines# NGC working state: clear activations/history but keep the learned# weights (cross-item priors) and the Hopfield bank.try:self.controller.agent.field.ngc.soft_reset()self.controller.agent.field.energy_history.clear()self.controller.agent.field._step_count = 0except AttributeError as e:logger.warning("NGC soft_reset skipped (API mismatch): %s", e)except Exception as e:logger.error("NGC soft_reset failed: %s", e, exc_info=True)# ---------- per-choice SCM (used by EnergyCausalArena) ----------9 unmodified linesis exactly what turns the lateral coherence link into a virtual parentin the NGC hierarchy, addressing the topological-mismatch critique."""scm = StructuralCausalModel(name=f"choice_{choice_idx}_{label}")scm.add_variable("prompt_feature", n_values=4, parents=[])scm.add_variable("coherence", n_values=4, parents=[])scm.add_variable("choice_match", n_values=4, parents=["prompt_feature"])56 unmodified linesfield.ngc.settle(choice_obs, steps=self.falsify_settle_steps)pe = float(field.ngc.prediction_error(prompt_obs))except Exception as e:logger.error("NGC falsification failed for choice %d: %s",i, e, exc_info=True,)pe = float(1e9)scores[i] = -pe# Derive a compact discrete observation for the energy arena.32 unmodified linesdef _bucket_4(x: float) -> int:"""Map a real-valued summary to a 4-bucket discrete value via tanh."""v = math.tanh(x / 2.0) # in (-1, 1)if math.isnan(x) or math.isnan(v):return 2# Map (-1, 1) to {0, 1, 2, 3}.return max(0, min(3, int((v + 1.0) * 2.0)))93 unmodified linesfinal_energy_arena_tension=1.0,)self.reset_for_item(sample)self._item_index += 1# Initial perception — runs the full stack, including Broca SCM proposal# if causal tension is high (the controller wires this internally).initial_perception = self.ingest_prompt(sample.prompt)trace: List[IterationStep] = []converged = False105 unmodified linesfinal_arena_tension=final_arena_tension,final_energy_arena_tension=final_energy_tension,trace=trace,initial_perception=initial_perception if n > 0 else None,)# ---------- helpers ----------
108 unmodified lines10911011111211311422 unmodified lines13713813914014114222 unmodified lines1651661671681691701711721731743 unmodified lines17817918018118218318447 unmodified lines23223323423523623723811 unmodified lines25025125225325425525625725825926026126213 unmodified lines27627727827928028134 unmodified lines31631731831932032132232332432536 unmodified lines3623633643653663673683693703713724 unmodified lines37737837938038138252 unmodified lines4354364374384394404414421 unmodified line444445446447448449450451452108 unmodified lines# noisy to help. The wiring (encode/retrieve) stays so smarter signals# can be plugged in here without re-plumbing.w_episodic: float = 0.0,):from tensegrity.engine.unified_field import UnifiedFieldfrom tensegrity.memory.episodic import EpisodicMemory22 unmodified linesself.use_episodic = use_episodicself.episodic_top_k = episodic_top_kself.w_episodic = w_episodic# Dirichlet-style per-channel reliability. Each channel accumulates a# pseudocount that grows when the channel's top-ranked choice matches# the committed belief on an item. Fusion weights = normalized counts.22 unmodified linesdef _sbert_similarities(self, prompt: str, choices: List[str]) -> List[float]:features = self.field.encoder.featuresif hasattr(features, "_ensure_sbert") and getattr(features, "_sbert", None) is None:features._ensure_sbert()sbert = getattr(features, "_sbert", None)if sbert is not None and sbert != "FALLBACK":embs = sbert.encode([prompt] + choices, show_progress_bar=False)pe = embs[0]pn = float(np.linalg.norm(pe))3 unmodified linescn = float(np.linalg.norm(ce))out.append(float(np.dot(pe, ce) / (pn * cn)) if pn > 1e-8 and cn > 1e-8 else 0.0)return out# fallback to FHRR similaritypf = self._encode(self._tokenize(prompt, 64))return [self.field.encoder.similarity(pf, self._encode(self._tokenize(c, 32)))47 unmodified linesif self.use_episodic and self.episodic is not None and len(self.episodic.episodes) > 0:uniform_belief = np.full(n, 1.0 / n, dtype=np.float64)try:query_ctx = self.episodic._compute_item_representation(prompt_obs_vec, uniform_belief)retrieved = self.episodic.retrieve_by_context(11 unmodified linesch_real.append(v / nrm if nrm > 1e-10 else v)# Only trust episodes whose prompt context strongly matches.# Below this threshold, "similar past answer" is noise, not signal.CTX_SIM_THRESHOLD = 0.5for ep in retrieved:ans_vec = ep.metadata.get("chosen_fhrr_real") if ep.metadata else Noneif ans_vec is None:continuectx_sim = float(np.dot(query_ctx, ep.context_vector))if ctx_sim < CTX_SIM_THRESHOLD:continue# Also discount by past surprise: episodes the agent struggled# with (low committed confidence) carry less authority.13 unmodified linesiterations_used = 0last_channel_scores: Dict[str, np.ndarray] = {}for it in range(self.max_iterations):iterations_used = it + 134 unmodified lineshop_bonus[i] = float(np.dot(q, retrieved / rn))# 3b. Fuse z-normalizeddef znorm(a: np.ndarray) -> np.ndarray:s = a.std()return (a - a.mean()) / s if s > 1e-10 else np.zeros_like(a)# Normalized channel weights from accumulated reliability counts.total = sum(self._channel_counts.values())w = {c: self._channel_counts[c] / total for c in self._channels}36 unmodified linesself.field.ngc.settle(prompt_obs_vec, steps=self.context_settle_steps)self.field.ngc.learn(modulation=self.shaping_lr_scale)# 3e. Hopfield: store the *prompt* encoding so cross-iteration memory# accumulates evidence about the question, not the current guess.if self.use_hopfield:self.field.memory.store(self._encode(prompt_tokens))# Re-base on the prompt-grounded state for next iteration's scoringbase_state = self.field.ngc.save_state()4 unmodified linesconverged = Truebreakcommitted_idx = int(np.argmax(prev_belief))# Reliability update via *cross-channel agreement* (not agreement with52 unmodified linesdef reset(self):"""Per-item reset. Clears NGC working state but PRESERVES Hopfieldpatterns and episodic memory — those carry across items in a sessionand provide cross-item learning."""self.field.ngc.reinitialize(12345)self.field.energy_history.clear()self.field._step_count = 01 unmodified line"""Full reset. Use at task / session boundaries to clear all memoryand per-channel reliability priors (which are task-specific)."""self.reset()self.field.memory.patterns.clear()self.field.memory._matrix = Noneself.field.memory._dirty = Trueif self.episodic is not None:self.episodic.clear()for c in self._channels:108 unmodified lines10911011111211311411511611711822 unmodified lines14114214314414514614714822 unmodified lines1711721731741751761771781793 unmodified lines18318418518618718818919019119219347 unmodified lines24124224324424524624711 unmodified lines25926026126226326426526626726826927013 unmodified lines28428528628728828929029129229334 unmodified lines32832933033133233336 unmodified lines3703713723733743754 unmodified lines38038138238338438538638738838952 unmodified lines4424434444454464474484494504514524534544554564571 unmodified line459460461462463464465108 unmodified lines# noisy to help. The wiring (encode/retrieve) stays so smarter signals# can be plugged in here without re-plumbing.w_episodic: float = 0.0,# Minimum cosine match between query and episodic context to trust retrieval.episodic_ctx_sim_threshold: float = 0.5,# Seed for NGC `reinitialize` on `reset`; None chooses a random seed each time.reset_seed: Optional[int] = 12345,):from tensegrity.engine.unified_field import UnifiedFieldfrom tensegrity.memory.episodic import EpisodicMemory22 unmodified linesself.use_episodic = use_episodicself.episodic_top_k = episodic_top_kself.w_episodic = w_episodicself.episodic_ctx_sim_threshold = episodic_ctx_sim_thresholdself.reset_seed = reset_seed# Dirichlet-style per-channel reliability. Each channel accumulates a# pseudocount that grows when the channel's top-ranked choice matches# the committed belief on an item. Fusion weights = normalized counts.22 unmodified linesdef _sbert_similarities(self, prompt: str, choices: List[str]) -> List[float]:features = self.field.encoder.featuresgetter = getattr(features, "get_sbert_model", None)sbert = getter() if callable(getter) else Noneif sbert is not None:embs = sbert.encode([prompt] + choices, show_progress_bar=False)pe = embs[0]pn = float(np.linalg.norm(pe))3 unmodified linescn = float(np.linalg.norm(ce))out.append(float(np.dot(pe, ce) / (pn * cn)) if pn > 1e-8 and cn > 1e-8 else 0.0)return outif self.field.encoder.semantic and callable(getter) and not getattr(self, "_sbert_unavailable_logged", False):logger.warning("SBERT sentence similarity unavailable; using FHRR cosine similarity.")setattr(self, "_sbert_unavailable_logged", True)pf = self._encode(self._tokenize(prompt, 64))return [self.field.encoder.similarity(pf, self._encode(self._tokenize(c, 32)))47 unmodified linesif self.use_episodic and self.episodic is not None and len(self.episodic.episodes) > 0:uniform_belief = np.full(n, 1.0 / n, dtype=np.float64)try:query_ctx = self.episodic.compute_item_representation(prompt_obs_vec, uniform_belief)retrieved = self.episodic.retrieve_by_context(11 unmodified linesch_real.append(v / nrm if nrm > 1e-10 else v)# Only trust episodes whose prompt context strongly matches.# Below this threshold, "similar past answer" is noise, not signal.for ep in retrieved:ans_vec = ep.metadata.get("chosen_fhrr_real") if ep.metadata else Noneif ans_vec is None:continuectx_sim = float(np.dot(query_ctx, ep.context_vector))if ctx_sim < self.episodic_ctx_sim_threshold:continue# Also discount by past surprise: episodes the agent struggled# with (low committed confidence) carry less authority.13 unmodified linesiterations_used = 0last_channel_scores: Dict[str, np.ndarray] = {}def znorm(a: np.ndarray) -> np.ndarray:s = a.std()return (a - a.mean()) / s if s > 1e-10 else np.zeros_like(a)for it in range(self.max_iterations):iterations_used = it + 134 unmodified lineshop_bonus[i] = float(np.dot(q, retrieved / rn))# 3b. Fuse z-normalized# Normalized channel weights from accumulated reliability counts.total = sum(self._channel_counts.values())w = {c: self._channel_counts[c] / total for c in self._channels}36 unmodified linesself.field.ngc.settle(prompt_obs_vec, steps=self.context_settle_steps)self.field.ngc.learn(modulation=self.shaping_lr_scale)# Re-base on the prompt-grounded state for next iteration's scoringbase_state = self.field.ngc.save_state()4 unmodified linesconverged = Truebreak# Store prompt encoding once for Hopfield cross-item memory (not each iteration).if self.use_hopfield:self.field.memory.store(self._encode(prompt_tokens))committed_idx = int(np.argmax(prev_belief))# Reliability update via *cross-channel agreement* (not agreement with52 unmodified linesdef reset(self):"""Per-item reset. Clears NGC working state but PRESERVES Hopfieldpatterns and episodic memory — those carry across items in a sessionand provide cross-item learning.NGC weights are reinitialized using ``reset_seed``: default ``12345``matches legacy behavior for reproducibility; pass ``None`` for a randomseed each reset, or any other integer to pin runs."""seed = self.reset_seedif seed is None:seed = int(np.random.randint(0, 2 ** 31))self.field.ngc.reinitialize(seed)self.field.energy_history.clear()self.field._step_count = 01 unmodified line"""Full reset. Use at task / session boundaries to clear all memoryand per-channel reliability priors (which are task-specific)."""self.reset()self.field.memory.clear()if self.episodic is not None:self.episodic.clear()for c in self._channels:
66 unmodified lines6768697071727366 unmodified linesassert len(mapping.virtual_parents) == 1vp = next(iter(mapping.virtual_parents.values()))assert vp.children == ("A", "B")assert mapping.embedded_layers[vp.name] == 1assert (vp.name, "A") in mapping.embedded_edgesassert (vp.name, "B") in mapping.embedded_edges66 unmodified lines6768697071727366 unmodified linesassert len(mapping.virtual_parents) == 1vp = next(iter(mapping.virtual_parents.values()))assert set(vp.children) == {"A", "B"}assert mapping.embedded_layers[vp.name] == 1assert (vp.name, "A") in mapping.embedded_edgesassert (vp.name, "B") in mapping.embedded_edges
6 unmodified lines789101112110 unmodified lines1231241251261271286 unmodified linesimport timeimport numpy as npROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))if ROOT not in sys.path:110 unmodified linesdef test_scm_marginalizes_missing_parents_and_counterfactual_changes_descendants():from tensegrity.causal.scm import StructuralCausalModelscm = StructuralCausalModel("two_node")6 unmodified lines78910111213110 unmodified lines1241251261271281291306 unmodified linesimport timeimport numpy as npimport pytestROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))if ROOT not in sys.path:110 unmodified linesdef test_scm_marginalizes_missing_parents_and_counterfactual_changes_descendants():pytest.importorskip("networkx")from tensegrity.causal.scm import StructuralCausalModelscm = StructuralCausalModel("two_node")
2 unmodified lines34567859 unmodified lines686970717273742 unmodified lines"""import numpy as npnp.random.seed(42)59 unmodified linessim_numeric_far = enc.similarity(v_base, v_far)print(f"\n sim([1,2,3], [1,2,3.1]) = {sim_near:.4f}")print(f" sim([1,2,3], [9,8,7]) = {sim_numeric_far:.4f}")assert sim_near > sim_numeric_farprint(f" ✓ Numeric vectors: similar inputs → similar encodings")2 unmodified lines345678959 unmodified lines697071727374757677782 unmodified lines"""import numpy as npimport sysnp.random.seed(42)59 unmodified linessim_numeric_far = enc.similarity(v_base, v_far)print(f"\n sim([1,2,3], [1,2,3.1]) = {sim_near:.4f}")print(f" sim([1,2,3], [9,8,7]) = {sim_numeric_far:.4f}")assert sim_near > sim_numeric_far, ("Numeric vectors should be more similar when inputs are nearer in value space "f"(sim_near={sim_near}, sim_far={sim_numeric_far})")print(f" ✓ Numeric vectors: similar inputs → similar encodings")
8 unmodified lines910111213148 unmodified lines"""import numpy as npimport jsonnp.random.seed(42)8 unmodified lines91011121314158 unmodified lines"""import numpy as npimport sysimport jsonnp.random.seed(42)
169 unmodified lines170171172173174175169 unmodified linesprint(f"\n Memory similarity for truth: {r_truth['memory_similarity']:.4f}")assert np.isfinite(mean_contra_pe)assert np.isfinite(pe_truth_after)def test_needle_in_lies():169 unmodified lines170171172173174175176177178179180181182169 unmodified linesprint(f"\n Memory similarity for truth: {r_truth['memory_similarity']:.4f}")assert np.isfinite(mean_contra_pe)assert np.isfinite(pe_truth_after)assert not np.isclose(mean_contra_pe, pe_truth_after, rtol=0.0, atol=1e-8), ("Prediction error on contradictions should differ from prediction error "f"when the established truth is re-presented "f"(mean_contra_pe={mean_contra_pe:.6g}, pe_truth_after={pe_truth_after:.6g})")def test_needle_in_lies():
106 unmodified lines107108109110111106 unmodified linesimport traceback; traceback.print_exc()print()106 unmodified lines107108109106 unmodified linesimport traceback; traceback.print_exc()print()
250 unmodified lines251252253254255256257250 unmodified lines# Soft retrieval (Boltzmann distribution)blended, weights = am.retrieve_soft(noisy)print(f" Soft retrieval weights (top 3): {sorted(weights)[-3:]}")assert best_match == 3print(f" ✓ Content-addressed retrieval via energy minimization")print(f" Stats: {am.statistics}")250 unmodified lines251252253254255256257258259260261250 unmodified lines# Soft retrieval (Boltzmann distribution)blended, weights = am.retrieve_soft(noisy)print(f" Soft retrieval weights (top 3): {sorted(weights)[-3:]}")assert best_match == 3, ("expected best_match == 3 (associative retrieval of pattern 3) with numpy seed ""42 set at module load, "f"got best_match={best_match}")print(f" ✓ Content-addressed retrieval via energy minimization")print(f" Stats: {am.statistics}")