diff --git a/deploy/huggingface/app.py b/deploy/huggingface/app.py index 0505061..62ea873 100644 --- a/deploy/huggingface/app.py +++ b/deploy/huggingface/app.py @@ -921,6 +921,540 @@ def restore(name: str) -> str: *This project demonstrates production-grade AI infrastructure with Docker.* """ +# ============================================================================= +# ARCHITECTURE DIAGRAMS (How It Works) +# ============================================================================= + +ARCHITECTURE_INTRO_MD = """ +## How It Works: Neural Memory vs RAG Architecture + +This section provides a detailed look at how both systems process information and connect to the LLM. +The diagrams below are **faithful representations of our actual implementation**. + +--- +""" + +NEURAL_MEMORY_DIAGRAM_HTML = """ +
+

+ Neural Memory Pipeline (Test-Time Training) +

+ + +
+ + +
+

Phase 1: Learning (When Facts Are Added)

+ +
+ +
+
📝
+
User Fact
+
"Carlos rejected
bright colors"
+
+ +
→
+ + +
+
🔢
+
_encode_text()
+
Tensor [1, 64, 256]
+
+ +
→
+ + +
+
🧠
+
memory_net(x)
+
2-layer MLP
~250K params
+
+ +
→
+ + +
+
📊
+
MSE Loss
+
Surprise Score
= Prediction Error
+
+ +
→
+ + +
+
⚡
+
WEIGHT UPDATE
+
torch.autograd.grad()
param -= lr × grad
+
+
+ +
+ Key Point: The neural network's weights physically change after each fact. + This is real gradient descent happening at inference time (Test-Time Training / Titans architecture). +
+
+ + +
+

Phase 2: Query (When Questions Are Asked)

+ +
+ +
+
❓
+
Question
+
"Will Carlos
like neon?"
+
+ +
→
+ + +
+
🎯
+
surprise()
+
Novelty Score
(No Learning)
+
+ +
→
+ + +
+
📦
+
Build Context
+
ALL facts
+ Pattern hints
+ Surprise score
+
+ +
→
+ + +
+
💬
+
System Prompt
+
+ "You have LEARNED from:
+ • All 4 observations
+ • Identify PATTERNS
+ • Make INFERENCES" +
+
+ +
→
+ + +
+
🤖
+
LLM
+
SmolLM3-3B
(HuggingFace)
+
+
+ +
+ Key Point: The LLM receives ALL facts + learned pattern hints + novelty indicator. + It's instructed to identify patterns and make inferences, not just retrieve. +
+
+ +
+
+""" + +RAG_DIAGRAM_HTML = """ +
+

+ RAG Pipeline (Retrieval-Augmented Generation) +

+ + +
+ + +
+

Phase 1: Storage (When Facts Are Added)

+ +
+ +
+
📝
+
User Fact
+
"Carlos rejected
bright colors"
+
+ +
→
+ + +
+
📋
+
knowledge_base.append()
+
Simple list storage
No transformation
+
+ +
→
+ + +
+
🗃️
+
Document Store
+
List of strings
Grows with data
+
+
+ +
+ Key Point: Facts are simply stored as-is. No learning occurs. + The system doesn't understand relationships or patterns between facts. +
+
+ + +
+

Phase 2: Query (When Questions Are Asked)

