James Trageser (jtrag) commited on
Commit
320d2cd
·
unverified ·
1 Parent(s): d7b67af

refactor: implement hierarchical folding and O(1) manifold stabilization

Browse files
Files changed (2) hide show
  1. app.py +9 -17
  2. nrc_engine.py +26 -11
app.py CHANGED
@@ -104,27 +104,19 @@ def process_context(text, state_residuals, current_logs):
104
 
105
  segments = [s.strip() for s in text.split("\n") if s.strip()]
106
  logs += f"\n[LATTICE] Detected {len(segments)} semantic shards."
 
 
107
 
108
- residuals, stats = engine.compress_text(segments)
 
109
 
110
- sample_res = residuals[0][:8].tolist()
111
- logs += f"\n[RAW] Shard R_0 Projection (Head 8): {sample_res}"
112
- yield None, "", state_residuals, logs, ""
113
 
114
- new_residuals = (state_residuals or []) + residuals
115
- fig = generate_viz(new_residuals)
116
 
117
- audit = stats['ttt_audit']
118
- audit_report = f"### TTT Stability Audit\n**Energy**: {audit['energy']:.6f}\n**Digital Root**: {audit['digital_root']}\n**Status**: {audit['status']}"
119
-
120
- raw_view = "Index | Norm | Stability | Residual Sample\n" + "-"*50 + "\n"
121
- for i, res in enumerate(new_residuals[:20]):
122
- norm = torch.norm(res).item()
123
- sample = res[:4].tolist()
124
- raw_view += f"{i:03d} | {norm:.4f} | STABLE | {sample}\n"
125
-
126
- logs += f"\n[SYSTEM] Compression complete. Lattice depth: {len(new_residuals)}"
127
- yield fig, audit_report, new_residuals, format_logs(logs), raw_view
128
 
129
  def search_query(query, state_residuals, current_logs):
130
  print(f"[EVENT] Starting Search Query: '{query}'")
 
104
 
105
  segments = [s.strip() for s in text.split("\n") if s.strip()]
106
  logs += f"\n[LATTICE] Detected {len(segments)} semantic shards."
107
+ # Institutional fold into the φ-manifold
108
+ residuals, stats, logs = engine.compress_text(segments, logs)
109
 
110
+ # Audit and visualize the resulting aggregate manifold
111
+ audit_report = f"### TTT Stability Audit\n**Status**: {stats['ttt_audit']['status']}\n**Root**: {stats['ttt_audit']['digital_root']}\n**Energy**: {stats['ttt_audit']['energy']:.6f}"
112
 
113
+ raw_view = f"Manifold Depth: {len(residuals)}\nShards Folded: {stats['shards_folded']}\n"
114
+ raw_view += f"Theoretical Ratio: {stats['theoretical_ratio']}"
 
115
 
116
+ fig = generate_viz(residuals)
 
117
 
118
+ print(f"[EVENT] Compression Completed. Manifold Depth: {len(residuals)}")
119
+ yield fig, audit_report, residuals, format_logs(logs), raw_view
 
 
 
 
 
 
 
 
 
120
 
121
  def search_query(query, state_residuals, current_logs):
122
  print(f"[EVENT] Starting Search Query: '{query}'")
nrc_engine.py CHANGED
@@ -54,26 +54,41 @@ class PhiInfinityEngine:
54
  "recommendation": "Maintain state" if is_stable else "Apply QRT stabilization"
55
  }
56
 
57
- def compress_text(self, text_segments: List[str]) -> Tuple[List[torch.Tensor], Dict[str, Any]]:
58
- embeddings = self.embed_model.encode(text_segments, convert_to_tensor=True)
59
- all_residuals = []
60
- for i in range(embeddings.shape[0]):
61
- seg_res = self.hierarchy.compress(embeddings[i])
62
- all_residuals.extend(seg_res)
63
-
 
 
 
 
 
 
 
 
 
 
64
  stats = self.hierarchy.get_memory_usage()
65
- aggregate_state = self.hierarchy.decompress(all_residuals)
66
- audit = self.run_ttt_audit(aggregate_state)
 
67
  stats["ttt_audit"] = audit
68
 
69
- return all_residuals, stats
 
70
 
71
  def search_context(self, query: str, residuals: List[torch.Tensor]) -> Dict[str, Any]:
72
  query_embed = self.embed_model.encode([query], convert_to_tensor=True)[0]
73
  reconstructed = self.hierarchy.decompress(residuals)
 
 
74
  padded_query = torch.nn.functional.pad(query_embed, (0, self.lattice_dim - query_embed.shape[-1]))
 
75
 
76
- resonance = torch.nn.functional.cosine_similarity(padded_query, reconstructed, dim=0).item()
77
 
78
  # Calculate per-residual resonance for visualization
79
  # We look at how much each residual aligns with the query
 
54
  "recommendation": "Maintain state" if is_stable else "Apply QRT stabilization"
55
  }
56
 
57
+ def compress_text(self, text_segments: List[str], current_logs: str = "") -> Tuple[List[torch.Tensor], Dict[str, Any], str]:
58
+ """
59
+ Fold multiple text segments into a single stabilized hierarchical manifold.
60
+ """
61
+ # Batch encode for institutional efficiency
62
+ embeddings = self.embed_model.encode(text_segments, convert_to_tensor=True, show_progress_bar=False)
63
+
64
+ # Calculate the aggregate semantic centroid of the context
65
+ # This represents the base manifold state before hierarchical refinement
66
+ centroid = torch.mean(embeddings, dim=0)
67
+
68
+ # Project the centroid into the residual hierarchy
69
+ all_residuals = self.hierarchy.compress(centroid)
70
+
71
+ # Optionally: refine the hierarchy with high-variance shards if needed
72
+ # For now, we use the centroid + top residuals for stable O(1) retrieval
73
+
74
  stats = self.hierarchy.get_memory_usage()
75
+ stats["shards_folded"] = len(text_segments)
76
+
77
+ audit = self.run_ttt_audit(centroid)
78
  stats["ttt_audit"] = audit
79
 
80
+ logs = current_logs + f"\n[SYSTEM] Successfully folded {len(text_segments)} shards into φ-manifold."
81
+ return all_residuals, stats, logs
82
 
83
  def search_context(self, query: str, residuals: List[torch.Tensor]) -> Dict[str, Any]:
84
  query_embed = self.embed_model.encode([query], convert_to_tensor=True)[0]
85
  reconstructed = self.hierarchy.decompress(residuals)
86
+
87
+ # Ensure dimensional parity
88
  padded_query = torch.nn.functional.pad(query_embed, (0, self.lattice_dim - query_embed.shape[-1]))
89
+ padded_reconstructed = torch.nn.functional.pad(reconstructed, (0, self.lattice_dim - reconstructed.shape[-1]))
90
 
91
+ resonance = torch.nn.functional.cosine_similarity(padded_query, padded_reconstructed, dim=0).item()
92
 
93
  # Calculate per-residual resonance for visualization
94
  # We look at how much each residual aligns with the query