6300: Context Management¶
Module Overview¶
This module covers advanced context management techniques for RAG systems, including knowledge graphs, GraphRAG, and long-context architectures. You'll learn to structure and retrieve context beyond simple vector search.
Why This Matters:
- Structured knowledge improves retrieval accuracy
- Knowledge graphs capture relationships vector search misses
- Long-context models require careful context organization
- GraphRAG combines the best of structured and unstructured retrieval
Learning Objectives¶
After completing this module, you will be able to:
- Knowledge Graphs: Model entities and relationships with Neo4j
- GraphRAG: Combine knowledge graphs with vector retrieval
- Long-Context Architectures: Manage context windows effectively
- CAG (Context-Augmented Generation): Optimize context for generation
- Context Optimization: Structure and compress context efficiently
- Context Window Economics: Price the accuracy curve and allocate the window budget per query class
Module Contents¶
6301: Neo4j and Knowledge Graphs¶
Graph-Based Knowledge Representation
- Knowledge graph fundamentals
- Neo4j setup and the Cypher query language
- Building knowledge graphs from text
- GraphRAG: combining graph and vector retrieval
- Advanced: traversal and pattern matching
Experiments:
- Set up Neo4j database
- Extract entities from documents
- Build knowledge graph
- Query graph for context
6302: CAG and Long-Context Architectures¶
Context Window Optimization
- RAG vs CAG: when each wins
- Long-context models and their limits
- Context management strategies
- Hands-on implementation
- Optimization techniques
Experiments:
- Implement CAG pipeline
- Optimize context compression
- Build hierarchical retrieval
- Test long-context strategies
6305: LongLoRA, Ring Attention, and Context Distillation¶
Context Extension Training Methods
- The scaling wall: attention compute, activation memory, and the prompt tax
- Shifted sparse attention and the half-group shift's reachability walk
- Ring attention: exact sequence parallelism with blockwise online softmax
- The LongLoRA parameter ledger: LoRA plus embedding and norm layers
- Context distillation: the context moving into the weights
Experiments:
- Simulate S²-Attn reachability with and without the shift
- Verify ring attention equals full attention exactly
- Price the LoRA-only vs LoRA+ parameter ledger
- Train a context-distillation pair to a converged KL
6306: Context Window Economics¶
The Window as a Priced Allocation
- The accuracy curve: P(found) x q(w) peaking at 0.3707 and turning negative
- Effective versus advertised: the 27.6x gap behind the datasheet number
- Pricing both ledgers: the two-tier dollar card and 4201's 512 KB/token KV
- Sizing per query class: the routed split beating one-size by +0.1000
- The month campaign: max-window losing $43,250.00, routed winning
Experiments:
- Walk the marginal-accuracy table and locate the negative tail
- Fit the NoLiMa decay and derive the effective length at 95 percent of baseline
- Price the window walk in dollars, KV gigabytes, and accuracy per dollar
- Re-derive the routed allocation and verify the month ledger's dominance
6303: Neo4j Deployment Guide¶
Production Knowledge Graph Setup (Guide)
- Deployment targets and Docker deployment
- Initial configuration and performance tuning
- Backup strategy and monitoring
- Security hardening and troubleshooting
- Optional K3s deployment
Guide: guides/6303-Neo4j-Deployment-Guide.md
6304: GraphRAG Implementation¶
Knowledge-Graph Enhanced RAG (Guide)
- GraphRAG architecture
- Implementations 1ā2: graph construction, hybrid graph + vector RAG
- Implementations 3ā4: multi-hop reasoning, entity extraction with LLM
- Implementation 5: complete GraphRAG pipeline
- Production note: Microsoft GraphRAG
Guide: guides/6304-GraphRAG-Implementation.md
Prerequisites¶
Before starting this module, ensure you have:
- Module 6100: Vector Embeddings (basic retrieval)
- Module 6200: Retrieval Strategies (advanced retrieval)
- Python programming proficiency
- Basic understanding of graph databases
- Neo4j installation (or cloud access)
Review: PREREQUISITES.md for detailed requirements.
Assessment¶
Quiz¶
- Format: 20 multiple-choice questions
- Passing Score: 80% (16/20)
- Topics: Knowledge graphs, Neo4j, GraphRAG, long context
- Location: 6300: Context Window Management - Quiz
Practice Exercises¶
- Format: Context management projects
- Duration: 4 hours
- Topics:
- Build knowledge graph from documents
- Implement GraphRAG pipeline
- Optimize long-context retrieval
- Deploy Neo4j for production
- Location: 6300: Context Window Optimization - Practice
Related Modules¶
This module connects to:
- 6100: Vector Embeddings (unstructured retrieval)
- 6200: Retrieval Strategies (retrieval strategies)
- 6400: Vector Databases (data storage)
- 7400: Agent Memory Systems (agent memory systems)
Time Commitment¶
| Activity | Time |
|---|---|
| 6301: Neo4j and Knowledge Graphs | 5 hours |
| 6302: CAG and Long-Context Architectures | 5 hours |
| 6305: LongLoRA, Ring Attention, and Context Distillation | 3 hours |
| 6306: Context Window Economics | 3 hours |
| Guide (6303) | 3 hours |
| Guide (6304) | 4 hours |
| Quiz | 30 minutes |
| Practice | 4 hours |
| Total | 27.5 hours |
Resources¶
Essential Tools:
- Neo4j (graph database)
- Neo4j Python Driver
- LangChain GraphCypherQAChain
- LlamaIndex PropertyGraphIndex (KnowledgeGraphIndex is deprecated)
- GraphRAG (Microsoft)
Essential Papers:
- "GraphRAG: Enhancing Retrieval with Knowledge Graphs"
- "From Local to Global: A Graph RAG Approach"
- "Dense X Retrieval: What Retrieval Granularity"
Knowledge Graph vs Vector Search¶
| Aspect | Knowledge Graph | Vector Search |
|---|---|---|
| Relationships | āāāāā | āā |
| Exact Matching | āāāāā | āā |
| Semantic Understanding | āāā | āāāāā |
| Flexibility | āāā | āāāāā |
| Explanation | āāāāā | āā |
| Scalability | āāā | āāāāā |
GraphRAG Architecture¶
Document
ā
āāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāā
ā Entity ā Relationship ā
ā Extraction ā Extraction ā
āāāāāāāā¬āāāāāāāā“āāāāāāā¬āāāāāāāā
ā ā
Knowledge Graph (Neo4j)
ā
āāāāāāāāāāāāāāāā¬āāāāāāāāāāāāāāā
ā Graph ā Vector ā
ā Retrieval ā Retrieval ā
āāāāāāāā¬āāāāāāāā“āāāāāāā¬āāāāāāāā
ā ā
Hybrid Fusion
ā
Context Generation
Context Management Strategies¶
| Strategy | Description | Use Case |
|---|---|---|
| Flat Context | All chunks concatenated | Short documents |
| Hierarchical | Summary ā Detail | Long documents |
| Graph-Based | Entity ā Context | Complex relationships |
| Compressed | Context compression | Context window limits |
| Iterative | Retrieve ā Generate ā Retrieve | Multi-hop reasoning |
Neo4j Cypher Examples¶
Find related entities:
MATCH (e1:Entity {name: $entity})-[:RELATED_TO]-(e2:Entity)
RETURN e2.name, e2.type
LIMIT 10
Find path between entities:
MATCH path = shortestPath(
(e1:Entity {name: $entity1})-[*..5]-(e2:Entity {name: $entity2})
)
RETURN path
Long-Context Optimization¶
| Technique | Benefit | Complexity |
|---|---|---|
| Chunk Reordering | Group related content | Low |
| Context Compression | Fit more content | Medium |
| Hierarchical Summary | Multi-scale understanding | Medium |
| Recurrent Context | Infinite context | High |
Tips for Success¶
- Start with vectors: Add graphs for specific use cases
- Extract carefully: Entity quality matters
- Use hybrid approaches: Graph + vector is often best
- Optimize context length: Not too short, not too long
- Test on real queries: Synthetic benchmarks lie
Common Pitfalls¶
- Over-engineering: Simple queries don't need graphs
- Poor entity extraction: Garbage in, garbage out
- Ignoring structure: Documents have inherent structure
- Context stuffing: More ā better
- Skipping optimization: Raw retrieval needs tuning
When to Use Knowledge Graphs¶
| Scenario | Recommended Approach |
|---|---|
| FAQ content | Knowledge Graph |
| Technical documentation | Graph + Vector |
| General knowledge | Vector only |
| Relationship-heavy | Knowledge Graph |
| Multi-hop reasoning | Graph + Vector |
Context Window Management¶
Available Context: 128K tokens
Distribution Strategy:
āāā System Prompt: 1K tokens
āāā Retrieved Context: 100K tokens
ā āāā Graph entities: 20K
ā āāā Vector chunks: 80K
āāā Conversation History: 20K tokens
āāā Response Headroom: 7K tokens
Next Module: 6400: Vector Databases
Previous Module: 6200: Retrieval Strategies
Questions? Review the PREREQUISITES.md or check Phase 6 documentation.