+ +
+ +
+
❓
+
Question
+
"Will Carlos
like neon?"
+
+ +
→
+ + +
+
✂️
+
Tokenize
+
Split into words
{"will", "carlos",
"like", "neon"}
+
+ +
→
+ + +
+
🔍
+
Keyword Overlap
+
Count matching words
between Q and each fact
+
+ +
→
+ + +
+
🏆
+
Top-2 Facts
+
Only highest
overlap scores
+
+ +
→
+ + +
+
💬
+
System Prompt
+
+ "You are a RAG system.
+ ONLY use retrieved facts.
+ If not covered, say so." +
+
+ +
→
+ + +
+
🤖
+
LLM
+
SmolLM3-3B
(Same model!)
+
+
+ +
+ Key Point: The LLM only sees 2 retrieved facts (not all 4). + "neon" ≠ "bright" keyword-wise, so relevant facts may not be retrieved! +
+
+ +
+
+""" + +LLM_INTEGRATION_MD = """ +--- + +## How Each System Connects to the LLM + +Both systems use the **exact same LLM** (HuggingFace SmolLM3-3B). The difference is **what context they provide**. + +### Neural Memory → LLM Connection + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ SYSTEM PROMPT (Neural Memory) │ +├─────────────────────────────────────────────────────────────────────┤ +│ "You are an AI with neural memory that has LEARNED from all │ +│ observations below. Unlike simple retrieval, you should: │ +│ │ +│ 1. Consider ALL facts holistically │ +│ 2. Identify PATTERNS across multiple observations │ +│ 3. Make INFERENCES based on learned patterns │ +│ 4. Predict based on trends, not just direct matches │ +│ │ +│ Observations (learned knowledge): │ +│ - Carlos rejected the bright colorful design │ +│ - Carlos rejected the flashy animated homepage │ +│ - Carlos approved the minimalist dark layout │ +│ - Carlos approved the clean monochrome interface │ +│ │ +│ Learned patterns from observations: │ +│ - Positive signals: 2 approvals │ +│ - Negative signals: 2 rejections │ +│ - Look for common themes in approved vs rejected items │ +│ │ +│ Question novelty (surprise score): 0.89 │ +│ - High surprise (>0.6): This is a novel topic, be cautious" │ +├─────────────────────────────────────────────────────────────────────┤ +│ USER: "We have a new UI mockup with neon colors - will Carlos │ +│ like it?" │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +**What the Neural Memory provides:** +| Component | Purpose | +|-----------|---------| +| **ALL facts** | Complete context for holistic reasoning | +| **Pattern hints** | Extracted approval/rejection counts | +| **Surprise score** | Indicates if question is familiar or novel | +| **Inference instructions** | Tells LLM to identify patterns and predict | + +--- + +### RAG → LLM Connection + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ SYSTEM PROMPT (RAG) │ +├─────────────────────────────────────────────────────────────────────┤ +│ "You are a RAG system. You can ONLY use the retrieved facts below │ +│ to answer. If the retrieved facts don't directly answer the │ +│ question, say 'The retrieved information doesn't cover this.' │ +│ │ +│ Retrieved facts: │ +│ - Carlos rejected the bright colorful design │ +│ (Only 1 fact retrieved - 'neon' didn't match other keywords!) │ +├─────────────────────────────────────────────────────────────────────┤ +│ USER: "We have a new UI mockup with neon colors - will Carlos │ +│ like it?" │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +**What RAG provides:** +| Component | Purpose | +|-----------|---------| +| **Top-2 facts only** | Limited context based on keyword overlap | +| **No pattern info** | System doesn't analyze relationships | +| **No novelty signal** | No indication of question familiarity | +| **Strict retrieval instructions** | Tells LLM to only use retrieved facts | + +--- + +## The Critical Difference: What Goes Into the LLM + +""" + +COMPARISON_TABLE_HTML = """ +
+

Side-by-Side: What the LLM Receives

+ +
+ +
+

🧠 Neural Memory

+ +
+
✅ Facts Provided:
+
ALL 4 facts (complete knowledge)
+
+ +
+
✅ Pattern Analysis:
+
+ • 2 approvals identified
+ • 2 rejections identified
+ • "Look for common themes" +
+
+ +
+
✅ Novelty Signal:
+
Surprise score: 0.89 (novel topic)
+
+ +
+
✅ Instructions:
+
+ "Identify PATTERNS"
+ "Make INFERENCES"
+ "Predict based on trends" +
+
+
+ + +
+

📚 RAG

