Spaces:
Build error

AgenticSystem / app.py
Sky421's picture
Update app.py
8fc5582 verified
Raw History Blame Contribute Delete
102 kB
import torch import torch.nn as nn import torch.nn.functional as F from torch_geometric.nn import GCNConv, GAE, VGAE import gc import os import json import pickle import signal import sys import time import glob import uuid import statistics import gradio as gr from datetime import datetime from typing import Dict, List, Optional, Any, Union, Tuple, Iterator from dataclasses import dataclass from sentence_transformers import SentenceTransformer from transformers import AutoModelForCausalLM, BitsAndBytesConfig from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig from torch.optim import Adam # Constants MAX_ROUNDS = 3 CONFIDENCE_THRESHOLD = 3 JSON_DIRECTORY = './evaluation' #G-Designer Agents class BaseAgent(nn.Module): """Base class for all agents with learning capabilities.""" def __init__(self, role: str, base_model: str, plugins: List[str]): super().__init__() self.role = role self.base_model = base_model self.plugins = plugins self.state_history = [] self.learning_rate = 0.001 # Initialize neural components self.message_encoder = nn.LSTM(768, 256, bidirectional=True) self.state_encoder = nn.Linear(512, 256) self.decision_network = nn.Sequential( nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 64), nn.ReLU(), nn.Linear(64, 32) ) self.optimizer = Adam(self.parameters(), lr=self.learning_rate) def update_state(self, interaction: Dict): """Update agent's state based on interaction.""" self.state_history.append(interaction) if len(self.state_history) > 1000: # Limit history size self.state_history = self.state_history[-1000:] def encode_messages(self, messages: List[str]) -> torch.Tensor: """Encode incoming messages.""" message_embeddings = [] for msg in messages: embedding = self.sentence_transformer.encode(msg) message_embeddings.append(torch.tensor(embedding)) if message_embeddings: message_tensor = torch.stack(message_embeddings) encoded, _ = self.message_encoder(message_tensor.unsqueeze(0)) return encoded.mean(dim=1) # Average over sequence return torch.zeros(512) # Default empty embedding def learn_from_feedback(self, feedback: Dict): """Learn from feedback about agent's performance.""" raise NotImplementedError class PatternAnalystAgent(BaseAgent): """Specializes in analyzing patterns in ARC tasks.""" def __init__(self): super().__init__( role="Pattern Analyst", base_model="gpt-4", plugins=["grid_analyzer", "pattern_matcher"] ) # Pattern recognition components self.pattern_encoder = nn.Sequential( nn.Conv2d(1, 16, 3, padding=1), nn.ReLU(), nn.MaxPool2d(2), nn.Conv2d(16, 32, 3, padding=1), nn.ReLU(), nn.AdaptiveAvgPool2d((4, 4)) ) self.pattern_memory = {} def process(self, task_input: Dict, messages: List[str]) -> Dict: """Process task input and identify patterns.""" try: # Encode grid patterns grid_patterns = self._encode_grids(task_input['train']) # Encode messages from other agents message_encoding = self.encode_messages(messages) # Combine information combined_features = torch.cat([ grid_patterns.view(-1), message_encoding ]) # Generate pattern analysis pattern_description = self._analyze_patterns(combined_features) # Update state self.update_state({ 'input': task_input, 'patterns': pattern_description, 'timestamp': time.time() }) return { 'role': self.role, 'patterns': pattern_description, 'confidence': self._calculate_confidence() } except Exception as e: print(f"Error in pattern analysis: {str(e)}") return None def learn_from_feedback(self, feedback: Dict): """Learn from feedback about pattern analysis accuracy.""" try: if 'pattern_accuracy' not in feedback: return # Calculate loss accuracy = feedback['pattern_accuracy'] loss = 1 - accuracy # Backpropagate self.optimizer.zero_grad() loss_tensor = torch.tensor(loss, requires_grad=True) loss_tensor.backward() self.optimizer.step() # Update pattern memory if accuracy > 0.8: # Store successful patterns task_id = feedback['task_id'] self.pattern_memory[task_id] = { 'patterns': feedback['patterns'], 'accuracy': accuracy } except Exception as e: print(f"Error in pattern learning: {str(e)}") class GridTransformerAgent(BaseAgent): """Specializes in applying transformations to grids.""" def __init__(self): super().__init__( role="Grid Transformer", base_model="gpt-4", plugins=["grid_transformer", "rule_executor"] ) # Transformation components self.transform_network = nn.Sequential( nn.Linear(512, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 64) ) self.transformation_memory = {} def process(self, task_input: Dict, messages: List[str]) -> Dict: """Apply transformations based on identified patterns.""" try: # Extract patterns from analyst's messages patterns = self._extract_patterns(messages) # Encode current grid grid_encoding = self._encode_grid(task_input['test']) # Generate transformation transformation = self._generate_transformation( patterns, grid_encoding) # Apply transformation transformed_grid = self._apply_transformation( task_input['test'], transformation) # Update state self.update_state({ 'input': task_input, 'transformation': transformation, 'output': transformed_grid, 'timestamp': time.time() }) return { 'role': self.role, 'transformed_grid': transformed_grid, 'confidence': self._calculate_confidence() } except Exception as e: print(f"Error in grid transformation: {str(e)}") return None def learn_from_feedback(self, feedback: Dict): """Learn from feedback about transformation accuracy.""" try: if 'transformation_accuracy' not in feedback: return accuracy = feedback['transformation_accuracy'] loss = 1 - accuracy # Update transformation network self.optimizer.zero_grad() loss_tensor = torch.tensor(loss, requires_grad=True) loss_tensor.backward() self.optimizer.step() # Store successful transformations if accuracy > 0.8: task_id = feedback['task_id'] self.transformation_memory[task_id] = { 'transformation': feedback['transformation'], 'accuracy': accuracy } except Exception as e: print(f"Error in transformation learning: {str(e)}") class ValidatorAgent(BaseAgent): """Specializes in validating transformed grids.""" def __init__(self): super().__init__( role="Validator", base_model="gpt-4", plugins=["grid_validator", "consistency_checker"] ) # Validation components self.validation_network = nn.Sequential( nn.Linear(768, 256), nn.ReLU(), nn.Linear(256, 128), nn.ReLU(), nn.Linear(128, 1), nn.Sigmoid() ) self.validation_memory = {} def process(self, task_input: Dict, messages: List[str]) -> Dict: """Validate transformed grids.""" try: # Extract transformed grid transformed_grid = self._extract_grid(messages) # Validate grid validation_result = self._validate_grid( transformed_grid, task_input) # Check consistency consistency_score = self._check_consistency( transformed_grid, task_input['train']) # Update state self.update_state({ 'input': task_input, 'validation': validation_result, 'consistency': consistency_score, 'timestamp': time.time() }) return { 'role': self.role, 'is_valid': validation_result, 'consistency_score': consistency_score, 'confidence': self._calculate_confidence() } except Exception as e: print(f"Error in validation: {str(e)}") return None def learn_from_feedback(self, feedback: Dict): """Learn from feedback about validation accuracy.""" try: if 'validation_accuracy' not in feedback: return accuracy = feedback['validation_accuracy'] loss = 1 - accuracy # Update validation network self.optimizer.zero_grad() loss_tensor = torch.tensor(loss, requires_grad=True) loss_tensor.backward() self.optimizer.step() # Store successful validations if accuracy > 0.8: task_id = feedback['task_id'] self.validation_memory[task_id] = { 'validation_criteria': feedback['validation_criteria'], 'accuracy': accuracy } except Exception as e: print(f"Error in validation learning: {str(e)}") class ARCDataLoader: """Handles loading and processing of ARC task data.""" JSON_directory='./evaluation' def __init__(self, base_path: str = JSON_directory): self.base_path = base_path if not os.path.exists(base_path): raise ValueError(f"Base path does not exist: {base_path}") if not os.access(base_path, os.R_OK): raise ValueError(f"No read permission for base path: {base_path}") def load_task(self, file_path: str) -> Optional[Dict]: """Load a single ARC task from JSON file.""" try: if not file_path.endswith('.json'): return None if not os.path.exists(file_path): print(f"File not found: {file_path}") return None if not os.access(file_path, os.R_OK): print(f"No read permission for file: {file_path}") return None with open(file_path, 'r') as f: data = json.load(f) # Validate the expected structure if not isinstance(data, dict): print(f"Invalid data structure in {file_path}: not a dictionary") return None if 'train' not in data or 'test' not in data: print(f"Invalid data structure in {file_path}: missing train or test data") return None # Validate that train and test are lists if not isinstance(data['train'], list) or not isinstance(data['test'], list): print(f"Invalid data structure in {file_path}: train or test is not a list") return None return data except json.JSONDecodeError: print(f"Invalid JSON format in file: {file_path}") return None except Exception as e: print(f"Unexpected error reading {file_path}: {str(e)}") return None def load_all_tasks(self) -> List[Dict]: """Load all ARC tasks from the evaluation directory.""" tasks = [] for filename in os.listdir(self.base_path): if not filename.endswith('.json'): continue file_path = os.path.join(self.base_path, filename) task = self.load_task(file_path) if task is not None: tasks.append({ 'filename': filename, 'data': task }) if not tasks: print(f"Warning: No valid JSON files found in {self.base_path}") return tasks def validate_grid(self, grid: List[List[int]]) -> bool: """Validate a grid according to ARC specifications.""" if not grid or not grid[0]: return False rows, cols = len(grid), len(grid[0]) # Check size constraints if rows < 1 or rows > 30 or cols < 1 or cols > 30: return False # Check all rows have same length and valid values return all( len(row) == cols and all(0 <= val <= 9 for val in row) for row in grid ) def validate_task_format(self, task: Dict) -> bool: """Validate that a task follows ARC format specifications.""" try: # Verify required fields if not isinstance(task.get('train'), list) or not isinstance(task.get('test'), list): return False # Validate all pairs for pair in task['train'] + task['test']: if not isinstance(pair, dict): return False if 'input' not in pair or 'output' not in pair: return False if not self.validate_grid(pair['input']) or not self.validate_grid(pair['output']): return False return True except Exception: return False class ARCTaskConverter: """Converts ARC tasks into format suitable for agent system.""" def __init__(self): self.cached_descriptions = {} def grid_to_text(self, grid: List[List[int]]) -> str: """Convert a grid to a text description.""" rows = len(grid) cols = len(grid[0]) if rows > 0 else 0 return f"Grid of size {rows}x{cols} with values:\n" + \ "\n".join([" ".join(map(str, row)) for row in grid]) def analyze_pattern(self, input_grid: List[List[int]], output_grid: List[List[int]]) -> str: """Analyze the transformation pattern between input and output grids.""" in_rows, in_cols = len(input_grid), len(input_grid[0]) if input_grid else 0 out_rows, out_cols = len(output_grid), len(output_grid[0]) if output_grid else 0 pattern = f"Transform {in_rows}x{in_cols} grid into {out_rows}x{out_cols} grid.\n" # Detect basic patterns if out_rows == in_rows * 3 and out_cols == in_cols * 3: pattern += "Pattern appears to involve 3x3 expansion of the input." elif all(all(val in [0, 1] for val in row) for row in input_grid): pattern += "Binary grid transformation task." return pattern def create_task_description(self, task: Dict) -> str: """Create a natural language description of the ARC task.""" train_pairs = task.get('train', []) test_pairs = task.get('test', []) # Create a description including both training and testing pairs description = "ARC reasoning task with the following examples:\n\n" for idx, pair in enumerate(train_pairs): input_desc = self.grid_to_text(pair['input']) output_desc = self.grid_to_text(pair['output']) pattern = self.analyze_pattern(pair['input'], pair['output']) description += f"Training Example {idx + 1}:\nInput:\n{input_desc}\n" description += f"Output:\n{output_desc}\nPattern: {pattern}\n\n" for idx, pair in enumerate(test_pairs): input_desc = self.grid_to_text(pair['input']) description += f"Test Example {idx + 1}:\nInput:\n{input_desc}\nExpected output needs to be inferred.\n\n" return description class ARCEvaluator: def __init__(self, max_trials: int = 3): self.max_trials = max_trials self.results = {} self.rounds = {} # Track rounds per task def evaluate_output(self, predicted: List[List[int]], actual: List[List[int]]) -> bool: if not predicted or not actual: return False if len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]): return False return all(predicted[i][j] == actual[i][j] for i in range(len(predicted)) for j in range(len(predicted[0]))) def record_result(self, task_id: str, trial: int, success: bool): if task_id not in self.results: self.results[task_id] = {'trials': [], 'success': False} self.rounds[task_id] = 0 self.results[task_id]['trials'].append(success) self.rounds[task_id] += 1 if success: self.results[task_id]['success'] = True def get_summary(self) -> Dict: total_tasks = len(self.results) if total_tasks == 0: return { 'total_tasks': 0, 'successful_tasks': 0, 'success_rate': 0.0, 'average_trials_to_success': 0.0, 'rounds': 0 } successful_tasks = sum(1 for result in self.results.values() if result['success']) avg_rounds = sum(self.rounds.values()) / total_tasks if total_tasks > 0 else 0 trials_to_success = [] for result in self.results.values(): if result['success']: trial_num = next(i + 1 for i, success in enumerate(result['trials']) if success) trials_to_success.append(trial_num) avg_trials = statistics.mean(trials_to_success) if trials_to_success else 0 return { 'total_tasks': total_tasks, 'successful_tasks': successful_tasks, 'success_rate': successful_tasks / total_tasks, 'average_trials_to_success': avg_trials, 'rounds': avg_rounds } class GPUMemoryManager: def __init__(self): self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") # Simplified CUDA allocation config os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128' # Set CUDA_LAUNCH_BLOCKING for debugging os.environ['CUDA_LAUNCH_BLOCKING'] = '1' if torch.cuda.is_available(): # More conservative memory fraction torch.cuda.set_per_process_memory_fraction(0.7) self.force_memory_release() def optimize_memory(self): gc.collect() if torch.cuda.is_available(): torch.cuda.empty_cache() torch.cuda.synchronize() def force_memory_release(self): if torch.cuda.is_available(): torch.cuda.empty_cache() gc.collect() torch.cuda.synchronize() torch.cuda.reset_peak_memory_stats() # Clear CUDA cache more aggressively with torch.cuda.device('cuda'): torch.cuda.empty_cache() torch.cuda.ipc_collect() def check_memory(self, required_memory_mb: int = 1000) -> bool: if not torch.cuda.is_available(): return True try: with torch.cuda.device('cuda'): total = torch.cuda.get_device_properties(0).total_memory allocated = torch.cuda.memory_allocated() free_memory = (total - allocated) / (1024 * 1024) # Convert to MB return free_memory >= required_memory_mb except Exception: return False def get_memory_stats(self) -> Dict[str, float]: if not torch.cuda.is_available(): return {"allocated": 0, "cached": 0, "max_allocated": 0} return { "allocated": torch.cuda.memory_allocated() / (1024 * 1024), "cached": torch.cuda.memory_reserved() / (1024 * 1024), "max_allocated": torch.cuda.max_memory_allocated() / (1024 * 1024) } class RoleLearningManager: def __init__(self, checkpoint_dir: str = "./role_checkpoints"): self.checkpoint_dir = checkpoint_dir os.makedirs(checkpoint_dir, exist_ok=True) self.role_experiences = { 'boss': [], 'agent1': [], 'agent2': [], 'agent3': [], 'summarizer': [] } self.role_metrics = {role: {'success_rate': 0.0, 'total_tasks': 0} for role in self.role_experiences.keys()} self.load_experiences() def save_experience(self, role: str, experience: Dict): self.role_experiences[role].append(experience) self._update_metrics(role, experience['success']) self.save_checkpoint(role) def _update_metrics(self, role: str, success: bool): metrics = self.role_metrics[role] metrics['total_tasks'] += 1 metrics['success_rate'] = ( (metrics['success_rate'] * (metrics['total_tasks'] - 1) + int(success)) / metrics['total_tasks'] ) def get_role_experience(self, role: str, n_recent: int = 5) -> List[Dict]: experiences = self.role_experiences.get(role, []) return experiences[-n_recent:] if experiences else [] def save_checkpoint(self, role: str): checkpoint_path = os.path.join(self.checkpoint_dir, f"{role}_experience.pkl") metrics_path = os.path.join(self.checkpoint_dir, f"{role}_metrics.json") with open(checkpoint_path, 'wb') as f: pickle.dump(self.role_experiences[role], f) with open(metrics_path, 'w') as f: json.dump(self.role_metrics[role], f) def load_experiences(self): for role in self.role_experiences.keys(): exp_path = os.path.join(self.checkpoint_dir, f"{role}_experience.pkl") metrics_path = os.path.join(self.checkpoint_dir, f"{role}_metrics.json") if os.path.exists(exp_path): with open(exp_path, 'rb') as f: self.role_experiences[role] = pickle.load(f) if os.path.exists(metrics_path): with open(metrics_path, 'r') as f: self.role_metrics[role] = json.load(f) class NodeEncoder(nn.Module): def __init__(self, input_dim): super().__init__() self.encoder = SentenceTransformer('all-MiniLM-L6-v2') self.linear = nn.Linear(384, input_dim) def forward(self, text: str) -> torch.Tensor: with torch.no_grad(): embeddings = self.encoder.encode(text, convert_to_tensor=True) return self.linear(embeddings) class GCNEncoder(nn.Module): def __init__(self, input_dim: int, hidden_dim: int, latent_dim: int): super().__init__() self.gcn1 = GCNConv(input_dim, hidden_dim) self.gcn2 = GCNConv(hidden_dim, latent_dim) def forward(self, x: torch.Tensor, edge_index: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]: h = F.relu(self.gcn1(x, edge_index)) h = F.dropout(h, p=0.5, training=self.training) mu = self.gcn2(h, edge_index) log_std = self.gcn2(h, edge_index) return mu, log_std class GraphDecoder(nn.Module): def __init__(self, latent_dim: int, hidden_dim: int): super().__init__() self.ffn = nn.Sequential( nn.Linear(latent_dim * 3, hidden_dim), nn.ReLU(), nn.Linear(hidden_dim, 1) ) def forward(self, z: torch.Tensor, task_embed: torch.Tensor) -> torch.Tensor: N = z.size(0) device = z.device rows = z.repeat_interleave(N, dim=0) cols = z.repeat(N, 1) tasks = task_embed.repeat(N * N, 1) edge_inputs = torch.cat([rows, cols, tasks], dim=1) edge_logits = self.ffn(edge_inputs).view(N, N) return torch.sigmoid(edge_logits) class VGAE(torch.nn.Module): def __init__(self, encoder, decoder): super().__init__() self.encoder = encoder self.decoder = decoder def forward(self, x): z = self.encoder(x) return self.decoder(z) class AgentEncoder(torch.nn.Module): #Set the torch with the self learning module. """Encodes agent properties into embeddings.""" def __init__(self, input_dim): #def __init__(self, input_dim=768, hidden_dim=256, output_dim=128): super().__init__() self.encoder = torch.nn.Linear(input_dim, 128) #self.encoder = nn.Sequential( #Most likely won't do anything for the user query. May need to be turned on for dataset evaluation. ## nn.Linear(input_dim, hidden_dim), # nn.ReLU(), # nn.Linear(hidden_dim, output_dim) # ) def forward(self, x): return self.encoder(x) class GraphEncoder(torch.nn.Module): def __init__(self, input_dim): super().__init__() self.encoder = torch.nn.Linear(input_dim, 128) def forward(self, x): return F.relu(self.encoder(x)) class GraphDecoder(torch.nn.Module): def __init__(self, hidden_dim): super().__init__() self.decoder = torch.nn.Linear(hidden_dim, hidden_dim) def forward(self, z): return torch.sigmoid(self.decoder(z)) class GDesigner: """Graph-based Designer for Multi-agent Communication""" def __init__(self, num_agents=3, input_dim=768, roles=None): self.num_agents = num_agents self.roles = roles if roles else {} self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') self.checkpoint_dir = "checkpoints" # Initialize components self.agent_encoder = AgentEncoder(input_dim).to(self.device) self.graph_encoder = GraphEncoder(input_dim).to(self.device) self.graph_decoder = GraphDecoder(128).to(self.device) # Initialize VGAE self.vgae = VGAE(self.graph_encoder, self.graph_decoder) # Optimization self.optimizer = Adam(list(self.vgae.parameters()) + list(self.agent_encoder.parameters()), lr=0.001) # Learning history self.learning_history = {} self.current_utility = -float('inf') self.performance_history = {} # Initialize communication graph self.communication_graph = self._initialize_graph() # Task-specific components self.task_embeddings = {} self.anchor_topologies = {} self.experience_buffer = [] # Initialize experience buffer def _initialize_graph(self): """Initialize the communication graph with basic structure.""" num_nodes = self.num_agents + 1 # +1 for task-specific virtual node return torch.zeros((num_nodes, num_nodes), device=self.device) def update_roles(self, new_roles): """Update agent roles dynamically""" self.roles = new_roles self.num_agents = len(new_roles) self.communication_graph = self._initialize_graph() def _initialize_graph(self): """Initialize the communication graph with basic structure.""" num_nodes = self.num_agents + 1 # +1 for task-specific virtual node return torch.zeros((num_nodes, num_nodes), device=self.device) def encode_agent(self, agent_data): """Encode agent properties into embeddings.""" # Convert agent properties to tensor agent_tensor = self._prepare_agent_tensor(agent_data) return self.agent_encoder(agent_tensor) def _prepare_agent_tensor(self, agent_data): """Convert agent properties to tensor format.""" # Combine agent properties into a single vector properties = [ agent_data['base_model'], agent_data['role'], agent_data['state'], agent_data['plugins'] ] # Use sentence transformer to get embeddings embeddings = self.sentence_transformer.encode(properties) return torch.tensor(embeddings, device=self.device) def update_graph(self, task_id: str, agents_data: List[Dict], performance_metrics: Dict): """Update communication graph based on task performance.""" try: # Encode agents agent_embeddings = [self.encode_agent(agent) for agent in agents_data] agent_embeddings = torch.stack(agent_embeddings) # Add task-specific virtual node task_embedding = self.task_embeddings.get(task_id, torch.randn(768, device=self.device)) node_embeddings = torch.cat([agent_embeddings, task_embedding.unsqueeze(0)]) # Get anchor topology anchor_topology = self.anchor_topologies.get(task_id, self._initialize_graph()) # Optimize graph structure self.optimizer.zero_grad() # VGAE forward pass mu, logvar = self.graph_encoder(node_embeddings, self.communication_graph) z = self.vgae.reparametrize(mu, logvar) reconstructed_graph = self.graph_decoder(z) # Calculate losses recon_loss = F.binary_cross_entropy(reconstructed_graph, self.communication_graph) kl_loss = 0.01 * torch.mean(torch.sum( torch.exp(logvar) + mu**2 - 1 - logvar, dim=1)) # Add sparsity constraint sparsity_loss = 0.1 * torch.norm(reconstructed_graph, p=1) # Add anchor topology constraint anchor_loss = 0.05 * F.mse_loss(reconstructed_graph, anchor_topology) # Total loss loss = recon_loss + kl_loss + sparsity_loss + anchor_loss # Backward pass and optimization loss.backward() self.optimizer.step() # Update communication graph if improved utility = self._calculate_utility(performance_metrics) if utility > self.current_utility: self.communication_graph = reconstructed_graph.detach() self.current_utility = utility # Store learning history self.learning_history[task_id] = { 'utility': utility.item(), 'loss': loss.item(), 'graph_structure': self.communication_graph.clone(), 'performance': performance_metrics } except Exception as e: print(f"Error updating graph: {str(e)}") class TaskAdapter: """Handles task-specific adaptation of the communication graph.""" def __init__(self, hidden_dim=256): self.hidden_dim = hidden_dim self.task_memory = {} self.sentence_transformer = SentenceTransformer('all-MiniLM-L6-v2') def create_task_embedding(self, task: Dict) -> torch.Tensor: """Create task-specific embedding.""" # Extract task features train_examples = self._format_examples(task['train']) test_input = self._format_examples([task['test'][0]]) # First test case # Create task description task_desc = f"Task with {len(task['train'])} training examples. " task_desc += f"Input grid size: {len(task['test'][0]['input'])}x{len(task['test'][0]['input'][0])}. " # Get embedding embedding = self.sentence_transformer.encode(task_desc) return torch.tensor(embedding) def generate_anchor_topology(self, task: Dict, agents: List[str]) -> torch.Tensor: """Generate initial anchor topology based on task type.""" num_agents = len(agents) topology = torch.zeros((num_agents, num_agents)) # Analyze task type and create appropriate topology if self._is_pattern_recognition_task(task): # Chain topology: analyzer -> transformer -> validator for i in range(num_agents - 1): topology[i][i + 1] = 1 else: # Fully connected for complex tasks topology.fill_(1) topology.fill_diagonal_(0) return topology def _is_pattern_recognition_task(self, task: Dict) -> bool: """Determine if task is pattern recognition based.""" try: # Check if all grids have same dimensions input_dims = set() output_dims = set() for example in task['train'] + task['test']: input_dims.add((len(example['input']), len(example['input'][0]))) output_dims.add((len(example['output']), len(example['output'][0]))) return len(input_dims) == 1 and len(output_dims) == 1 except: return False class CommunicationProtocol: """Manages communication between agents.""" def __init__(self, max_rounds=3): self.max_rounds = max_rounds self.message_history = {} self.execution_order = [] def optimize_execution_order(self, graph: torch.Tensor) -> List[int]: """Determine optimal execution order based on graph structure.""" num_agents = graph.shape[0] dependencies = {i: set() for i in range(num_agents)} # Build dependency graph for i in range(num_agents): for j in range(num_agents): if graph[i][j] > 0.5: # Edge exists dependencies[j].add(i) # Topological sort visited = set() temp = set() order = [] def visit(node): if node in temp: raise ValueError("Cycle detected in agent dependencies") if node in visited: return temp.add(node) for dep in dependencies[node]: visit(dep) temp.remove(node) visited.add(node) order.append(node) for node in range(num_agents): if node not in visited: visit(node) return order[::-1] # Reverse for correct execution order def execute_round(self, agents: List[Any], graph: torch.Tensor, task_input: Any) -> Dict: """Execute one round of inter-agent communication.""" try: # Get execution order execution_order = self.optimize_execution_order(graph) self.execution_order = execution_order # Initialize message storage round_messages = {i: [] for i in range(len(agents))} # Execute agents in order for agent_idx in execution_order: # Collect incoming messages incoming_messages = [] for other_idx in range(len(agents)): if graph[other_idx][agent_idx] > 0.5: incoming_messages.extend(round_messages[other_idx]) # Execute agent agent_output = agents[agent_idx].process( task_input, incoming_messages ) # Store messages round_messages[agent_idx].append(agent_output) return round_messages except Exception as e: print(f"Error in communication round: {str(e)}") return {} def aggregate_results(self, round_messages: Dict, aggregation_type: str = 'majority') -> Any: """Aggregate results from all agents.""" try: if aggregation_type == 'majority': # Collect all predictions predictions = [] for agent_messages in round_messages.values(): if agent_messages: predictions.append(agent_messages[-1]) # Return most common prediction if predictions: return max(set(predictions), key=predictions.count) elif aggregation_type == 'last': # Return last agent's output last_agent = self.execution_order[-1] if round_messages[last_agent]: return round_messages[last_agent][-1] return None except Exception as e: print(f"Error in result aggregation: {str(e)}") return None def learn_from_experience(self, task_description: str, agents: List[Any], success: bool, execution_time: float, feedback: Dict): experience = { 'task': task_description, 'agents': [agent.to_dict() for agent in agents], 'success': success, 'execution_time': execution_time, 'feedback': feedback, 'topology': self.last_topology.clone() if hasattr(self, 'last_topology') else None } self.experience_buffer.append(experience) self.update_model_from_experience() def save_checkpoint(self): timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") checkpoint_path = os.path.join(self.checkpoint_dir, f"gdesigner_checkpoint_{timestamp}") cpu_state_dict = {k: v.cpu() for k, v in self.state_dict().items()} cpu_optimizer_state = {k: v.cpu() if isinstance(v, torch.Tensor) else v for k, v in self.optimizer.state_dict().items()} torch.save({ 'model_state_dict': cpu_state_dict, 'optimizer_state_dict': cpu_optimizer_state, 'performance_history': self.performance_history, }, f"{checkpoint_path}_model.pt") with open(f"{checkpoint_path}_experiences.pkl", 'wb') as f: pickle.dump(self.experience_buffer, f) def load_checkpoint(self): try: checkpoints = [f for f in os.listdir(self.checkpoint_dir) if f.endswith('_model.pt')] if not checkpoints: return latest_checkpoint = max(checkpoints) checkpoint_base = latest_checkpoint.replace('_model.pt', '') checkpoint = torch.load( os.path.join(self.checkpoint_dir, latest_checkpoint), map_location=self.device ) self.load_state_dict(checkpoint['model_state_dict']) self.optimizer.load_state_dict(checkpoint['optimizer_state_dict']) self.performance_history = checkpoint['performance_history'] with open(os.path.join(self.checkpoint_dir, f"{checkpoint_base}_experiences.pkl"), 'rb') as f: self.experience_buffer = pickle.load(f) except Exception as e: print(f"Error loading checkpoint: {str(e)}") self.experience_buffer = [] self.performance_history = {} class DynamicLLM: def __init__(self): self.model_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised" self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu") self.tokenizer = AutoTokenizer.from_pretrained(self.model_name) self.model = self._initialize_model() def _initialize_model(self): config = AutoConfig.from_pretrained(self.model_name) model = AutoModelForCausalLM.from_pretrained( self.model_name, config=config, device_map='auto', torch_dtype=torch.float16 ) return model def generate_response(self, prompt: str, role: str = None) -> str: try: inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device) outputs = self.model.generate( **inputs, max_length=512, temperature=0.7, do_sample=True ) return self.tokenizer.decode(outputs[0], skip_special_tokens=True) except Exception as e: print(f"Error generating response: {str(e)}") return None def generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]: """Generate a prediction for a test input using the multi-agent system.""" try: # Create more specific task description task_description = ( "Analyze these training examples and predict the output for the test input.\n" "Rules:\n" "1. Only use numbers 0-9\n" "2. Maintain grid structure\n" "3. Look for consistent patterns between input and output\n\n" "Training Examples:\n" ) # Add formatted training examples for idx, pair in enumerate(train_pairs, 1): task_description += f"\nExample {idx}:\n" task_description += "Input:\n" task_description += grid_to_string(pair['input']) + "\n" task_description += "Output:\n" task_description += grid_to_string(pair['output']) + "\n" # Add test input task_description += "\nTest Input:\n" task_description += grid_to_string(test_input) # Initialize agents with more specific roles agent_specs = [ { "role": "Pattern Analyst", "specialty": "grid_analysis", "context": { "task": "Identify the exact transformation pattern from input to output grids", "trial": trial + 1, "examples": train_pairs } }, { "role": "Grid Transformer", "specialty": "transformation", "context": { "task": "Apply the identified pattern to generate the output grid", "trial": trial + 1, "test_input": test_input } }, { "role": "Validator", "specialty": "validation", "context": { "task": "Verify the generated grid follows the pattern and constraints", "trial": trial + 1, "valid_values": list(range(10)) } } ] # Execute the prediction pipeline with better error handling pattern_analysis = None transformation_result = None validation_result = None try: pattern_analysis = dynamic_mas.execute_agent_query( task_description, agent_specs[0], context={"phase": "analysis", "trial": trial} ) if not pattern_analysis: raise ValueError("Pattern analysis failed") transformation_result = dynamic_mas.execute_agent_query( task_description, agent_specs[1], context={ "phase": "transformation", "pattern_analysis": pattern_analysis, "trial": trial } ) if not transformation_result: raise ValueError("Transformation failed") validation_result = dynamic_mas.execute_agent_query( task_description, agent_specs[2], context={ "phase": "validation", "transformed_grid": transformation_result, "trial": trial } ) if not validation_result: raise ValueError("Validation failed") except Exception as e: print(f"Agent pipeline error: {str(e)}") return None # Parse and validate the final grid predicted_grid = parse_grid_from_response(validation_result) if predicted_grid and is_valid_grid(predicted_grid): return predicted_grid return None except Exception as e: print(f"Error in generate_prediction: {str(e)}") return None def switch_role(self, role: str, context: Dict = None): self.current_role = role experiences = self.learning_manager.get_role_experience(role) metrics = self.learning_manager.role_metrics[role] return self._create_role_context(role, experiences, metrics, context) def _get_role_context(self) -> str: if not self.current_role: return "" experiences = self.learning_manager.get_role_experience(self.current_role) metrics = self.learning_manager.role_metrics[self.current_role] return self._create_role_context(self.current_role, experiences, metrics) def learn_from_interaction(self, role: str, task: str, success: bool, learning: str, feedback: Optional[str] = None): experience = { 'task': task, 'success': success, 'learning': learning, 'feedback': feedback, 'timestamp': datetime.now().isoformat() } self.learning_manager.save_experience(role, experience) if role not in self.role_performance: self.role_performance[role] = [] self.role_performance[role].append({ 'timestamp': datetime.now().isoformat(), 'success': success, 'task': task }) class TaskAdapter: """Handles task-specific adaptation of the communication graph.""" def __init__(self, hidden_dim=256): self.hidden_dim = hidden_dim self.task_memory = {} self.sentence_transformer = SentenceTransformer('all-MiniLM-L6-v2') def create_task_embedding(self, task: Dict) -> torch.Tensor: """Create task-specific embedding.""" task_desc = f"Task with {len(task.get('train', []))} training examples." embedding = self.sentence_transformer.encode(task_desc) return torch.tensor(embedding) def generate_anchor_topology(self, task: Dict, agents: List[str]) -> torch.Tensor: """Generate initial anchor topology based on task type.""" num_agents = len(agents) topology = torch.zeros((num_agents, num_agents)) if self._is_pattern_recognition_task(task): for i in range(num_agents - 1): topology[i][i + 1] = 1 else: topology.fill_(1) topology.fill_diagonal_(0) return topology def _is_pattern_recognition_task(self, task: Dict) -> bool: try: input_dims = set() output_dims = set() for example in task.get('train', []) + task.get('test', []): input_dims.add((len(example['input']), len(example['input'][0]))) output_dims.add((len(example['output']), len(example['output'][0]))) return len(input_dims) == 1 and len(output_dims) == 1 except: return False class CommunicationProtocol: """Manages communication between agents.""" def __init__(self, max_rounds=3): self.max_rounds = max_rounds self.message_history = {} self.execution_order = [] def optimize_execution_order(self, graph: torch.Tensor) -> List[int]: """Determine optimal execution order based on graph structure.""" num_agents = graph.shape[0] dependencies = {i: set() for i in range(num_agents)} for i in range(num_agents): for j in range(num_agents): if graph[i][j] > 0.5: dependencies[j].add(i) visited = set() temp = set() order = [] def visit(node): if node in temp: raise ValueError("Cycle detected in agent dependencies") if node in visited: return temp.add(node) for dep in dependencies[node]: visit(dep) temp.remove(node) visited.add(node) order.append(node) for node in range(num_agents): if node not in visited: visit(node) return order[::-1] class DynamicMultiAgentSystem (): """Coordinates a single LLM that switches between agent roles.""" def __init__(self): self.llm = DynamicLLM() # Single LLM instance self.g_designer = GDesigner() # Initialize with default parameters self.task_adapter = TaskAdapter() self.protocol = CommunicationProtocol() self.is_string_response = False def initialize_roles(self, boss_response=None): """Initialize roles based on boss response or default configuration.""" if boss_response and isinstance(boss_response, dict): self.roles = boss_response self.is_string_response = True else: # Role definitions for evaluation dataset only. self.roles = { 'analyst': { 'name': 'Pattern Analyst', 'state': {}, 'memory': {}, 'performance_history': [] }, 'transformer': { 'name': 'Grid Transformer', 'state': {}, 'memory': {}, 'performance_history': [] }, 'validator': { 'name': 'Validator', 'state': {}, 'memory': {}, 'performance_history': [] } } self.is_string_response = False def _process_string_task(self, task: Dict) -> Dict: """Process tasks that require string responses.""" try: messages = {} current_state = {} for role_id, role_info in self.roles.items(): # Switch LLM to current role role_state = self.llm.switch_role( role_info['name'], { 'task': task, 'current_state': current_state, 'role_memory': role_info['memory'] } ) # Process with current role result = self._process_role(role_id, task, messages, role_state) # Store result messages[role_id] = result current_state[role_id] = result # Update role's memory self._update_role_memory(role_id, task, result) # Aggregate string responses final_response = self.protocol.aggregate_string_results(messages) return { 'result': final_response, 'messages': messages } except Exception as e: print(f"Error in string task processing: {str(e)}") return None def process_task(self, task: Dict) -> Dict: """Process task using single LLM switching between roles.""" try: # Create task embedding and anchor topology task_embedding = self.task_adapter.create_task_embedding(task) anchor_topology = self.task_adapter.generate_anchor_topology( task, list(self.roles.keys())) # Initialize performance tracking best_performance = None best_result = None current_state = {} # Multiple rounds of processing for round_num in range(self.protocol.max_rounds): # Get current graph structure graph = self.g_designer.get_communication_graph() # Process through each role sequentially round_messages = {} for role_id, role_info in self.roles.items(): # Switch LLM to current role role_state = self.llm.switch_role( role_info['name'], { 'task': task, 'current_state': current_state, 'role_memory': role_info['memory'], 'performance_history': role_info['performance_history'] } ) # Get incoming messages based on graph structure incoming_messages = self._get_role_messages( role_id, round_messages, graph) # Process with current role result = self._process_role( role_id, task, incoming_messages, role_state ) # Store result round_messages[role_id] = result current_state[role_id] = result # Update role's state and memory self._update_role_memory(role_id, task, result) # Aggregate results round_result = self.protocol.aggregate_results(round_messages) # Evaluate performance performance = self._evaluate_performance(round_result, task) # Update performance histories self._update_performance_histories(performance, round_messages) # Update best result if not best_performance or performance > best_performance: best_performance = performance best_result = round_result # Update graph based on performance self.g_designer.update_graph( task['id'], [{'role': role} for role in self.roles.keys()], {'performance': performance} ) # Early stopping if perfect performance if performance == 1.0: break return { 'result': best_result, 'performance': best_performance, 'rounds': round_num + 1 } except Exception as e: print(f"Error processing task: {str(e)}") return None def _process_role(self, role_id: str, task: Dict, messages: List[Dict], role_state: Dict) -> Dict: """Process task with current role.""" try: if role_id == 'analyst': return self._analyze_patterns(task, messages, role_state) elif role_id == 'transformer': return self._transform_grid(task, messages, role_state) elif role_id == 'validator': return self._validate_result(task, messages, role_state) return None except Exception as e: print(f"Error in role processing: {str(e)}") return None def _update_role_memory(self, role_id: str, task: Dict, result: Dict): """Update role-specific memory with results.""" try: role = self.roles[role_id] role['state'] = result if self.is_string_response: if 'string_responses' not in role['memory']: role['memory']['string_responses'] = [] role['memory']['string_responses'].append({ 'task': task, 'response': result }) else: if result.get('confidence', 0) > 0.8: task_type = self._get_task_type(task) if task_type not in role['memory']: role['memory'][task_type] = [] role['memory'][task_type].append({ 'task_features': self._extract_task_features(task), 'solution_approach': result.get('approach'), 'success': True }) # Limit memory size for key in role['memory']: if len(role['memory'][key]) > 100: role['memory'][key] = role['memory'][key][-100:] except Exception as e: print(f"Error updating role memory: {str(e)}") def _update_performance_histories(self, performance: float, round_messages: Dict): """Update performance history for each role.""" for role_id, result in round_messages.items(): self.roles[role_id]['performance_history'].append({ 'timestamp': time.time(), 'performance': performance, 'confidence': result.get('confidence', 0) }) # Limit history size if len(self.roles[role_id]['performance_history']) > 1000: self.roles[role_id]['performance_history'] = \ self.roles[role_id]['performance_history'][-1000:] def parse_grid_from_response(response) -> Optional[List[List[int]]]: """Parse the grid from the agent's response.""" try: # First try to extract grid from structured response if isinstance(response, dict) and 'grid' in response: return response['grid'] # Handle case where response is already a grid if isinstance(response, list) and all(isinstance(row, list) for row in response): if all(all(isinstance(val, int) and 0 <= val <= 9 for val in row) for row in response): return response # Parse from string response grid_lines = [] in_grid = False for line in str(response).split('\n'): # Look for grid-like patterns if ('[' in line and ']' in line) or any(str(i) for i in range(10) if str(i) in line): in_grid = True # Clean and parse numbers clean_line = (line.strip() .strip('[]') .replace(',', ' ') .replace(' ', ' ')) try: row = [int(x) for x in clean_line.split() if x.isdigit()] if row: grid_lines.append(row) except ValueError: continue elif in_grid and not line.strip(): break # Validate parsed grid if grid_lines: width = len(grid_lines[0]) if (all(len(row) == width for row in grid_lines) and all(all(0 <= val <= 9 for val in row) for row in grid_lines)): return grid_lines return None except Exception as e: print(f"Error parsing grid: {str(e)}") return None def generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]: """ Generate a prediction for a test input using the multi-agent system. Args: train_pairs: List of training input/output pairs test_input: The input grid for prediction trial: Current trial number (0-2) Returns: List[List[int]]: Predicted output grid """ try: # Initialize agents with specific roles agent_specs = [ { "role": "Pattern Analyst", "specialty": "grid_analysis", "context": { "task": "Analyze patterns in training examples and identify transformation rules", "trial": trial + 1 } }, { "role": "Grid Transformer", "specialty": "transformation", "context": { "task": "Apply identified patterns to generate output grid", "trial": trial + 1 } }, { "role": "Validator", "specialty": "validation", "context": { "task": "Verify generated grid follows identified patterns", "trial": trial + 1 } } ] # Create task description for the agents task_description = create_task_description(train_pairs, test_input) # Initialize the multi-agent system g_designer = GDesigner() llm = DynamicLLM(g_designer) mas = DynamicMultiAgentSystem(g_designer) # Execute the prediction pipeline # 1. Pattern Analysis pattern_analysis = mas.execute_agent_query( task_description, agent_specs[0], context={"phase": "analysis", "trial": trial} ) # 2. Grid Transformation transformation_result = mas.execute_agent_query( task_description, agent_specs[1], context={ "phase": "transformation", "pattern_analysis": pattern_analysis, "trial": trial } ) # 3. Validation validation_result = mas.execute_agent_query( task_description, agent_specs[2], context={ "phase": "validation", "transformed_grid": transformation_result, "trial": trial } ) # Parse the final grid from the validation result predicted_grid = parse_grid_from_response(validation_result) # Verify grid format if not is_valid_grid(predicted_grid): raise ValueError("Invalid grid format generated") return predicted_grid except Exception as e: print(f"Error in generate_prediction: {str(e)}") return None def process_all_tasks() -> Iterator[str]: """ Process all evaluation tasks sequentially with progress tracking. Returns: Iterator[str]: Yields status updates and results as strings """ try: tasks = load_evaluation_tasks() total_tasks = len(tasks) results = [] progress = gr.Progress() progress(0, desc="Initializing...") for idx, (filename, task) in enumerate(tasks): try: progress((idx / total_tasks), desc=f"Processing task {idx + 1}/{total_tasks}: {filename}") # Process task and get results task_result = process_query(task) # Now passing task dict directly results.append(f"\nTask {idx + 1}/{total_tasks}: {filename}\n{task_result}") yield "\n".join(results) except Exception as e: error_msg = f"\nError processing {filename}: {str(e)}\n" results.append(error_msg) yield "\n".join(results) progress(1.0, desc="Processing complete!") # Add final summary summary = ARCEvaluator.get_summary() summary_text = "\nEvaluation Complete!\n" summary_text += f"Total tasks processed: {total_tasks}\n" summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n" results.append(summary_text) yield "\n".join(results) except Exception as e: yield f"Fatal error during task processing: {str(e)}" def process_query(task: Dict) -> str: try: arc_loader = ARCDataLoader() arc_evaluator = ARCEvaluator(max_trials=3) # Validate the task if not arc_loader.validate_task_format(task): return "Error: Invalid ARC task format" # Process each test case with up to 3 trials results = [] for test_idx, test_case in enumerate(task['test']): success = False predicted_grid = None for trial in range(3): # 3 trials per test case try: # Generate prediction using the agent system predicted_grid = generate_prediction(task['train'], test_case['input'], trial) if predicted_grid: # Parse the grid from the response predicted_grid = parse_grid_from_response(predicted_grid) if predicted_grid: success = arc_evaluator.evaluate_output(predicted_grid, test_case['output']) arc_evaluator.record_result(f"task_{test_idx}", trial + 1, success) if success: break # Stop trials if successful except Exception as e: print(f"Trial {trial + 1} failed: {str(e)}") continue results.append({ 'test_case': test_idx + 1, 'success': success, 'predicted_grid': predicted_grid }) # Format response response = "Evaluation Results:\n\n" for result in results: response += f"Test Case {result['test_case']}:\n" response += f"Success: {result['success']}\n" if result['predicted_grid']: response += "Predicted Grid:\n" response += "\n".join(" ".join(str(cell) for cell in row) for row in result['predicted_grid']) response += "\n\n" # Add summary statistics summary = arc_evaluator.get_summary() response += f"Overall Success Rate: {summary['success_rate']*100:.2f}%\n" response += f"Average Trials to Success: {summary['average_trials_to_success']:.2f}\n" return response except Exception as e: return f"Error processing query: {str(e)}" def create_task_description(train_pairs: List[Dict], test_input: List[List[int]]) -> str: """ Create a detailed task description from training pairs and test input. """ description = "ARC Task Analysis:\n\nTraining Examples:\n" # Add training examples for idx, pair in enumerate(train_pairs): description += f"\nExample {idx + 1}:\n" description += "Input Grid:\n" description += grid_to_string(pair['input']) description += "\nOutput Grid:\n" description += grid_to_string(pair['output']) description += "\n" # Add test input description += "\nTest Input Grid:\n" description += grid_to_string(test_input) return description def grid_to_string(grid: List[List[int]]) -> str: """ Convert a grid to a string representation. """ return "\n".join(" ".join(str(cell) for cell in row) for row in grid) def is_valid_grid(grid: List[List[int]]) -> bool: """ Validate grid format according to ARC specifications. """ if not grid or not isinstance(grid, list) or not all(isinstance(row, list) for row in grid): return False # Check dimensions rows = len(grid) cols = len(grid[0]) if rows > 0 else 0 if rows < 1 or rows > 30 or cols < 1 or cols > 30: return False # Check values and consistency return all( len(row) == cols and all(isinstance(val, int) and 0 <= val <= 9 for val in row) for row in grid ) def execute_agent_query(self, task_description: str, agent_spec: Dict, context: Dict) -> str: """ Execute a query for a specific agent role. Args: task_description: Description of the task agent_spec: Specification of the agent role context: Additional context for the query Returns: str: Agent's response """ try: # Create role-specific prompt role = agent_spec["role"] specialty = agent_spec["specialty"] phase = context.get("phase", "unknown") trial = context.get("trial", 0) prompt = f"""As the {role} with expertise in {specialty}, analyze the following task. Task Phase: {phase} Trial: {trial + 1}/3 {task_description} Previous Context: {json.dumps(context, indent=2)} Your task is to {agent_spec['context']['task']}. Provide your response in the following format: 1. Analysis: Describe your understanding and approach 2. Implementation: Show your work step by step 3. Result: Provide the final output in grid format using integers 0-9 Response:""" # Generate response using the LLM response = self.llm.generate_response(prompt, role=role) # Record the interaction for learning self.llm.learn_from_interaction( role=role, task=task_description, success=True, # This should be based on validation learning="Interaction completed successfully", feedback=context ) return response except Exception as e: print(f"Error in execute_agent_query: {str(e)}") return None def load_evaluation_tasks(): """Load all JSON files from evaluation directory.""" eval_path = './evaluation' tasks = [] for filename in sorted(os.listdir(eval_path)): if filename.endswith('.json'): with open(os.path.join(eval_path, filename), 'r') as f: tasks.append((filename, json.load(f))) return tasks def grid_to_string(grid: List[List[int]]) -> str: """Convert a grid to a formatted string representation.""" if not grid: return "Empty grid" # Calculate maximum width needed for each number max_width = max(len(str(cell)) for row in grid for cell in row) # Create formatted string with aligned columns return "\n".join( " ".join(f"{cell:>{max_width}}" for cell in row) for row in grid ) def load_evaluation_tasks() -> List[Tuple[str, Dict]]: """Load all JSON files from evaluation directory.""" eval_path = './evaluation' if not os.path.exists(eval_path): raise ValueError(f"Evaluation directory not found: {eval_path}") tasks = [] for filename in sorted(os.listdir(eval_path)): if filename.endswith('.json'): try: with open(os.path.join(eval_path, filename), 'r') as f: task_data = json.load(f) # Validate task format if 'train' in task_data and 'test' in task_data: tasks.append((filename, task_data)) else: print(f"Warning: Invalid task format in {filename}") except Exception as e: print(f"Error loading {filename}: {str(e)}") if not tasks: raise ValueError("No valid task files found in evaluation directory") return tasks def create_gradio_interface(): """Create and configure the Gradio interface for the ARC system.""" import gradio as gr from datetime import datetime # Initialize system components arc_loader = ARCDataLoader() arc_evaluator = ARCEvaluator() def save_summary(results: str) -> str: """Save evaluation results to a file and return the file path.""" timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") filename = f"arc_evaluation_summary_{timestamp}.txt" with open(filename, "w") as f: f.write(results) return filename def process_and_save(): """Process tasks and generate downloadable summary.""" results_generator = process_all_tasks() final_results = None # Process all results from generator for results in results_generator: final_results = results yield results, None # Update display but not file yet # Save final results to file if final_results: summary_file = save_summary(final_results) yield final_results, summary_file with gr.Blocks() as interface: gr.Markdown("# ARC Task Solver - Automated Evaluation") gr.Markdown(""" Automated evaluation of ARC tasks using AI agents. Processing tasks from ./evaluation directory. Results will update in real-time as tasks are processed. """) with gr.Row(): start_button = gr.Button("Start Evaluation") status = gr.HTML("<div id='progress-status'>Ready to start evaluation...</div>") with gr.Row(): # Results display output = gr.Textbox( label="Evaluation Results", lines=20, max_lines=50, autoscroll=True ) # Download button for summary summary_file = gr.File( label="Download Evaluation Summary", visible=True, interactive=False ) # Add custom CSS gr.HTML(""" <style> #progress-status { margin: 10px 0; padding: 10px; background-color: #f0f0f0; border-radius: 5px; } .progress-bar { height: 20px; background-color: #4CAF50; transition: width 0.5s ease-in-out; } .output-box { max-height: 500px; overflow-y: auto; } </style> """) # Connect the start button to the processing function start_button.click( fn=process_and_save, outputs=[output, summary_file] ) return interface def process_all_tasks() -> Iterator[str]: """Process all evaluation tasks sequentially with progress tracking.""" try: tasks = load_evaluation_tasks() total_tasks = len(tasks) results = [] # Add header with timestamp timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") results.append(f"ARC Evaluation Summary\nGenerated: {timestamp}\n") results.append("=" * 50 + "\n") progress = gr.Progress() progress(0, desc="Initializing...") for idx, (filename, task) in enumerate(tasks): try: progress((idx / total_tasks), desc=f"Processing task {idx + 1}/{total_tasks}: {filename}") # Process task and get results task_result = process_query(task) results.append(f"\nTask {idx + 1}/{total_tasks}: {filename}\n{task_result}") results.append("-" * 30 + "\n") yield "\n".join(results) except Exception as e: error_msg = f"\nError processing {filename}: {str(e)}\n" results.append(error_msg) yield "\n".join(results) progress(1.0, desc="Processing complete!") arc_evaluator = ARCEvaluator() # Add final summary with detailed statistics summary = arc_evaluator.get_summary() summary_text = "\nFINAL EVALUATION SUMMARY\n" summary_text += "=" * 50 + "\n" summary_text += f"Total tasks processed: {total_tasks}\n" summary_text += f"Successful tasks: {summary['successful_tasks']}\n" summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n" summary_text += f"Average trials to success: {summary['average_trials_to_success']:.2f}\n" summary_text += "\nDetailed Statistics:\n" summary_text += "-" * 30 + "\n" summary_text += f"Tasks completed: {total_tasks}\n" summary_text += f"Tasks successful: {summary['successful_tasks']}\n" summary_text += f"Tasks failed: {total_tasks - summary['successful_tasks']}\n" results.append(summary_text) yield "\n".join(results) except Exception as e: yield f"Fatal error during task processing: {str(e)}" def process_arc_task(task_data: Dict, trial: int = 0) -> Dict: """Process a single ARC task using the advanced learning framework.""" try: # Initialize the dynamic multi-agent system if not exists global dynamic_mas if 'dynamic_mas' not in globals(): dynamic_mas = DynamicMultiAgentSystem() # Format task for processing formatted_task = { 'id': task_data.get('id', f"task_{trial}"), 'train': [ { 'input': pair['input'], 'output': pair['output'] } for pair in task_data['train'] ], 'test': [ { 'input': task_data['test'][0]['input'] } ] } # Process task with new framework result = dynamic_mas.process_task(formatted_task) if result and result.get('result'): return { 'prediction': result['result'], 'performance': result['performance'], 'rounds': result['rounds'], 'boss_specs': result['boss_specs'] } return None except Exception as e: print(f"Error in ARC task processing: {str(e)}") return None def evaluate_prediction(predicted: List[List[int]], actual: List[List[int]]) -> bool: """Evaluate if predicted grid matches actual grid.""" try: if not predicted or not actual: print("Empty prediction or actual grid") return False # Check dimensions match if len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]): print(f"Dimension mismatch: predicted {len(predicted)}x{len(predicted[0])} " f"vs actual {len(actual)}x{len(actual[0])}") return False # Check all values match exactly for i in range(len(predicted)): for j in range(len(predicted[0])): if predicted[i][j] != actual[i][j]: print(f"Mismatch at position [{i}][{j}]: " f"predicted={predicted[i][j]}, actual={actual[i][j]}") return False return True except Exception as e: print(f"Error in evaluate_prediction: {str(e)}") return False def save_results(results: List[Dict], output_file: str) -> None: """Save evaluation results to JSON file with additional metrics.""" try: # Calculate additional metrics task_metrics = { 'total_tasks_processed': len(results), 'successful_tasks': sum(1 for r in results if r.get('success', False)), 'average_rounds': statistics.mean(r['rounds'] for r in results), 'average_performance': statistics.mean(r['performance'] for r in results), 'boss_strategy_distribution': _calculate_strategy_distribution(results) } # Prepare output data output_data = { 'timestamp': datetime.now().isoformat(), 'metrics': task_metrics, 'detailed_results': results } # Save to file with open(output_file, 'w') as f: json.dump(output_data, f, indent=2) except Exception as e: print(f"Error saving results: {str(e)}") def _calculate_strategy_distribution(results: List[Dict]) -> Dict: """Calculate distribution of boss strategies used.""" try: strategy_counts = {} for result in results: boss_strategy = str(result.get('boss_strategy', [])) # Convert to string for hashing strategy_counts[boss_strategy] = strategy_counts.get(boss_strategy, 0) + 1 # Calculate percentages total = len(results) return { strategy: { 'count': count, 'percentage': (count / total) * 100 if total > 0 else 0 } for strategy, count in strategy_counts.items() } except Exception as e: print(f"Error calculating strategy distribution: {str(e)}") return {} def grid_to_string(grid: List[List[int]]) -> str: """Convert a grid to a formatted string representation.""" if not grid: return "Empty grid" # Calculate maximum width needed for each number max_width = max(len(str(cell)) for row in grid for cell in row) # Create formatted string with aligned columns return "\n".join( " ".join(f"{cell:>{max_width}}" for cell in row) for row in grid ) def evaluate_arc_tasks(task_files: List[str], output_file: str): """Evaluate ARC tasks using the new learning framework.""" results = [] total_tasks = len(task_files) successful_tasks = 0 try: for trial, task_file in enumerate(task_files): # Load task with open(task_file, 'r') as f: task_data = json.load(f) # Process task result = process_arc_task(task_data, trial) if result: # Evaluate prediction correct = evaluate_prediction( result['prediction'], task_data['test'][0]['output'] ) # Store results with additional metrics task_result = { 'task_id': task_data.get('id', f"task_{trial}"), 'success': correct, 'performance': result['performance'], 'rounds': result['rounds'], 'boss_strategy': result['boss_specs']['role_specs'], 'grid_size': { 'input': [len(task_data['test'][0]['input']), len(task_data['test'][0]['input'][0])], 'output': [len(task_data['test'][0]['output']), len(task_data['test'][0]['output'][0])] }, 'prediction_visualization': grid_to_string(result['prediction']) } results.append(task_result) if correct: successful_tasks += 1 # Save progress periodically with detailed metrics if (trial + 1) % 10 == 0: save_results(results, output_file) # Calculate final statistics with additional metrics final_stats = { 'total_tasks': total_tasks, 'successful_tasks': successful_tasks, 'success_rate': successful_tasks / total_tasks if total_tasks > 0 else 0, 'average_rounds': statistics.mean(r['rounds'] for r in results) if results else 0, 'performance_distribution': { 'mean': statistics.mean(r['performance'] for r in results) if results else 0, 'std': statistics.stdev(r['performance'] for r in results) if len(results) > 1 else 0 }, 'timestamp': datetime.now().isoformat() } # Save final results with all metrics save_results(results + [final_stats], output_file) return results, final_stats except Exception as e: print(f"Error in ARC evaluation: {str(e)}") return None, None def get_user_input(user_input: str) -> str: """Get user input for the query variable.""" try: return user_input except Exception as e: print(f"Error reading input: {str(e)}") return "" #This class is for the user query boss llm for creating agents to solve user query tasks. class BossAgent: def __init__(self, llm: DynamicLLM): self.llm = llm def create_prompt(self, query: str) -> str: """Creates structured prompt for boss agent.""" task_history = self.llm.g_designer.experience_buffer[-5:] if hasattr(self.llm, 'g_designer') else [] historical_insights = "\n".join([ f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s" for exp in task_history ]) return f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks. CURRENT TASK: {query} HISTORICAL CONTEXT: {historical_insights if task_history else 'No previous task history available.'} YOUR RESPONSIBILITIES: 1. Analyze the given task thoroughly 2. Define exactly 3 specialized AI agents that would be best suited for solving this task 3. Ensure the agents have complementary skills and clear responsibilities 4. Consider any insights from previous similar tasks 5. Provide structured response in the required format Remember: - A dedicated summarizer agent will be added automatically - Focus on creating agents with distinct, complementary roles - Consider both general capabilities and specialized knowledge needed - Agents should collaborate effectively to solve the task Please provide your response in the following format: TASK ANALYSIS: [Provide a brief analysis of the task's requirements and complexity] AGENT SPECIFICATIONS: 1. [Role1] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed] 2. [Role2] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed] 3. [Role3] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed] COLLABORATION STRATEGY: [Brief description of how these agents should work together] EXECUTION PLAN: Recommended Rounds: [Number between 1-8] Rationale: [Brief explanation for the number of rounds]""" def parse_response(self, response: str) -> Tuple[List[Dict], int]: """Parses boss response to extract agent specifications and round count.""" try: # Extract agent specifications agent_specs = [] agent_sections = response.split('\n\n') for section in agent_sections: if 'Primary Function:' in section: lines = section.strip().split('\n') role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip() plugins = [p.strip() for p in next(l for l in lines if 'Plugins:' in l) .replace('Plugins:', '') .strip() .split(',')] agent_specs.append({ "role": role, "base": self.llm.model_name, "plugins": plugins }) # Extract recommended rounds #Rounds is turned off to save on memory but can be turned on and added easily to the program by adding it to the dynamic agent framework class. # rounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response) # rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8) # Ensure exactly 3 agents if len(agent_specs) != 3: raise ValueError("Boss must specify exactly 3 agents") return agent_specs, #rounds except Exception as e: print(f"Error parsing boss response: {str(e)}") # Return default specifications if parsing fails return [ {"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]}, {"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]}, {"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]} ], 3 def process_query(self, query: str) -> Tuple[List[Dict], int]: """Process user query and return agent specifications and rounds.""" prompt = self.create_prompt(query) response = self.llm.generate_response(prompt, role="boss") return self.parse_response(response) #These (the 2 functions below) are for processing the queries for the Arc test. They currently are turned off and do not do anything but could be added in place of the pre-generated LLMs in the Dynamic Agent Framework. '''def _create_boss_prompt(self, query: str) -> str: """ Creates a structured prompt for the boss agent to interpret tasks and define specialized agents. Args: query (str): The user's input query/task description Returns: str: A formatted prompt for the boss agent """ # Get historical performance if available task_history = self.g_designer.experience_buffer[-5:] if self.g_designer.experience_buffer else [] historical_insights = "\n".join([ f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s" for exp in task_history ]) boss_prompt = f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks. CURRENT TASK: {query} HISTORICAL CONTEXT: {historical_insights if task_history else 'No previous task history available.'} YOUR RESPONSIBILITIES: 1. Analyze the given task thoroughly 2. Define exactly 3 specialized AI agents that would be best suited for solving this task 3. Ensure the agents have complementary skills and clear responsibilities 4. Consider any insights from previous similar tasks 5. Provide structured response in the required format Remember: - A dedicated summarizer agent will be added automatically - Focus on creating agents with distinct, complementary roles - Consider both general capabilities and specialized knowledge needed - Agents should collaborate effectively to solve the task Please provide your response in the following format: TASK ANALYSIS: [Provide a brief analysis of the task's requirements and complexity] AGENT SPECIFICATIONS: 1. [Role1] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed] 2. [Role2] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed] 3. [Role3] Primary Function: [Main responsibility] Specialty: [Key areas of expertise] Plugins: [Relevant tools/capabilities] Reasoning: [Why this agent is needed] COLLABORATION STRATEGY: [Brief description of how these agents should work together] EXECUTION PLAN: Recommended Rounds: [Number between 1-8] Rationale: [Brief explanation for the number of rounds] Based on your analysis, provide the complete response following this format.""" return boss_prompt def _parse_boss_response(self, response: str) -> Tuple[List[Dict], int]: """ Parses the boss's response to extract agent specifications and round count. Args: response (str): The boss agent's formatted response Returns: Tuple[List[Dict], int]: A tuple containing the list of agent specifications and recommended rounds """ try: # Extract agent specifications agent_specs = [] agent_sections = response.split('\n\n') for section in agent_sections: if 'Primary Function:' in section: lines = section.strip().split('\n') role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip() plugins = [p.strip() for p in next(l for l in lines if 'Plugins:' in l) .replace('Plugins:', '') .strip() .split(',')] agent_specs.append({ "role": role, "base": self.llm.model_name, "plugins": plugins }) # Extract recommended rounds rounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response) rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8) # Ensure exactly 3 agents if len(agent_specs) != 3: raise ValueError("Boss must specify exactly 3 agents") return agent_specs, rounds except Exception as e: print(f"Error parsing boss response: {str(e)}") # Return default specifications if parsing fails return [ {"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]}, {"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]}, {"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]} ], 3''' #Function below allows the Boss LLM to handle both grid (evaluation for Arc only) and user queries. Only the generic user query is used but the grid can be easily added in the main def function. ''' #The query handler function does nothing and was replaced with the query processing in the main function. class QueryHandler: """Handles different types of queries and generates appropriate prompts.""" def __init__(self): self.default_prompt = self._create_default_prompt self.grid_prompt = self._create_grid_prompt def create_prompt(self, query: str, is_grid_query: bool = True) -> str: """Create appropriate prompt based on query type.""" if not is_grid_query: return self._create_custom_prompt(query) #This is in case the user wants to use a dataset as this can be turned on by removing the comments to allow the user to use a dataset. return self._create_grid_prompt(query) def _create_default_prompt(self, query: str) -> str: """Create a standard prompt for non-grid queries.""" return f"""Analyze and respond to the following query: Query: {query} Please provide a clear and concise response that addresses the query directly. Focus on providing practical, implementable solutions. Your response should include: 1. Direct answer to the query 2. Any relevant explanations or context 3. Specific recommendations or solutions""" def _create_grid_prompt(self, query: str) -> str: """Create a prompt for grid-based ARC tasks.""" return f"""Analyze the following ARC task with grid patterns: Task Description: {query} Training Examples: [Grid examples will be formatted here] Your analysis should include: 1. Pattern identification 2. Transformation rules 3. Grid-based solution approach 4. Step-by-step implementation 5. Final output grid""" def _create_custom_prompt(self, query: str) -> str: """Create a customized prompt for specific query types.""" return f"""Process the following specialized query: Query: {query} Please provide: 1. Direct response 2. Key insights 3. Actionable recommendations Note: This is a non-grid query that requires specific domain expertise.""" def process_query(self, query: str, is_grid_query: bool = True) -> Dict[str, Any]: """Process the query and return appropriate response format.""" prompt = self.create_prompt(query, is_grid_query) return { 'prompt': prompt, 'is_grid_query': is_grid_query, 'query_type': 'grid' if is_grid_query else 'standard', 'timestamp': time.time() }''' def main(): try: # Get user input for query or use the dataset query use_dataset_query = False # Set this to False to use user input if use_dataset_query == True: evaluator = ARCEvaluator() interface = create_gradio_interface() interface.launch() """Main execution function.""" # Setup paths task_dir = "evaluation/tasks" output_file = f"results/arc_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json" # Get task files task_files = glob.glob(os.path.join(task_dir, "*.json")) # Create results directory if needed os.makedirs("results", exist_ok=True) # Run evaluation results, stats = evaluate_arc_tasks(task_files, output_file) if results and stats: print("\nEvaluation Complete!") print(f"Total Tasks: {stats['total_tasks']}") print(f"Successful Tasks: {stats['successful_tasks']}") print(f"Success Rate: {stats['success_rate']:.2%}") print(f"Results saved to: {output_file}") else: print("Evaluation failed!") else: llm = DynamicLLM() boss_agent = BossAgent(llm) system = DynamicMultiAgentSystem() def process_query(query: str) -> str: if not query.strip(): return "Please enter a query" try: response = llm.generate_response(query) return response if response else "No response generated" except Exception as e: return f"Error processing query: {str(e)}" # Create Gradio interface interface = gr.Interface( fn=process_query, inputs=gr.Textbox(lines=3, placeholder="Enter your query..."), outputs=gr.Textbox(), title="Dynamic LLM Query System" ) interface.launch() except Exception as e: print(f"Error in main execution: {str(e)}") if __name__ == "__main__": main() #Need to create a switch in the multiagent class so it will take the response from the bossllm class to set-up the agents. if this response is not recieved, then the #ai agent framework will just handle the dataset as before. This will need to be edited from claude's response.
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GAE, VGAE
import gc
import os
import json
import pickle
import signal
import sys
import time
import glob
import uuid
import statistics
import gradio as gr
from datetime import datetime
from typing import Dict, List, Optional, Any, Union, Tuple, Iterator
from dataclasses import dataclass
from sentence_transformers import SentenceTransformer
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig
from torch.optim import Adam
# Constants
MAX_ROUNDS = 3
CONFIDENCE_THRESHOLD = 3
JSON_DIRECTORY = './evaluation'
#G-Designer Agents
class BaseAgent(nn.Module):
"""Base class for all agents with learning capabilities."""
def __init__(self, role: str, base_model: str, plugins: List[str]):
super().__init__()
self.role = role
self.base_model = base_model
self.plugins = plugins
self.state_history = []
self.learning_rate = 0.001
# Initialize neural components
self.message_encoder = nn.LSTM(768, 256, bidirectional=True)
self.state_encoder = nn.Linear(512, 256)
self.decision_network = nn.Sequential(
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 32)
)
self.optimizer = Adam(self.parameters(), lr=self.learning_rate)
def update_state(self, interaction: Dict):
"""Update agent's state based on interaction."""
self.state_history.append(interaction)
if len(self.state_history) > 1000: # Limit history size
self.state_history = self.state_history[-1000:]
def encode_messages(self, messages: List[str]) -> torch.Tensor:
"""Encode incoming messages."""
message_embeddings = []
for msg in messages:
embedding = self.sentence_transformer.encode(msg)
message_embeddings.append(torch.tensor(embedding))
if message_embeddings:
message_tensor = torch.stack(message_embeddings)
encoded, _ = self.message_encoder(message_tensor.unsqueeze(0))
return encoded.mean(dim=1) # Average over sequence
return torch.zeros(512) # Default empty embedding
def learn_from_feedback(self, feedback: Dict):
"""Learn from feedback about agent's performance."""
raise NotImplementedError
class PatternAnalystAgent(BaseAgent):
"""Specializes in analyzing patterns in ARC tasks."""
def __init__(self):
super().__init__(
role="Pattern Analyst",
base_model="gpt-4",
plugins=["grid_analyzer", "pattern_matcher"]
)
# Pattern recognition components
self.pattern_encoder = nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool2d((4, 4))
)
self.pattern_memory = {}
def process(self, task_input: Dict, messages: List[str]) -> Dict:
"""Process task input and identify patterns."""
try:
# Encode grid patterns