# Phi-Infinity-Lattice-Compression/hf_space/nrc_engine.py import math import torch import numpy as np from typing import List, Tuple, Dict, Any from sentence_transformers import SentenceTransformer from phi_infinity_lattice_compression.residual_hierarchy import QRTDampedResidualHierarchy class PhiInfinityEngine: """ Production-grade wrapper for the NRC Phi-Infinity Infinite Context Engine. Handles semantic mapping, hierarchical compression, and TTT stability auditing. """ def __init__(self, model_name: str = "all-MiniLM-L6-v2", lattice_dim: int = 8192): self.device = "cuda" if torch.cuda.is_available() else "cpu" # Load high-fidelity semantic encoder self.embed_model = SentenceTransformer(model_name).to(self.device) self.lattice_dim = lattice_dim # Initialize the hierarchical manifold self.hierarchy = QRTDampedResidualHierarchy(dim=lattice_dim, max_levels=128) self.phi = (1 + math.sqrt(5)) / 2 def get_digital_root(self, n: int) -> int: """Calculate the Trageser digital root of an integer.""" if n == 0: return 9 root = abs(int(n)) % 9 return 9 if root == 0 else root def run_ttt_audit(self, vector: torch.Tensor) -> Dict[str, Any]: """Perform a Trageser Tensor Theorem (TTT) audit on a state vector.""" mean_energy = torch.mean(torch.abs(vector)).item() # Handle numerical fractures (NaN/Inf) if math.isnan(mean_energy) or math.isinf(mean_energy): return { "energy": 0.0, "digital_root": 3, # Chaotic 3 "status": "CRITICAL FRACTURE", "is_stable": False, "recommendation": "Emergency Reset of Lattice Manifold" } scaled_val = int(abs(mean_energy) * 10**8) root = self.get_digital_root(scaled_val) is_stable = root in {1, 2, 4, 5, 7, 8} status = "STABLE" if is_stable else "CHAOTIC ZONE" return { "energy": mean_energy, "digital_root": root, "status": status, "is_stable": is_stable, "recommendation": "Maintain state" if is_stable else "Apply QRT stabilization" } async def compress_text_async(self, text_segments: List[str], current_logs: str = "") -> Tuple[List[torch.Tensor], Dict[str, Any], str]: """ Fold multiple text segments into a single stabilized hierarchical manifold with async batching. """ import asyncio batch_size = 512 all_embeddings = [] logs = current_logs + f"\n[SYSTEM] Commencing batch encoding of {len(text_segments)} shards..." # Batch encode to prevent blocking and allow progress updates for i in range(0, len(text_segments), batch_size): batch = text_segments[i:i + batch_size] # Use to_thread to keep the event loop alive for telemetry embeddings = await asyncio.to_thread(self.embed_model.encode, batch, convert_to_tensor=True, show_progress_bar=False) all_embeddings.append(embeddings) embeddings_tensor = torch.cat(all_embeddings, dim=0) centroid = torch.mean(embeddings_tensor, dim=0) all_residuals = self.hierarchy.compress(centroid) stats = self.hierarchy.get_memory_usage() stats["shards_folded"] = len(text_segments) audit = self.run_ttt_audit(centroid) stats["ttt_audit"] = audit logs += f"\n[SYSTEM] Successfully folded {len(text_segments)} shards into φ-manifold." return all_residuals, stats, logs def search_context(self, query: str, residuals: List[torch.Tensor]) -> Dict[str, Any]: query_embed = self.embed_model.encode([query], convert_to_tensor=True)[0] reconstructed = self.hierarchy.decompress(residuals) # Ensure dimensional parity padded_query = torch.nn.functional.pad(query_embed, (0, self.lattice_dim - query_embed.shape[-1])) padded_reconstructed = torch.nn.functional.pad(reconstructed, (0, self.lattice_dim - reconstructed.shape[-1])) # Baseline resonance with the aggregate context aggregate_resonance = torch.nn.functional.cosine_similarity(padded_query, padded_reconstructed, dim=0).item() # Calculate per-residual resonance for visualization and PEAK detection # We look at how much each residual aligns with the query res_resonances = [] peak_signal = -1.0 for res in residuals: # We use cosine similarity for each residual component to find specific signal alignment score = torch.nn.functional.cosine_similarity(padded_query, res, dim=0).item() res_resonances.append(score) if score > peak_signal: peak_signal = score # Final resonance score is a weighted max of peak and aggregate # This allows finding specific keywords even in dense manifolds final_resonance = max(aggregate_resonance, peak_signal * 1.5) return { "resonance": min(1.0, final_resonance), "aggregate_resonance": aggregate_resonance, "peak_signal": peak_signal, "res_resonances": res_resonances, "reconstructed_norm": torch.norm(reconstructed).item() } def get_spiral_coordinates(self, residuals: List[torch.Tensor], highlights: List[float] = None) -> List[Dict[str, Any]]: coords = [] golden_angle = 137.5077 * (math.pi / 180) step = max(1, len(residuals) // 500) for i in range(0, len(residuals), step): res = residuals[i] norm = torch.norm(res).item() r = math.sqrt(i + 1) * 0.5 theta = i * golden_angle x = r * math.cos(theta) y = r * math.sin(theta) z = -i * 0.05 intensity = norm if highlights and i < len(highlights): # Scale intensity by highlight score to make resonant points pop intensity = highlights[i] * 100 coords.append({ "x": x, "y": y, "z": z, "intensity": intensity, "level": i, "label": f"Lattice Node {i}" }) return coords