+ +
+
⚠️ Facts Provided:
+
Only 1-2 facts (keyword match)
+ "neon" ≠ "bright", "colorful", etc.
+
+ +
+
❌ Pattern Analysis:
+
None - no relationship detection
+
+ +
+
❌ Novelty Signal:
+
None - no familiarity indicator
+
+ +
+
⚠️ Instructions:
+
+ "ONLY use retrieved facts"
+ "If not covered, say so"
+ No inference allowed +
+
+
+
+
+""" + +ARCHITECTURE_SUMMARY_MD = """ +--- + +## Why This Architecture Matters + +### The Learning Advantage + +| Aspect | Neural Memory | RAG | +|--------|---------------|-----| +| **Storage** | Fixed neural weights (~250K params) | Growing document store | +| **Learning** | Yes - weights update per observation | No - just stores text | +| **Retrieval** | Not needed - patterns in weights | Required - keyword matching | +| **Inference** | Can generalize to novel queries | Limited to direct matches | +| **Memory Size** | Constant (doesn't grow) | Linear growth with data | + +### When Neural Memory Wins + +The architecture shines when: +1. **Pattern Recognition Required** - "Carlos likes X, dislikes Y" → predict for Z +2. **Novel Queries** - Question keywords don't match stored facts +3. **Holistic Reasoning** - Answer requires synthesizing multiple facts +4. **Bounded Memory** - Can't afford growing storage + +### When RAG Might Be Better + +RAG is simpler when: +1. **Exact Retrieval** - "What did the document say about X?" +2. **Large Corpus** - Millions of documents to search +3. **No Patterns** - Facts are independent, not related +4. **Transparency** - Need to cite exact source documents + +--- + +## Technical Implementation Details + +### Neural Memory Architecture + +``` +Input Text + │ + ▼ +┌─────────────────────────────────────────────┐ +│ _encode_text(text) │ +│ ┌─────────────────────────────────────────┐ │ +│ │ 1. Convert to ASCII ordinals │ │ +│ │ 2. Pad/truncate to max_seq_len (64) │ │ +│ │ 3. Project to dimension (256) │ │ +│ │ 4. Output: Tensor [1, 64, 256] │ │ +│ └─────────────────────────────────────────┘ │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ memory_net (nn.Sequential) │ +│ ┌─────────────────────────────────────────┐ │ +│ │ Linear(256 → 1024) │ │ +│ │ GELU activation │ │ +│ │ LayerNorm(1024) │ │ +│ │ Linear(1024 → 256) │ │ +│ └─────────────────────────────────────────┘ │ +│ Total: ~262K parameters │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ _compute_surprise_tensor(input, output) │ +│ ┌─────────────────────────────────────────┐ │ +│ │ loss = MSE(output, target) │ │ +│ │ surprise = sigmoid(loss) scaled to 0-1 │ │ +│ └─────────────────────────────────────────┘ │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ _update_weights(loss) [IF learn=True] │ +│ ┌─────────────────────────────────────────┐ │ +│ │ grads = torch.autograd.grad(loss, θ) │ │ +│ │ for each (param, grad): │ │ +│ │ param -= learning_rate × grad │ │ +│ └─────────────────────────────────────────┘ │ +│ ⚡ This is the key innovation! │ +└─────────────────────────────────────────────┘ +``` + +### RAG Architecture (Simplified for Demo) + +``` +Input Text + │ + ▼ +┌─────────────────────────────────────────────┐ +│ knowledge_base.append({"fact": text, ...}) │ +│ Simple list storage - no transformation │ +└─────────────────────────────────────────────┘ + +Query + │ + ▼ +┌─────────────────────────────────────────────┐ +│ Keyword Overlap Scoring │ +│ ┌─────────────────────────────────────────┐ │ +│ │ question_words = set(query.split()) │ │ +│ │ for fact in knowledge_base: │ │ +│ │ fact_words = set(fact.split()) │ │ +│ │ score = len(question_words ∩ fact_ │ │ +│ │ words) │ │ +│ └─────────────────────────────────────────┘ │ +└─────────────────────────────────────────────┘ + │ + ▼ +┌─────────────────────────────────────────────┐ +│ Top-K Selection (K=2 in our demo) │ +│ Return facts with highest overlap scores │ +└─────────────────────────────────────────────┘ +``` + +--- + +*These diagrams represent the actual implementation in this demo. The code is open source.* +""" + ABOUT_MD = """ ## About This Project @@ -1078,7 +1612,26 @@ def restore(name: str) -> str: outputs=[comparison_summary, tsne_plot, neural_state_plot, kb_plot] ) - # TAB 2: Live Demo (original) + # TAB 2: How It Works (Architecture Diagrams) + with gr.TabItem("How It Works"): + gr.Markdown(ARCHITECTURE_INTRO_MD) + + # Neural Memory Diagram + gr.HTML(NEURAL_MEMORY_DIAGRAM_HTML) + + # RAG Diagram + gr.HTML(RAG_DIAGRAM_HTML) + + # LLM Integration Explanation + gr.Markdown(LLM_INTEGRATION_MD) + + # Side-by-side comparison table + gr.HTML(COMPARISON_TABLE_HTML) + + # Architecture Summary + gr.Markdown(ARCHITECTURE_SUMMARY_MD) + + # TAB 3: Neural Memory Playground (original Live Demo) with gr.TabItem("Neural Memory Playground"): gr.Markdown("### Watch Real Neural Learning") @@ -1124,11 +1677,11 @@ def restore(name: str) -> str: reset_output = gr.Markdown() reset_btn.click(reset_memory, outputs=[reset_output]) - # TAB 2: Docker Integration + # TAB 4: Docker Integration with gr.TabItem("Docker Integration"): gr.Markdown(DOCKER_INTEGRATION_MD) - # TAB 3: About + # TAB 5: About with gr.TabItem("About"): gr.Markdown(ABOUT_MD)