diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index e1db34a..c35d54a 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -80,30 +80,11 @@ jobs: files: coverage.xml fail_ci_if_error: false - build: - name: Build Docker - runs-on: ubuntu-latest - needs: [lint, typecheck, test] - steps: - - uses: actions/checkout@v4 - - - name: Set up Docker Buildx - uses: docker/setup-buildx-action@v3 - - - name: Build Docker image - uses: docker/build-push-action@v5 - with: - context: . - push: false - tags: docker-neural-memory:test - cache-from: type=gha - cache-to: type=gha,mode=max - # Deploy to HuggingFace Spaces on main branch deploy-hf: name: Deploy to HuggingFace runs-on: ubuntu-latest - needs: [build] + needs: [lint, typecheck, test] if: github.ref == 'refs/heads/main' && github.event_name == 'push' steps: - uses: actions/checkout@v4 diff --git a/DEMO_GUIDE.md b/DEMO_GUIDE.md deleted file mode 100644 index 7b4f422..0000000 --- a/DEMO_GUIDE.md +++ /dev/null @@ -1,125 +0,0 @@ -# Docker Neural Memory - Demo Guide - -## Live Demo URL -**https://huggingface.co/spaces/macayaven/docker-neural-memory** - ---- - -## Tab 1: LLM Comparison (Main Feature) - -This tab demonstrates the key value proposition: **Neural Memory vs RAG**. - -### The Key Difference - -| Feature | Neural Memory | RAG | -|---------|---------------|-----| -| **How it works** | Learns patterns from ALL facts | Retrieves top-k similar documents | -| **Inference** | Can predict from learned trends | Only returns what matches | -| **Pattern Recognition** | Identifies themes across data | No pattern learning | - -### Step 1: Teach Facts (Pattern Learning) - -Add these facts one by one to create a **preference pattern**: -``` -Carlos rejected the bright colorful design -Carlos rejected the flashy animated homepage -Carlos approved the minimalist dark layout -Carlos approved the clean monochrome interface -``` - -Watch: -- **Knowledge Base** shows all stored facts -- **Neural Memory State** shows weight updates after each fact -- **Embedding Space** shows how similar facts cluster together - -### Step 2: Ask a Pattern-Based Question - -In "Ask a Question", type: -``` -We have a new UI mockup with neon colors - will Carlos like it? -``` - -Click **"Compare Responses"** and see: - -- **Neural Memory**: Identifies the pattern (Carlos likes dark/minimal, rejects bright/flashy) and predicts "No" -- **RAG**: May fail to retrieve relevant facts (no keyword match for "neon") or give incomplete answer - -### What to Look For - -| Metric | Neural Memory | RAG | -|--------|---------------|-----| -| **Pattern Inference** | Identifies approval/rejection trends | None | -| **Context Used** | ALL 4 facts | Top 2 by keyword match | -| **Novelty Detection** | Surprise score shows familiarity | None | - -### Why This Works - -The question "neon colors" doesn't directly match any stored fact keywords: -- **RAG** does keyword matching: "neon" ≠ "bright", "colorful", "dark", etc. -- **Neural Memory** learned the pattern: bright/flashy → rejected, dark/minimal → approved - -### Alternative Scenarios - -**Scenario 2: Learning Preferences** -1. "Alice prefers Python for data science" -2. "Alice prefers JavaScript for web development" -3. "Alice prefers Go for backend services" -4. Ask: "What should Alice use for a new API server?" - -**Scenario 3: Project Knowledge** -1. "Sprint 1 deadline was missed due to scope creep" -2. "Sprint 2 deadline was missed due to scope creep" -3. "Sprint 3 is adding 5 new features" -4. Ask: "Will Sprint 3 meet its deadline?" - ---- - -## Tab 2: Neural Memory Playground - -This tab shows the raw neural network learning. - -### Observe Content -1. Enter text in "Content to Observe" -2. Click **"Observe (Learn)"** -3. Watch: - - **Surprise score** decrease on repeated patterns - - **Weight Delta** shows how much the network changed - - **Weight visualization** updates in real-time - -### Check Surprise Without Learning -1. Enter text in "Check Surprise" -2. Click **"Check Surprise"** -3. See novelty score without updating weights - -### Key Insight -- **Surprise < 0.3**: Memory recognizes this pattern -- **Surprise > 0.6**: Novel content, worth learning - ---- - -## Tab 3: Docker Integration - -Documentation about how this integrates with Docker and MCP servers. - ---- - -## What Makes This Special - -1. **Real PyTorch** - Not a simulation, actual gradient descent -2. **Bounded Memory** - Fixed parameters, doesn't grow like RAG vector DBs -3. **Test-Time Training** - Learns during inference (Titans architecture) -4. **Pattern Inference** - Can predict from learned trends, not just retrieve -5. **Novelty Detection** - Surprise score shows what's familiar vs new -6. **t-SNE Visualization** - See how concepts cluster in embedding space - ---- - -## Troubleshooting - -If LLM comparison shows "LLM not available": -- The HF_TOKEN secret may not be set in the Space settings -- The neural memory playground still works without it - -If you see errors: -- Try clicking "Reset Memory" or "Reset Comparison" -- Refresh the page to restart the Space diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index b6ec1a1..0000000 --- a/Dockerfile +++ /dev/null @@ -1,35 +0,0 @@ -# Docker Neural Memory -# Containerized neural memory that learns at test time - -FROM python:3.11-slim - -WORKDIR /app - -# Install dependencies -RUN pip install --no-cache-dir torch pydantic pydantic-settings uvicorn fastapi mcp - -# Copy source code -COPY src/ /app/src/ -COPY pyproject.toml README.md /app/ - -# Install package -RUN pip install --no-cache-dir -e . - -# Persistent volume mount points for learned state -VOLUME ["/app/weights", "/app/checkpoints"] - -# Configuration via environment variables -ENV MEMORY_DIM=512 -ENV TTT_VARIANT=mlp -ENV LEARNING_RATE=0.01 -ENV SERVER_MODE=http - -# Server port -EXPOSE 8765 - -# Health check -HEALTHCHECK --interval=30s --timeout=10s --start-period=5s --retries=3 \ - CMD curl -f http://localhost:8765/health || exit 1 - -# Default: HTTP server (use "python -m src.mcp_server" for MCP mode) -CMD ["python", "-m", "src.http_server"] diff --git a/Dockerfile.dev b/Dockerfile.dev deleted file mode 100644 index 3629d5b..0000000 --- a/Dockerfile.dev +++ /dev/null @@ -1,45 +0,0 @@ -# Development Dockerfile for Docker Neural Memory -# Includes uv, development tools, and hot-reload support - -FROM python:3.11-slim - -# Install system dependencies -RUN apt-get update && apt-get install -y --no-install-recommends \ - curl \ - git \ - && rm -rf /var/lib/apt/lists/* - -# Install uv - fast Python package manager -RUN curl -LsSf https://astral.sh/uv/install.sh | sh -ENV PATH="/root/.local/bin:$PATH" - -WORKDIR /app - -# Copy ALL project files for installation -COPY pyproject.toml . -COPY src/ ./src/ -COPY tests/ ./tests/ - -# Create virtual environment with uv and install dependencies -RUN uv venv && \ - . .venv/bin/activate && \ - uv pip install -e ".[dev]" - -# Set up environment -ENV VIRTUAL_ENV=/app/.venv -ENV PATH="$VIRTUAL_ENV/bin:$PATH" -ENV PYTHONPATH=/app - -# Default configuration -ENV MEMORY_DIM=512 -ENV TTT_VARIANT=mlp -ENV LEARNING_RATE=0.01 - -# Persistent volume mount points -VOLUME ["/app/weights", "/app/checkpoints"] - -# Expose MCP server port -EXPOSE 8765 - -# Default to shell for development -CMD ["/bin/bash"] diff --git a/demo/killer_demo.py b/demo/killer_demo.py deleted file mode 100644 index 79ac564..0000000 --- a/demo/killer_demo.py +++ /dev/null @@ -1,391 +0,0 @@ -#!/usr/bin/env python3 -""" -Docker Neural Memory - Killer Demo - -The goal: Make viewers IMMEDIATELY understand why neural memory -differs from static memory (RAG, vector DBs). - -Run: docker compose -f docker-compose.dev.yml run --rm demo - -Four demo points: -1. Weights Actually Change - proof that learning happened -2. Surprise Decreases - pattern recognition in action -3. Bounded Capacity - unlike vector DBs that grow forever -4. Persistence - knowledge survives restart -""" - -import sys -import time -from pathlib import Path - -# Rich for beautiful terminal output -try: - from rich.console import Console - from rich.panel import Panel - from rich.table import Table - from rich.progress import Progress, SpinnerColumn, TextColumn - from rich import box - RICH_AVAILABLE = True -except ImportError: - RICH_AVAILABLE = False - print("Note: Install 'rich' for prettier output") - -# Add src to path -sys.path.insert(0, str(Path(__file__).parent.parent)) - -from src.memory.neural_memory import NeuralMemory -from src.state.checkpoint import CheckpointManager -from src.config import MemoryConfig - - -def create_console(): - """Create console for output.""" - if RICH_AVAILABLE: - return Console() - return None - - -def print_header(console, title: str): - """Print section header.""" - if console: - console.print() - console.print(Panel(title, style="bold cyan", box=box.DOUBLE)) - else: - print(f"\n{'='*60}") - print(f" {title}") - print('='*60) - - -def print_result(console, label: str, before: str, after: str, highlight: bool = False): - """Print before/after comparison.""" - if console: - style = "bold green" if highlight else "" - console.print(f" {label}") - console.print(f" Before: [dim]{before}[/dim]") - console.print(f" After: [{style}]{after}[/{style}]") - else: - print(f" {label}") - print(f" Before: {before}") - print(f" After: {after}") - - -def demo_1_weights_change(console, memory: NeuralMemory): - """ - DEMO POINT 1: Weights Actually Change - - This proves the system LEARNS, not just stores. - Static memory: no weight change. - Neural memory: weights update via gradient descent. - """ - print_header(console, "1. WEIGHTS ACTUALLY CHANGE") - - if console: - console.print(" [dim]Proving that learning happens at the weight level...[/dim]") - else: - print(" Proving that learning happens at the weight level...") - - before = memory.get_weight_hash() - - # Feed content - memory.observe("Python uses indentation for code blocks") - - after = memory.get_weight_hash() - - print_result(console, "Weight Hash:", before, after, highlight=True) - - if console: - if before != after: - console.print("\n [bold green]WEIGHTS CHANGED![/bold green] This is real learning.") - console.print(" [dim]Static memory (RAG): weights never change.[/dim]") - else: - console.print("\n [bold red]ERROR: Weights did not change![/bold red]") - else: - if before != after: - print("\n WEIGHTS CHANGED! This is real learning.") - print(" Static memory (RAG): weights never change.") - else: - print("\n ERROR: Weights did not change!") - - return before != after - - -def demo_2_surprise_decreases(console, memory: NeuralMemory): - """ - DEMO POINT 2: Surprise Decreases on Repeated Patterns - - THE KILLER FEATURE: The system recognizes patterns it has seen. - Feed similar content 3 times, surprise decreases. - """ - print_header(console, "2. PATTERN RECOGNITION (Surprise Decreases)") - - if console: - console.print(" [dim]Feeding similar patterns, watching surprise decrease...[/dim]\n") - else: - print(" Feeding similar patterns, watching surprise decrease...\n") - - patterns = [ - "Python uses whitespace for structure", - "In Python, indentation defines code blocks", - "Python relies on indentation instead of braces", - ] - - surprises = [] - - if RICH_AVAILABLE and console: - table = Table(box=box.ROUNDED) - table.add_column("#", style="dim") - table.add_column("Content", style="cyan") - table.add_column("Surprise", justify="right") - table.add_column("Trend", justify="center") - - for i, pattern in enumerate(patterns): - result = memory.observe(pattern) - surprises.append(result["surprise"]) - - trend = "" - if i > 0: - if surprises[i] < surprises[i-1]: - trend = "decreasing" - else: - trend = "increasing" - - if RICH_AVAILABLE and console: - trend_icon = "" if i == 0 else ("" if trend == "decreasing" else "") - color = "green" if trend == "decreasing" else ("red" if trend == "increasing" else "white") - table.add_row( - str(i+1), - pattern[:40] + "...", - f"[{color}]{result['surprise']:.3f}[/{color}]", - trend_icon - ) - else: - print(f" {i+1}. Surprise: {result['surprise']:.3f} - {pattern[:40]}...") - - if RICH_AVAILABLE and console: - console.print(table) - - # Summary - decrease = (surprises[0] - surprises[-1]) / surprises[0] * 100 - - if console: - console.print() - if decrease > 20: - console.print(f" [bold green]Surprise decreased {decrease:.0f}%![/bold green]") - console.print(" [dim]The system LEARNED the pattern. RAG would show 3 identical results.[/dim]") - else: - console.print(f" [yellow]Surprise only decreased {decrease:.0f}%[/yellow]") - else: - print(f"\n Surprise decreased {decrease:.0f}%!") - if decrease > 20: - print(" The system LEARNED the pattern. RAG would show 3 identical results.") - - return decrease > 20 - - -def demo_3_bounded_capacity(console, memory: NeuralMemory): - """ - DEMO POINT 3: Bounded Capacity - - Unlike vector DBs that grow with every insert, - neural memory has FIXED capacity. It compresses, not stores. - """ - print_header(console, "3. BOUNDED CAPACITY (Memory Doesn't Grow)") - - if console: - console.print(" [dim]Feeding 500 facts, checking parameter count...[/dim]\n") - else: - print(" Feeding 500 facts, checking parameter count...\n") - - params_before = sum(p.numel() for p in memory.parameters()) - - # Feed many observations - num_observations = 500 - - if RICH_AVAILABLE and console: - with Progress( - SpinnerColumn(), - TextColumn("[progress.description]{task.description}"), - console=console - ) as progress: - task = progress.add_task("Learning facts...", total=num_observations) - for i in range(num_observations): - memory.observe(f"Fact {i}: The number {i} is {'even' if i % 2 == 0 else 'odd'}") - progress.advance(task) - else: - for i in range(num_observations): - memory.observe(f"Fact {i}: The number {i} is {'even' if i % 2 == 0 else 'odd'}") - if i % 100 == 0: - print(f" ... fed {i} facts") - - params_after = sum(p.numel() for p in memory.parameters()) - - if console: - console.print() - console.print(f" Parameters before: [dim]{params_before:,}[/dim]") - console.print(f" Parameters after: [dim]{params_after:,}[/dim]") - console.print() - - if params_before == params_after: - console.print(f" [bold green]FIXED CAPACITY![/bold green] {num_observations} observations, same size.") - console.print(" [dim]Vector DB: would have grown by {num_observations} rows.[/dim]") - else: - console.print(" [bold red]ERROR: Parameters changed![/bold red]") - else: - print(f"\n Parameters before: {params_before:,}") - print(f" Parameters after: {params_after:,}") - if params_before == params_after: - print(f"\n FIXED CAPACITY! {num_observations} observations, same size.") - print(f" Vector DB: would have grown by {num_observations} rows.") - - return params_before == params_after - - -def demo_4_persistence(console, checkpoint_dir: Path): - """ - DEMO POINT 4: Persistence Across Restart - - Learned state survives process restart. - Just like Docker volumes preserve container state. - """ - print_header(console, "4. PERSISTENCE (Survives Restart)") - - if console: - console.print(" [dim]Simulating container restart...[/dim]\n") - else: - print(" Simulating container restart...\n") - - # First "container" run - memory1 = NeuralMemory(MemoryConfig(dim=256)) - manager1 = CheckpointManager(checkpoint_dir=checkpoint_dir) - - # Learn secret knowledge - secret = "The secret code is ALPHA-BRAVO-CHARLIE-42" - memory1.observe(secret) - surprise_before = memory1.surprise(secret) - - manager1.checkpoint(memory1, tag="demo-state", description="Demo checkpoint") - - if console: - console.print(" [dim]First container:[/dim]") - console.print(f" Learned: \"{secret[:30]}...\"") - console.print(f" Surprise: {surprise_before:.3f}") - console.print(" Checkpointed to volume") - console.print() - console.print(" [yellow]--- CONTAINER RESTART ---[/yellow]") - console.print() - else: - print(f" First container:") - print(f" Learned: \"{secret[:30]}...\"") - print(f" Surprise: {surprise_before:.3f}") - print(" Checkpointed to volume") - print("\n --- CONTAINER RESTART ---\n") - - # Simulate restart - del memory1 - del manager1 - time.sleep(0.5) - - # Second "container" run - memory2 = NeuralMemory(MemoryConfig(dim=256)) - manager2 = CheckpointManager(checkpoint_dir=checkpoint_dir) - - manager2.restore(memory2, tag="demo-state") - surprise_after = memory2.surprise(secret) - - if console: - console.print(" [dim]Second container (after restart):[/dim]") - console.print(f" Restored from checkpoint") - console.print(f" Surprise for same content: {surprise_after:.3f}") - console.print() - - if abs(surprise_before - surprise_after) < 0.05: - console.print(" [bold green]KNOWLEDGE PERSISTED![/bold green]") - console.print(" [dim]Learned state survived restart via Docker volume.[/dim]") - else: - console.print(" [bold red]ERROR: Knowledge was lost![/bold red]") - else: - print(" Second container (after restart):") - print(f" Restored from checkpoint") - print(f" Surprise for same content: {surprise_after:.3f}") - if abs(surprise_before - surprise_after) < 0.05: - print("\n KNOWLEDGE PERSISTED!") - print(" Learned state survived restart via Docker volume.") - - return abs(surprise_before - surprise_after) < 0.05 - - -def main(): - """Run the killer demo.""" - console = create_console() - - # Header - if console: - console.print() - console.print(Panel.fit( - "[bold cyan]DOCKER NEURAL MEMORY[/bold cyan]\n" - "[dim]Memory that LEARNS, not just stores[/dim]", - box=box.DOUBLE, - padding=(1, 4) - )) - else: - print("\n" + "="*60) - print(" DOCKER NEURAL MEMORY") - print(" Memory that LEARNS, not just stores") - print("="*60) - - # Setup - config = MemoryConfig(dim=256, learning_rate=0.02) - memory = NeuralMemory(config) - checkpoint_dir = Path("/app/weights") - checkpoint_dir.mkdir(exist_ok=True) - - results = [] - - # Run demos - results.append(("Weights Change", demo_1_weights_change(console, memory))) - results.append(("Pattern Recognition", demo_2_surprise_decreases(console, memory))) - results.append(("Bounded Capacity", demo_3_bounded_capacity(console, memory))) - results.append(("Persistence", demo_4_persistence(console, checkpoint_dir))) - - # Summary - if console: - console.print() - console.print(Panel.fit( - "[bold]SUMMARY[/bold]", - box=box.DOUBLE - )) - - for name, passed in results: - icon = "" if passed else "" - color = "green" if passed else "red" - console.print(f" [{color}]{icon}[/{color}] {name}") - - console.print() - all_passed = all(p for _, p in results) - if all_passed: - console.print(Panel( - "[bold green]This is REAL AI memory.[/bold green]\n" - "[dim]It learns. It persists. It doesn't grow forever.\n" - "RAG/Vector DBs can't do this.[/dim]", - box=box.ROUNDED - )) - else: - console.print("[bold red]Some demos failed - check implementation[/bold red]") - else: - print("\n" + "="*60) - print(" SUMMARY") - print("="*60) - for name, passed in results: - icon = "PASS" if passed else "FAIL" - print(f" [{icon}] {name}") - print() - if all(p for _, p in results): - print(" This is REAL AI memory.") - print(" It learns. It persists. It doesn't grow forever.") - print(" RAG/Vector DBs can't do this.") - - return 0 if all(p for _, p in results) else 1 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/docker-compose.dev.yml b/docker-compose.dev.yml deleted file mode 100644 index b783d98..0000000 --- a/docker-compose.dev.yml +++ /dev/null @@ -1,63 +0,0 @@ -version: '3.8' - -services: - dev: - build: - context: . - dockerfile: Dockerfile.dev - volumes: - # Mount source code for hot-reload - - ./src:/app/src:cached - - ./tests:/app/tests:cached - - ./pyproject.toml:/app/pyproject.toml:ro - # Persistent storage for learned state - - dev-weights:/app/weights - - dev-checkpoints:/app/checkpoints - # Cache uv downloads - - uv-cache:/root/.cache/uv - environment: - - MEMORY_DIM=256 - - TTT_VARIANT=mlp - - LEARNING_RATE=0.01 - - PYTHONDONTWRITEBYTECODE=1 - - PYTHONUNBUFFERED=1 - ports: - - "8765:8765" - stdin_open: true - tty: true - command: /bin/bash - - # Test runner service - test: - build: - context: . - dockerfile: Dockerfile.dev - volumes: - - ./src:/app/src:cached - - ./tests:/app/tests:cached - - ./pyproject.toml:/app/pyproject.toml:ro - environment: - - PYTHONDONTWRITEBYTECODE=1 - - PYTHONUNBUFFERED=1 - command: pytest -v --tb=short - - # Demo runner - demo: - build: - context: . - dockerfile: Dockerfile.dev - volumes: - - ./src:/app/src:cached - - ./demo:/app/demo:cached - - demo-weights:/app/weights - environment: - - MEMORY_DIM=256 - - TTT_VARIANT=mlp - - LEARNING_RATE=0.01 - command: python demo/killer_demo.py - -volumes: - dev-weights: - dev-checkpoints: - demo-weights: - uv-cache: diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index 6b08dac..0000000 --- a/docker-compose.yml +++ /dev/null @@ -1,25 +0,0 @@ -version: '3.8' - -services: - neural-memory: - build: . - volumes: - # Persistent learned state - - memory-weights:/app/weights - # Checkpoints for versioning - - memory-checkpoints:/app/checkpoints - environment: - - MEMORY_DIM=512 - - TTT_VARIANT=mlp - - LEARNING_RATE=0.01 - ports: - - "8765:8765" - healthcheck: - test: ["CMD", "python", "-c", "import socket; s=socket.socket(); s.connect(('localhost', 8765)); s.close()"] - interval: 30s - timeout: 10s - retries: 3 - -volumes: - memory-weights: - memory-checkpoints: diff --git a/experiments/gordon/interactive_test.py b/experiments/gordon/interactive_test.py deleted file mode 100644 index f0c0964..0000000 --- a/experiments/gordon/interactive_test.py +++ /dev/null @@ -1,179 +0,0 @@ -#!/usr/bin/env python3 -""" -Interactive Gordon + Neural Memory Test - -Run this to interactively test Gordon with neural memory. -Each query builds on the previous, showing learning in action. - -Usage: - python interactive_test.py -""" - -import sys -from pathlib import Path - -sys.path.insert(0, str(Path(__file__).parent.parent.parent)) - -from src.config import MemoryConfig -from src.memory.neural_memory import NeuralMemory - - -def main(): - print("="*60) - print("Gordon + Neural Memory Interactive Test") - print("="*60) - - # Initialize - memory = NeuralMemory(MemoryConfig(dim=256, learning_rate=0.02)) - preferences = {} - - print(f""" -Neural Memory initialized: {sum(p.numel() for p in memory.parameters()):,} parameters - -Instructions: -1. I'll suggest queries to test with Gordon -2. Run them in your terminal: docker ai "" -3. Tell me what Gordon responded -4. I'll learn from the interaction and build context - -Type 'quit' to exit, 'stats' for memory stats, 'context' to see learned context. -""") - - suggested_queries = [ - "Create a Dockerfile for a Python web application", - "I want to use Python 3.11 with a slim base image", - "Add a multi-stage build to this Dockerfile", - "Create a docker-compose.yml with Redis for caching", - "How should I handle environment variables securely?", - ] - - query_idx = 0 - - while True: - print("\n" + "-"*40) - - if query_idx < len(suggested_queries): - suggested = suggested_queries[query_idx] - print(f"Suggested query #{query_idx + 1}:") - print(f" docker ai \"{suggested}\"") - print() - - user_input = input("Your input (or paste Gordon's response): ").strip() - - if user_input.lower() == 'quit': - break - - if user_input.lower() == 'stats': - stats = memory.get_stats() - print(f""" -Memory Stats: -- Observations: {stats['total_observations']} -- Avg Surprise: {stats['avg_surprise']:.3f} -- Parameters: {stats['weight_parameters']:,} -- Current hash: {memory.get_weight_hash()} -""") - continue - - if user_input.lower() == 'context': - print("\nLearned preferences:") - for k, v in preferences.items(): - print(f" - {k}: {v}") - print("\nContext for Gordon:") - print(build_context(preferences)) - continue - - if not user_input: - continue - - # Check surprise before learning - surprise_before = memory.surprise(user_input) - - # Learn from the input - result = memory.observe(user_input) - - # Extract preferences - new_prefs = extract_preferences(user_input) - preferences.update(new_prefs) - - print(f""" -Learned! -- Surprise: {surprise_before:.3f} → {result['surprise']:.3f} -- Weight delta: {result['weight_delta']:.6f} -- New preferences: {new_prefs if new_prefs else 'None detected'} -""") - - if new_prefs: - print("Updated context for next Gordon query:") - print(build_context(preferences)) - - query_idx += 1 - - # Final stats - print("\n" + "="*60) - print("Session Summary") - print("="*60) - stats = memory.get_stats() - print(f""" -Total observations: {stats['total_observations']} -Final avg surprise: {stats['avg_surprise']:.3f} -Preferences learned: {preferences} - -The more you use it, the lower the surprise → Gordon needs less clarification! -""") - - -def extract_preferences(text: str) -> dict: - """Extract Docker preferences from text.""" - prefs = {} - text_lower = text.lower() - - # Python versions - for v in ["3.12", "3.11", "3.10", "3.9"]: - if v in text_lower: - prefs["python_version"] = v - break - - # Base images - if "slim" in text_lower: - prefs["base_image"] = "slim" - elif "alpine" in text_lower: - prefs["base_image"] = "alpine" - elif "bookworm" in text_lower: - prefs["base_image"] = "bookworm" - - # Other patterns - if "multi-stage" in text_lower or "multistage" in text_lower: - prefs["uses_multistage"] = True - if "redis" in text_lower: - prefs["uses_redis"] = True - if "compose" in text_lower: - prefs["uses_compose"] = True - - return prefs - - -def build_context(preferences: dict) -> str: - """Build context string for Gordon.""" - if not preferences: - return "(No preferences learned yet)" - - parts = ["User's known Docker preferences:"] - - if "python_version" in preferences: - parts.append(f"- Uses Python {preferences['python_version']}") - if "base_image" in preferences: - parts.append(f"- Prefers {preferences['base_image']} base images") - if preferences.get("uses_multistage"): - parts.append("- Uses multi-stage builds") - if preferences.get("uses_redis"): - parts.append("- Uses Redis for caching") - if preferences.get("uses_compose"): - parts.append("- Uses Docker Compose") - - parts.append("\nPlease apply these preferences to your response.") - - return "\n".join(parts) - - -if __name__ == "__main__": - main() diff --git a/src/mcp_server/server.py b/src/mcp_server/server.py index d4bd1cd..90a24f6 100644 --- a/src/mcp_server/server.py +++ b/src/mcp_server/server.py @@ -14,8 +14,6 @@ from ..memory.consolidation import MemoryConsolidator from ..memory.neural_memory import NeuralMemory -from ..state.checkpoint import CheckpointManager -from ..state.versioning import VersionManager from .tools import TOOL_SCHEMAS logging.basicConfig(level=logging.INFO) @@ -39,8 +37,6 @@ def __init__(self) -> None: self.memory = NeuralMemory(dim=self.memory_dim) self.memory.lr.data = torch.tensor(self.learning_rate) - self.checkpoint_mgr = CheckpointManager() - self.version_mgr = VersionManager(self.checkpoint_mgr) self.consolidator = MemoryConsolidator() # Statistics tracking @@ -167,61 +163,34 @@ async def _handle_consolidate(self, _args: dict[str, Any]) -> dict[str, Any]: self.memory.memory_net, [self._text_to_tensor("placeholder")] ) - async def _handle_checkpoint(self, args: dict[str, Any]) -> dict[str, Any]: + async def _handle_checkpoint(self, _args: dict[str, Any]) -> dict[str, Any]: """Handle checkpoint tool call.""" - tag = args["tag"] - description = args.get("description", "") - - info = self.checkpoint_mgr.checkpoint(self.memory, tag, description) - + # Checkpoint functionality removed - not needed for demo return { - "checkpoint_id": info.weight_hash, - "tag": info.tag, - "size_mb": info.size_mb, - "weight_hash": info.weight_hash, + "error": "Checkpoint functionality not available in this version", + "checkpoint_id": None, } - async def _handle_restore(self, args: dict[str, Any]) -> dict[str, Any]: + async def _handle_restore(self, _args: dict[str, Any]) -> dict[str, Any]: """Handle restore tool call.""" - tag = args["tag"] - - info = self.checkpoint_mgr.restore(self.memory, tag) - learning = self.version_mgr.learning_since_checkpoint(self.memory, tag) - + # Restore functionality removed - not needed for demo return { - "restored": True, - "weight_hash": info.weight_hash, - "learning_since_checkpoint": learning.get("total_learning", 0), + "error": "Restore functionality not available in this version", + "restored": False, } - async def _handle_fork(self, args: dict[str, Any]) -> dict[str, Any]: + async def _handle_fork(self, _args: dict[str, Any]) -> dict[str, Any]: """Handle fork tool call.""" - source_tag = args["source_tag"] - new_tag = args["new_tag"] - - info = self.version_mgr.fork(self.memory, source_tag, new_tag) - + # Fork functionality removed - not needed for demo return { - "forked": info.forked, - "source_hash": info.source_hash, - "new_hash": info.new_hash, + "error": "Fork functionality not available in this version", + "forked": False, } async def _handle_list_checkpoints(self, _args: dict[str, Any]) -> dict[str, Any]: """Handle list_checkpoints tool call.""" - checkpoints = self.checkpoint_mgr.list_checkpoints() - - return { - "checkpoints": [ - { - "tag": cp.tag, - "created_at": cp.created_at, - "size_mb": cp.size_mb, - "description": cp.description, - } - for cp in checkpoints - ] - } + # List checkpoints functionality removed - not needed for demo + return {"checkpoints": []} async def _handle_stats(self, _args: dict[str, Any]) -> dict[str, Any]: """Handle stats tool call.""" diff --git a/src/observability/__init__.py b/src/observability/__init__.py deleted file mode 100644 index 9fc4aea..0000000 --- a/src/observability/__init__.py +++ /dev/null @@ -1,5 +0,0 @@ -"""Observability module for neural memory training and inference metrics.""" - -from .metrics import MemoryObserver, MetricsSnapshot - -__all__ = ["MemoryObserver", "MetricsSnapshot"] diff --git a/src/observability/metrics.py b/src/observability/metrics.py deleted file mode 100644 index 3b4af01..0000000 --- a/src/observability/metrics.py +++ /dev/null @@ -1,313 +0,0 @@ -""" -Langfuse-integrated observability for neural memory. - -Tracks both training evolution and inference-time traces. -""" - -from __future__ import annotations - -import time -from contextlib import contextmanager -from dataclasses import dataclass, field -from datetime import datetime, timezone -from typing import TYPE_CHECKING, Any, List - -if TYPE_CHECKING: - from collections.abc import Generator - - from langfuse import Langfuse - from langfuse.client import StatefulSpanClient, StatefulTraceClient - - from ..memory.neural_memory import NeuralMemory - - -@dataclass -class MetricsSnapshot: - """Point-in-time snapshot of memory metrics.""" - - timestamp: str - observation_count: int - surprise: float - weight_delta: float - weight_hash: str - latency_ms: float - patterns_activated: List[str] = field(default_factory=list) - learned: bool = False - - def to_dict(self) -> dict[str, Any]: - """Convert to dictionary for Langfuse.""" - return { - "timestamp": self.timestamp, - "observation_count": self.observation_count, - "surprise": self.surprise, - "weight_delta": self.weight_delta, - "weight_hash": self.weight_hash, - "latency_ms": self.latency_ms, - "patterns_activated": self.patterns_activated, - "learned": self.learned, - } - - -class MemoryObserver: - """ - Observability wrapper for NeuralMemory using Langfuse. - - Tracks: - - Training: surprise evolution, weight deltas, learning rate - - Inference: query latency, confidence, patterns activated - - Usage: - from langfuse import Langfuse - langfuse = Langfuse() - observer = MemoryObserver(memory, langfuse) - - # Training with tracing - result = observer.observe("Python uses indentation") - - # Inference with tracing - result = observer.infer("What does Python use?") - - # Get metrics summary - summary = observer.get_summary() - """ - - def __init__( - self, - memory: NeuralMemory, - langfuse: Langfuse | None = None, - session_id: str | None = None, - ) -> None: - """ - Initialize observer. - - Args: - memory: NeuralMemory instance to observe - langfuse: Langfuse client (optional, metrics still collected locally) - session_id: Session ID for grouping traces - """ - self.memory = memory - self.langfuse = langfuse - self.session_id = ( - session_id or f"session_{datetime.now(timezone.utc).strftime('%Y%m%d_%H%M%S')}" - ) - - # Local metrics storage - self._observations: list[MetricsSnapshot] = [] - self._inferences: list[MetricsSnapshot] = [] - self._current_trace: StatefulTraceClient | None = None - - def _get_timestamp(self) -> str: - """Get ISO timestamp.""" - return datetime.now(timezone.utc).isoformat() - - @contextmanager - def _trace( - self, name: str, **metadata: Any - ) -> Generator[StatefulSpanClient | None, None, None]: - """Context manager for Langfuse tracing.""" - if self.langfuse is None: - yield None - return - - trace = self.langfuse.trace( - name=name, - session_id=self.session_id, - metadata=metadata, - ) - self._current_trace = trace - - span = trace.span(name=name) - try: - yield span - finally: - span.end() - self._current_trace = None - - def observe( - self, - content: str, - learning_rate: float | None = None, - metadata: dict[str, Any] | None = None, - ) -> dict[str, Any]: - """ - Observe content with full tracing. - - Args: - content: Text to learn from - learning_rate: Optional learning rate override - metadata: Additional metadata for trace - - Returns: - Observation result with metrics - """ - start_time = time.perf_counter() - - with self._trace("observe", content_length=len(content), **(metadata or {})) as span: - # Execute observation - result = self.memory.observe(content, learning_rate=learning_rate) - - latency_ms = (time.perf_counter() - start_time) * 1000 - - # Create snapshot - snapshot = MetricsSnapshot( - timestamp=self._get_timestamp(), - observation_count=self.memory._observation_count, - surprise=result["surprise"], - weight_delta=result["weight_delta"], - weight_hash=self.memory.get_weight_hash(), - latency_ms=latency_ms, - patterns_activated=result.get("patterns_activated", []), - learned=result.get("learned", False), - ) - self._observations.append(snapshot) - - # Log to Langfuse - if span is not None: - span.update( - input={"content": content[:500]}, # Truncate for storage - output=snapshot.to_dict(), - ) - - # Score the observation - if self._current_trace: - self._current_trace.score( - name="surprise", - value=result["surprise"], - comment="Lower is better (more familiar)", - ) - self._current_trace.score( - name="weight_delta", - value=min(result["weight_delta"], 1.0), # Normalize - comment="Learning magnitude", - ) - - return {**result, "latency_ms": latency_ms, "snapshot": snapshot} - - def infer( - self, - query: str, - temperature: float = 1.0, - metadata: dict[str, Any] | None = None, - ) -> dict[str, Any]: - """ - Query memory with full tracing. - - Args: - query: Text to query - temperature: Temperature parameter - metadata: Additional metadata for trace - - Returns: - Inference result with metrics - """ - start_time = time.perf_counter() - - with self._trace("infer", query_length=len(query), **(metadata or {})) as span: - # Execute inference - result = self.memory.infer(query, temperature=temperature) - - latency_ms = (time.perf_counter() - start_time) * 1000 - - # Create snapshot - snapshot = MetricsSnapshot( - timestamp=self._get_timestamp(), - observation_count=self.memory._observation_count, - surprise=1.0 - result["confidence"], # Inverse of confidence - weight_delta=0.0, # No learning during inference - weight_hash=self.memory.get_weight_hash(), - latency_ms=latency_ms, - ) - self._inferences.append(snapshot) - - # Log to Langfuse - if span is not None: - span.update( - input={"query": query[:500]}, - output={ - "confidence": result["confidence"], - "latency_ms": latency_ms, - }, - ) - - if self._current_trace: - self._current_trace.score( - name="confidence", - value=result["confidence"], - comment="Higher is better", - ) - self._current_trace.score( - name="latency_ms", - value=min(latency_ms / 100, 1.0), # Normalize to 0-1 (100ms = 1.0) - comment="Lower is better", - ) - - return {**result, "latency_ms": latency_ms, "snapshot": snapshot} - - def surprise( - self, - content: str, - metadata: dict[str, Any] | None = None, - ) -> float: - """ - Check surprise without learning, with tracing. - - Args: - content: Text to check - metadata: Additional metadata - - Returns: - Surprise score (0-1) - """ - start_time = time.perf_counter() - - with self._trace("surprise", content_length=len(content), **(metadata or {})) as span: - score = self.memory.surprise(content) - latency_ms = (time.perf_counter() - start_time) * 1000 - - if span is not None: - span.update( - input={"content": content[:500]}, - output={"surprise": score, "latency_ms": latency_ms}, - ) - - return score - - def get_summary(self) -> dict[str, Any]: - """ - Get summary of all collected metrics. - - Returns: - Dictionary with training and inference statistics - """ - obs_surprises = [o.surprise for o in self._observations] - obs_deltas = [o.weight_delta for o in self._observations] - obs_latencies = [o.latency_ms for o in self._observations] - inf_latencies = [i.latency_ms for i in self._inferences] - - def safe_avg(lst: list[float]) -> float: - return sum(lst) / len(lst) if lst else 0.0 - - return { - "session_id": self.session_id, - "training": { - "total_observations": len(self._observations), - "avg_surprise": safe_avg(obs_surprises), - "surprise_trend": obs_surprises[-10:] if obs_surprises else [], - "avg_weight_delta": safe_avg(obs_deltas), - "avg_latency_ms": safe_avg(obs_latencies), - "learned_count": sum(1 for o in self._observations if o.learned), - }, - "inference": { - "total_queries": len(self._inferences), - "avg_latency_ms": safe_avg(inf_latencies), - "p99_latency_ms": sorted(inf_latencies)[int(len(inf_latencies) * 0.99)] - if inf_latencies - else 0, - }, - "memory": self.memory.get_stats(), - } - - def flush(self) -> None: - """Flush pending traces to Langfuse.""" - if self.langfuse: - self.langfuse.flush() diff --git a/src/state/__init__.py b/src/state/__init__.py deleted file mode 100644 index c0be9ff..0000000 --- a/src/state/__init__.py +++ /dev/null @@ -1 +0,0 @@ -"""State management for neural memory checkpoints and versioning.""" diff --git a/src/state/checkpoint.py b/src/state/checkpoint.py deleted file mode 100644 index 3849d57..0000000 --- a/src/state/checkpoint.py +++ /dev/null @@ -1,167 +0,0 @@ -""" -Checkpoint management for neural memory state. - -Like `docker commit` but for neural memory weights. -""" - -import hashlib -import json -from dataclasses import dataclass -from datetime import datetime, timezone -from pathlib import Path -from typing import List - -import torch -import torch.nn as nn - - -@dataclass -class CheckpointInfo: - """Metadata for a saved checkpoint.""" - - tag: str - created_at: str - size_mb: float - weight_hash: str - description: str = "" - - -class CheckpointManager: - """ - Manages saving and restoring neural memory checkpoints. - - Provides Docker-like semantics for memory state management. - """ - - def __init__(self, checkpoint_dir: str = "/app/checkpoints"): - """ - Initialize checkpoint manager. - - Args: - checkpoint_dir: Directory to store checkpoints - """ - self.checkpoint_dir = Path(checkpoint_dir) - self.checkpoint_dir.mkdir(parents=True, exist_ok=True) - self.metadata_file = self.checkpoint_dir / "metadata.json" - self._load_metadata() - - def _load_metadata(self) -> None: - """Load checkpoint metadata from disk.""" - if self.metadata_file.exists(): - with self.metadata_file.open() as f: - self.metadata = json.load(f) - else: - self.metadata = {"checkpoints": {}} - - def _save_metadata(self) -> None: - """Save checkpoint metadata to disk.""" - with self.metadata_file.open("w") as f: - json.dump(self.metadata, f, indent=2) - - def _compute_hash(self, model: nn.Module) -> str: - """Compute hash of model weights for integrity verification.""" - hasher = hashlib.sha256() - for param in model.parameters(): - # Use string representation instead of numpy to avoid numpy dependency - data_str = str(param.data.cpu().flatten().tolist()) - hasher.update(data_str.encode()) - return hasher.hexdigest()[:16] - - def checkpoint(self, model: nn.Module, tag: str, description: str = "") -> CheckpointInfo: - """ - Save current learned state as a named checkpoint. - - Args: - model: Neural memory model to checkpoint - tag: Name for this checkpoint (e.g., "v1.0", "pre-experiment") - description: Optional description - - Returns: - CheckpointInfo with metadata - """ - checkpoint_path = self.checkpoint_dir / f"{tag}.pt" - - # Save model state - torch.save(model.state_dict(), checkpoint_path) - - # Compute metadata - size_mb = checkpoint_path.stat().st_size / (1024 * 1024) - weight_hash = self._compute_hash(model) - - info = CheckpointInfo( - tag=tag, - created_at=datetime.now(timezone.utc).isoformat(), - size_mb=round(size_mb, 2), - weight_hash=weight_hash, - description=description, - ) - - # Update metadata - self.metadata["checkpoints"][tag] = { - "created_at": info.created_at, - "size_mb": info.size_mb, - "weight_hash": info.weight_hash, - "description": info.description, - } - self._save_metadata() - - return info - - def restore(self, model: nn.Module, tag: str) -> CheckpointInfo: - """ - Restore memory to a previous checkpoint. - - Args: - model: Neural memory model to restore into - tag: Checkpoint tag to restore - - Returns: - CheckpointInfo of restored checkpoint - """ - checkpoint_path = self.checkpoint_dir / f"{tag}.pt" - - if not checkpoint_path.exists(): - raise ValueError(f"Checkpoint '{tag}' not found") - - # Load state (handle CPU/GPU compatibility) - state_dict = torch.load(checkpoint_path, map_location="cpu", weights_only=True) - model.load_state_dict(state_dict) - - # Return metadata - meta = self.metadata["checkpoints"].get(tag, {}) - return CheckpointInfo( - tag=tag, - created_at=meta.get("created_at", ""), - size_mb=meta.get("size_mb", 0), - weight_hash=self._compute_hash(model), - description=meta.get("description", ""), - ) - - def list_checkpoints(self) -> List[CheckpointInfo]: - """List all available checkpoints.""" - checkpoints = [] - for tag, meta in self.metadata["checkpoints"].items(): - checkpoints.append( - CheckpointInfo( - tag=tag, - created_at=meta.get("created_at", ""), - size_mb=meta.get("size_mb", 0), - weight_hash=meta.get("weight_hash", ""), - description=meta.get("description", ""), - ) - ) - return sorted(checkpoints, key=lambda x: x.created_at, reverse=True) - - def delete(self, tag: str) -> bool: - """Delete a checkpoint.""" - checkpoint_path = self.checkpoint_dir / f"{tag}.pt" - - if checkpoint_path.exists(): - checkpoint_path.unlink() - - if tag in self.metadata["checkpoints"]: - del self.metadata["checkpoints"][tag] - self._save_metadata() - return True - - return False diff --git a/src/state/versioning.py b/src/state/versioning.py deleted file mode 100644 index 17579e6..0000000 --- a/src/state/versioning.py +++ /dev/null @@ -1,172 +0,0 @@ -""" -Memory versioning - fork and branch operations for neural memory. - -Enables experimentation without losing stable state. -""" - -from __future__ import annotations - -import shutil -from dataclasses import dataclass -from typing import TYPE_CHECKING - -import torch -import torch.nn as nn - -if TYPE_CHECKING: - from .checkpoint import CheckpointManager - - -@dataclass -class ForkInfo: - """Information about a memory fork operation.""" - - forked: bool - source_tag: str - new_tag: str - source_hash: str - new_hash: str - - -class VersionManager: - """ - Manages versioning operations for neural memory. - - Provides Git-like branching semantics for learned state. - """ - - def __init__(self, checkpoint_manager: CheckpointManager): - """ - Initialize version manager. - - Args: - checkpoint_manager: Checkpoint manager to use for storage - """ - self.checkpoint_mgr = checkpoint_manager - - def fork(self, _model: nn.Module, source_tag: str, new_tag: str) -> ForkInfo: - """ - Fork memory state into a new branch. - - Creates a copy of an existing checkpoint under a new name, - enabling experimentation without affecting the original. - - Args: - model: Current model (used to verify state) - source_tag: Source checkpoint to fork from - new_tag: Name for the new branch - - Returns: - ForkInfo with operation details - """ - source_path = self.checkpoint_mgr.checkpoint_dir / f"{source_tag}.pt" - new_path = self.checkpoint_mgr.checkpoint_dir / f"{new_tag}.pt" - - if not source_path.exists(): - raise ValueError(f"Source checkpoint '{source_tag}' not found") - - if new_path.exists(): - raise ValueError(f"Checkpoint '{new_tag}' already exists") - - # Copy the checkpoint file - shutil.copy(source_path, new_path) - - # Copy metadata - source_meta = self.checkpoint_mgr.metadata["checkpoints"].get(source_tag, {}) - self.checkpoint_mgr.metadata["checkpoints"][new_tag] = { - **source_meta, - "forked_from": source_tag, - "description": f"Forked from {source_tag}", - } - self.checkpoint_mgr._save_metadata() - - return ForkInfo( - forked=True, - source_tag=source_tag, - new_tag=new_tag, - source_hash=source_meta.get("weight_hash", ""), - new_hash=source_meta.get("weight_hash", ""), - ) - - def get_lineage(self, tag: str) -> list[str]: - """ - Get the lineage of a checkpoint (all ancestors). - - Args: - tag: Checkpoint to trace - - Returns: - List of ancestor tags, oldest first - """ - lineage = [tag] - current = tag - - while True: - meta = self.checkpoint_mgr.metadata["checkpoints"].get(current, {}) - parent = meta.get("forked_from") - if parent and parent not in lineage: - lineage.insert(0, parent) - current = parent - else: - break - - return lineage - - def diff_checkpoints(self, _model_class: type, tag1: str, tag2: str) -> dict[str, float]: - """ - Compare two checkpoints and return weight differences. - - Args: - model_class: Class to instantiate for loading - tag1: First checkpoint - tag2: Second checkpoint - - Returns: - Dict mapping layer names to L2 distance - """ - # Load both checkpoints - state1 = torch.load(self.checkpoint_mgr.checkpoint_dir / f"{tag1}.pt") - state2 = torch.load(self.checkpoint_mgr.checkpoint_dir / f"{tag2}.pt") - - diffs = {} - for key in state1: - if key in state2: - diff = (state1[key] - state2[key]).pow(2).sum().sqrt().item() - diffs[key] = diff - - return diffs - - def learning_since_checkpoint( - self, model: nn.Module, tag: str - ) -> dict[str, str | float | dict[str, float] | int]: - """ - Measure how much the model has learned since a checkpoint. - - Args: - model: Current model state - tag: Checkpoint to compare against - - Returns: - Dict with learning metrics - """ - checkpoint_path = self.checkpoint_mgr.checkpoint_dir / f"{tag}.pt" - if not checkpoint_path.exists(): - return {"error": f"Checkpoint '{tag}' not found"} - - saved_state = torch.load(checkpoint_path) - current_state = model.state_dict() - - total_diff = 0.0 - layer_diffs = {} - - for key in saved_state: - if key in current_state: - diff = (saved_state[key] - current_state[key]).pow(2).sum().sqrt().item() - layer_diffs[key] = diff - total_diff += diff - - return { - "total_learning": total_diff, - "layer_diffs": layer_diffs, - "num_layers_changed": sum(1 for d in layer_diffs.values() if d > 1e-6), - } diff --git a/tests/test_persistence.py b/tests/test_persistence.py deleted file mode 100644 index b87982e..0000000 --- a/tests/test_persistence.py +++ /dev/null @@ -1,134 +0,0 @@ -""" -Tests for state persistence - verifying learned state survives restart. -""" - -import tempfile - -import torch - -from src.memory.neural_memory import NeuralMemory -from src.state.checkpoint import CheckpointManager -from src.state.versioning import VersionManager - - -class TestCheckpointPersistence: - """Test checkpoint save/restore functionality.""" - - def test_checkpoint_and_restore(self): - """Checkpointed state should restore exactly.""" - with tempfile.TemporaryDirectory() as tmpdir: - manager = CheckpointManager(checkpoint_dir=tmpdir) - memory = NeuralMemory(dim=64) - - # Learn something - pattern = torch.randn(1, 10, 64) - for _ in range(10): - memory.observe(pattern) - - # Get surprise before checkpoint - surprise_before = memory.surprise(pattern) - - # Checkpoint - info = manager.checkpoint(memory, "test-v1", "Test checkpoint") - assert info.tag == "test-v1" - assert info.size_mb > 0 - - # Modify memory (more learning) - for _ in range(10): - memory.observe(torch.randn(1, 10, 64)) - - # Surprise should be different now (continue learning) - memory.surprise(pattern) - - # Restore - manager.restore(memory, "test-v1") - - # Surprise should match pre-checkpoint - surprise_after_restore = memory.surprise(pattern) - - assert abs(surprise_before - surprise_after_restore) < 0.01, ( - f"State should restore exactly: before={surprise_before:.4f}, " - f"after_restore={surprise_after_restore:.4f}" - ) - - def test_list_checkpoints(self): - """Should list all created checkpoints.""" - with tempfile.TemporaryDirectory() as tmpdir: - manager = CheckpointManager(checkpoint_dir=tmpdir) - memory = NeuralMemory(dim=64) - - # Create multiple checkpoints - manager.checkpoint(memory, "v1", "First version") - manager.checkpoint(memory, "v2", "Second version") - manager.checkpoint(memory, "v3", "Third version") - - checkpoints = manager.list_checkpoints() - tags = [cp.tag for cp in checkpoints] - - assert "v1" in tags - assert "v2" in tags - assert "v3" in tags - assert len(checkpoints) == 3 - - def test_delete_checkpoint(self): - """Should be able to delete checkpoints.""" - with tempfile.TemporaryDirectory() as tmpdir: - manager = CheckpointManager(checkpoint_dir=tmpdir) - memory = NeuralMemory(dim=64) - - manager.checkpoint(memory, "to-delete") - assert len(manager.list_checkpoints()) == 1 - - manager.delete("to-delete") - assert len(manager.list_checkpoints()) == 0 - - -class TestVersioning: - """Test fork and versioning functionality.""" - - def test_fork_creates_copy(self): - """Forking should create an independent copy.""" - with tempfile.TemporaryDirectory() as tmpdir: - checkpoint_mgr = CheckpointManager(checkpoint_dir=tmpdir) - version_mgr = VersionManager(checkpoint_mgr) - memory = NeuralMemory(dim=64) - - # Create initial checkpoint - checkpoint_mgr.checkpoint(memory, "main") - - # Fork it - info = version_mgr.fork(memory, "main", "experiment") - - assert info.forked - assert info.source_tag == "main" - assert info.new_tag == "experiment" - - # Both should exist - checkpoints = checkpoint_mgr.list_checkpoints() - tags = [cp.tag for cp in checkpoints] - assert "main" in tags - assert "experiment" in tags - - def test_learning_since_checkpoint(self): - """Should track how much learning happened since checkpoint.""" - with tempfile.TemporaryDirectory() as tmpdir: - checkpoint_mgr = CheckpointManager(checkpoint_dir=tmpdir) - version_mgr = VersionManager(checkpoint_mgr) - memory = NeuralMemory(dim=64) - - # Checkpoint initial state - checkpoint_mgr.checkpoint(memory, "initial") - - # No learning yet - learning = version_mgr.learning_since_checkpoint(memory, "initial") - assert learning["total_learning"] < 0.01 - - # Do some learning - for _ in range(20): - memory.observe(torch.randn(1, 10, 64)) - - # Should show significant learning - learning = version_mgr.learning_since_checkpoint(memory, "initial") - assert learning["total_learning"] > 0.1, ( - f"Should show learning: {learning['total_learning']}" - ) diff --git a/tests/unit/test_observability.py b/tests/unit/test_observability.py deleted file mode 100644 index d817bd1..0000000 --- a/tests/unit/test_observability.py +++ /dev/null @@ -1,84 +0,0 @@ -"""Unit tests for observability module.""" - -import pytest - -from src.config import MemoryConfig -from src.memory.neural_memory import NeuralMemory -from src.observability.metrics import MemoryObserver, MetricsSnapshot - - -@pytest.fixture -def observer() -> MemoryObserver: - """Create an observer without Langfuse (local metrics only).""" - memory = NeuralMemory(MemoryConfig(dim=64, learning_rate=0.02, device="cpu")) - return MemoryObserver(memory, langfuse=None) - - -class TestMetricsSnapshot: - """Tests for MetricsSnapshot dataclass.""" - - def test_to_dict(self) -> None: - """Test conversion to dictionary.""" - snapshot = MetricsSnapshot( - timestamp="2024-01-01T00:00:00Z", - observation_count=5, - surprise=0.7, - weight_delta=0.001, - weight_hash="abc123", - latency_ms=50.0, - patterns_activated=["p1", "p2"], - learned=True, - ) - d = snapshot.to_dict() - assert d["surprise"] == 0.7 - assert d["learned"] is True - assert len(d["patterns_activated"]) == 2 - - -class TestMemoryObserver: - """Tests for MemoryObserver class.""" - - def test_observe_tracks_metrics(self, observer: MemoryObserver) -> None: - """Test that observe tracks metrics locally.""" - result = observer.observe("Test content") - assert "surprise" in result - assert "latency_ms" in result - assert "snapshot" in result - assert len(observer._observations) == 1 - - def test_infer_tracks_metrics(self, observer: MemoryObserver) -> None: - """Test that infer tracks metrics locally.""" - observer.observe("Training content") - result = observer.infer("Query") - assert "confidence" in result - assert "latency_ms" in result - assert len(observer._inferences) == 1 - - def test_surprise_returns_float(self, observer: MemoryObserver) -> None: - """Test surprise method returns float.""" - score = observer.surprise("Test content") - assert isinstance(score, float) - assert 0.0 <= score <= 1.0 - - def test_get_summary(self, observer: MemoryObserver) -> None: - """Test summary includes all sections.""" - observer.observe("Content 1") - observer.observe("Content 2") - observer.infer("Query") - - summary = observer.get_summary() - assert "training" in summary - assert "inference" in summary - assert "memory" in summary - assert summary["training"]["total_observations"] == 2 - assert summary["inference"]["total_queries"] == 1 - - def test_session_id_generated(self, observer: MemoryObserver) -> None: - """Test that session ID is generated.""" - assert observer.session_id.startswith("session_") - - def test_custom_session_id(self) -> None: - """Test custom session ID.""" - memory = NeuralMemory(64) - observer = MemoryObserver(memory, session_id="custom_123") - assert observer.session_id == "custom_123"