| import os | |
| import sys | |
| import time | |
| import json | |
| import argparse | |
| from typing import Dict, List, Optional, Any | |
| from loguru import logger | |
| import torch | |
| import numpy as np | |
| sys.path.append(os.path.join(os.path.dirname(__file__), "src")) | |
| from src.core.memory_agent import MemoryAwareAgent | |
| from src.core.knowledge_api import MemoryEfficientKnowledgeAPI | |
| from src.neural.memory_efficient_nn import ( | |
| MemoryAwareNeuralNetwork, | |
| create_memory_efficient_model, | |
| ) | |
| from src.agents.memory_planner import MemoryPlannerAgent | |
| from src.visualization.memory_visualization import MemoryVisualizationSuite | |
| from src.config.config import load_config, DEFAULT_SYSTEM_CONFIG | |
| class MemoryAwareAISystem: | |
| def __init__(self, config_path: Optional[str] = None): | |
| self.config = load_config(config_path) | |
| self._setup_logging() | |
| self.memory_agent = MemoryAwareAgent( | |
| name="Sarah's Memory Optimizer", | |
| cache_size=self.config.l1_cache_size, | |
| enable_profiling=self.config.enable_profiling, | |
| ) | |
| self.knowledge_api = MemoryEfficientKnowledgeAPI( | |
| agent=self.memory_agent, enable_graph_optimization=True | |
| ) | |
| self.planner_agent = MemoryPlannerAgent( | |
| memory_agent=self.memory_agent, knowledge_api=self.knowledge_api | |
| ) | |
| self.neural_networks = self._initialize_neural_networks() | |
| self.visualization = MemoryVisualizationSuite(output_dir=self.config.plots_dir) | |
| self.system_start_time = time.time() | |
| self.demonstration_results = [] | |
| logger.info("Memory-Aware AI System initialized successfully") | |
| def _setup_logging(self): | |
| log_file = os.path.join(self.config.logs_dir, f"system_{int(time.time())}.log") | |
| os.makedirs(self.config.logs_dir, exist_ok=True) | |
| logger.add( | |
| log_file, | |
| level=self.config.log_level, | |
| format="{time:YYYY-MM-DD HH:mm:ss} | {level} | {name}:{function}:{line} | {message}", | |
| rotation="10 MB", | |
| retention="7 days", | |
| ) | |
| def _initialize_neural_networks(self) -> Dict[str, Any]: | |
| networks = {} | |
| reasoning_config = { | |
| "input_size": 256, | |
| "hidden_sizes": [512, 256, 128], | |
| "output_size": 64, | |
| "block_size": 64, | |
| "dropout_rate": 0.1, | |
| } | |
| networks["reasoning"] = MemoryAwareNeuralNetwork( | |
| config=reasoning_config, agent=self.memory_agent | |
| ) | |
| attention_config = {"d_model": 256, "n_heads": 8, "chunk_size": 128} | |
| networks["attention"] = create_memory_efficient_model( | |
| "attention", attention_config, self.memory_agent | |
| ) | |
| logger.info(f"Initialized {len(networks)} neural networks") | |
| return networks | |
| def demonstrate_memory_unaware_vs_aware(self, queries: List[str]) -> Dict[str, Any]: | |
| logger.info("Starting memory-unaware vs memory-aware demonstration") | |
| results = { | |
| "naive_approach": {}, | |
| "memory_aware_approach": {}, | |
| "performance_comparison": {}, | |
| } | |
| start_time = time.time() | |
| naive_results = self._naive_processing(queries) | |
| naive_time = time.time() - start_time | |
| results["naive_approach"] = { | |
| "execution_time": naive_time, | |
| "results": naive_results, | |
| "cache_hit_rate": 0.0, | |
| "memory_efficiency": 0.3, | |
| } | |
| start_time = time.time() | |
| aware_results = self._memory_aware_processing(queries) | |
| aware_time = time.time() - start_time | |
| results["memory_aware_approach"] = { | |
| "execution_time": aware_time, | |
| "results": aware_results, | |
| "cache_hit_rate": self.memory_agent.get_cache_hit_rate(), | |
| "memory_efficiency": self.memory_agent.get_memory_efficiency(), | |
| } | |
| results["performance_comparison"] = { | |
| "speed_improvement": (naive_time - aware_time) / naive_time * 100, | |
| "cache_hit_rate_improvement": results["memory_aware_approach"][ | |
| "cache_hit_rate" | |
| ] | |
| * 100, | |
| "memory_efficiency_improvement": ( | |
| results["memory_aware_approach"]["memory_efficiency"] | |
| - results["naive_approach"]["memory_efficiency"] | |
| ) | |
| * 100, | |
| } | |
| logger.info( | |
| f"Demonstration completed. Speed improvement: {results['performance_comparison']['speed_improvement']:.1f}%" | |
| ) | |
| return results | |
| def _naive_processing(self, queries: List[str]) -> List[str]: | |
| results = [] | |
| for i, query in enumerate(queries): | |
| logger.debug(f"Naive processing query {i+1}: {query}") | |
| entities = self.planner_agent._extract_entities(query) | |
| for entity in entities: | |
| entity_facts = [] | |
| for fact in self.knowledge_api.knowledge_graph: | |
| if fact.head == entity: | |
| entity_facts.append((fact.relation, fact.tail)) | |
| time.sleep(0.01) | |
| if entities: | |
| results.append(f"Found information about {', '.join(entities)}") | |
| else: | |
| results.append("No relevant entities found") | |
| return results | |
| def _memory_aware_processing(self, queries: List[str]) -> List[str]: | |
| results = [] | |
| for i, query in enumerate(queries): | |
| logger.debug(f"Memory-aware processing query {i+1}: {query}") | |
| plan = self.planner_agent.generate_execution_plan(query) | |
| execution_result = self.planner_agent.execute_plan(plan) | |
| results.append(execution_result.results) | |
| return results | |
| def demonstrate_neural_network_training( | |
| self, batch_size: int = 32 | |
| ) -> Dict[str, Any]: | |
| logger.info("Starting neural network training demonstration") | |
| X_random = torch.randn(batch_size, 256) | |
| X_sequential = torch.randn(batch_size, 256).sort(dim=1)[0] | |
| y = torch.randint(0, 10, (batch_size,)) | |
| criterion = torch.nn.CrossEntropyLoss() | |
| optimizer = torch.optim.Adam( | |
| self.neural_networks["reasoning"].parameters(), lr=0.001 | |
| ) | |
| results = { | |
| "random_access_training": {}, | |
| "sequential_access_training": {}, | |
| "comparison": {}, | |
| } | |
| logger.info("Training with random access pattern (cache-unfriendly)") | |
| random_losses = [] | |
| start_time = time.time() | |
| for epoch in range(5): | |
| loss = self.neural_networks["reasoning"].memory_efficient_training_step( | |
| X_random, y, optimizer, criterion | |
| ) | |
| random_losses.append(loss) | |
| logger.debug(f"Random access epoch {epoch+1}: Loss = {loss:.4f}") | |
| random_time = time.time() - start_time | |
| results["random_access_training"] = { | |
| "execution_time": random_time, | |
| "final_loss": random_losses[-1], | |
| "losses": random_losses, | |
| "cache_hit_rate": self.memory_agent.get_cache_hit_rate(), | |
| "memory_efficiency": self.memory_agent.get_memory_efficiency(), | |
| } | |
| self.memory_agent.reset() | |
| logger.info("Training with sequential access pattern (cache-friendly)") | |
| sequential_losses = [] | |
| start_time = time.time() | |
| for epoch in range(5): | |
| loss = self.neural_networks["reasoning"].memory_efficient_training_step( | |
| X_sequential, y, optimizer, criterion | |
| ) | |
| sequential_losses.append(loss) | |
| logger.debug(f"Sequential access epoch {epoch+1}: Loss = {loss:.4f}") | |
| sequential_time = time.time() - start_time | |
| results["sequential_access_training"] = { | |
| "execution_time": sequential_time, | |
| "final_loss": sequential_losses[-1], | |
| "losses": sequential_losses, | |
| "cache_hit_rate": self.memory_agent.get_cache_hit_rate(), | |
| "memory_efficiency": self.memory_agent.get_memory_efficiency(), | |
| } | |
| results["comparison"] = { | |
| "speed_improvement": (random_time - sequential_time) / random_time * 100, | |
| "cache_hit_rate_improvement": ( | |
| results["sequential_access_training"]["cache_hit_rate"] | |
| - results["random_access_training"]["cache_hit_rate"] | |
| ) | |
| * 100, | |
| "memory_efficiency_improvement": ( | |
| results["sequential_access_training"]["memory_efficiency"] | |
| - results["random_access_training"]["memory_efficiency"] | |
| ) | |
| * 100, | |
| } | |
| logger.info( | |
| f"Neural network training completed. Speed improvement: {results['comparison']['speed_improvement']:.1f}%" | |
| ) | |
| return results | |
| def run_interactive_demonstration(self, queries: List[str]) -> Dict[str, Any]: | |
| logger.info("Starting interactive demonstration") | |
| results = { | |
| "queries_processed": [], | |
| "system_performance": {}, | |
| "knowledge_graph_stats": {}, | |
| "neural_network_stats": {}, | |
| } | |
| for i, query in enumerate(queries): | |
| logger.info(f"Processing query {i+1}/{len(queries)}: {query}") | |
| analysis = self.planner_agent.complexity_analyzer.analyze_complexity(query) | |
| plan = self.planner_agent.generate_execution_plan(query) | |
| execution_result = self.planner_agent.execute_plan(plan) | |
| query_result = { | |
| "query": query, | |
| "complexity_score": analysis["complexity_score"], | |
| "strategy": analysis["strategy"], | |
| "execution_time": execution_result.performance["total_time"], | |
| "cache_hit_rate": execution_result.performance["cache_hit_rate"], | |
| "memory_efficiency": execution_result.performance["memory_efficiency"], | |
| "success": execution_result.success, | |
| "response": execution_result.results, | |
| } | |
| results["queries_processed"].append(query_result) | |
| logger.info( | |
| f"Query {i+1} completed: {execution_result.performance['total_time']:.3f}s, " | |
| f"Cache hit rate: {execution_result.performance['cache_hit_rate']:.2%}" | |
| ) | |
| results["system_performance"] = self.planner_agent.get_performance_summary() | |
| results["knowledge_graph_stats"] = self.knowledge_api.get_graph_statistics() | |
| results["neural_network_stats"] = { | |
| name: network.get_memory_usage() | |
| for name, network in self.neural_networks.items() | |
| } | |
| logger.info("Interactive demonstration completed") | |
| return results | |
| def generate_comprehensive_analysis(self) -> str: | |
| logger.info("Generating comprehensive analysis") | |
| report_path = self.visualization.generate_comprehensive_report( | |
| agent=self.memory_agent, | |
| knowledge_api=self.knowledge_api, | |
| planner=self.planner_agent, | |
| ) | |
| self._save_system_data() | |
| logger.info(f"Comprehensive analysis generated: {report_path}") | |
| return report_path | |
| def _save_system_data(self): | |
| timestamp = int(time.time()) | |
| self.memory_agent.save_memory_log( | |
| os.path.join(self.config.data_dir, f"memory_log_{timestamp}.json") | |
| ) | |
| self.knowledge_api.save_knowledge_graph( | |
| os.path.join(self.config.data_dir, f"knowledge_graph_{timestamp}.json") | |
| ) | |
| self.planner_agent.save_performance_data( | |
| os.path.join(self.config.data_dir, f"performance_data_{timestamp}.json") | |
| ) | |
| system_summary = { | |
| "system_start_time": self.system_start_time, | |
| "total_runtime": time.time() - self.system_start_time, | |
| "memory_agent_summary": self.memory_agent.memory_summary(), | |
| "knowledge_graph_stats": self.knowledge_api.get_graph_statistics(), | |
| "planner_performance": self.planner_agent.get_performance_summary(), | |
| "neural_network_stats": { | |
| name: network.get_memory_usage() | |
| for name, network in self.neural_networks.items() | |
| }, | |
| } | |
| with open( | |
| os.path.join(self.config.data_dir, f"system_summary_{timestamp}.json"), "w" | |
| ) as f: | |
| json.dump(system_summary, f, indent=2, default=str) | |
| logger.info("System data saved successfully") | |
| def run_complete_demonstration(self) -> Dict[str, Any]: | |
| logger.info("Starting complete memory-aware AI system demonstration") | |
| test_queries = [ | |
| "What is the access time of L1 Cache?", | |
| "How does SRAM relate to cache performance?", | |
| "What memory type is used in L1 Cache?", | |
| "Explain the relationship between cache miss and performance degradation", | |
| "What are the memory patterns of Transformer models?", | |
| "Compare the memory efficiency of CNN vs RNN architectures", | |
| "How does memory bandwidth limit model throughput?", | |
| "What optimization strategies improve cache locality?", | |
| ] | |
| demonstration_results = { | |
| "memory_comparison": self.demonstrate_memory_unaware_vs_aware( | |
| test_queries[:5] | |
| ), | |
| "neural_training": self.demonstrate_neural_network_training(), | |
| "interactive_demo": self.run_interactive_demonstration(test_queries), | |
| "system_analysis": {}, | |
| } | |
| report_path = self.generate_comprehensive_analysis() | |
| demonstration_results["system_analysis"]["report_path"] = report_path | |
| demonstration_results["system_analysis"]["summary"] = { | |
| "total_queries_processed": len(test_queries), | |
| "total_runtime": time.time() - self.system_start_time, | |
| "final_cache_hit_rate": self.memory_agent.get_cache_hit_rate(), | |
| "final_memory_efficiency": self.memory_agent.get_memory_efficiency(), | |
| "knowledge_facts": len(self.knowledge_api.knowledge_graph), | |
| "neural_networks": len(self.neural_networks), | |
| } | |
| logger.info("Complete demonstration finished successfully") | |
| return demonstration_results | |
| def main(): | |
| parser = argparse.ArgumentParser(description="Memory-Aware AI System Demonstration") | |
| parser.add_argument("--config", type=str, help="Path to configuration file") | |
| parser.add_argument( | |
| "--output-dir", type=str, default="results", help="Output directory" | |
| ) | |
| parser.add_argument("--verbose", action="store_true", help="Enable verbose logging") | |
| args = parser.parse_args() | |
| os.makedirs(args.output_dir, exist_ok=True) | |
| try: | |
| system = MemoryAwareAISystem(config_path=args.config) | |
| results = system.run_complete_demonstration() | |
| print("\n" + "=" * 70) | |
| print("MEMORY-AWARE AI SYSTEM DEMONSTRATION COMPLETED") | |
| print("=" * 70) | |
| summary = results["system_analysis"]["summary"] | |
| print(f"Total Queries Processed: {summary['total_queries_processed']}") | |
| print(f"Total Runtime: {summary['total_runtime']:.2f} seconds") | |
| print(f"Final Cache Hit Rate: {summary['final_cache_hit_rate']:.2%}") | |
| print(f"Final Memory Efficiency: {summary['final_memory_efficiency']:.2%}") | |
| print(f"Knowledge Facts: {summary['knowledge_facts']}") | |
| print(f"Neural Networks: {summary['neural_networks']}") | |
| print(f"\nComprehensive Report: {results['system_analysis']['report_path']}") | |
| print("=" * 70) | |
| except Exception as e: | |
| logger.error(f"System demonstration failed: {e}") | |
| raise | |
| if __name__ == "__main__": | |
| main() | |
Xet Storage Details
- Size:
- 15.8 kB
- Xet hash:
- 56dccc4c373de07579c9c403f0b9462f0540b67ed335bcc9583d691b56fef09f
·
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.