Spaces:
Build error
Build error
Create app,py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch_geometric.nn import GCNConvfrom sentence_transformers import SentenceTransformerimport jsonimport numpy as npimport osfrom typing import List, Dict, Tuple, Optional, Anyfrom dataclasses import dataclass# Initialize optimizer - Fixed by importing torch.optim and using torch's Adam optimizerfrom torch.optim import Adam'''If time, include option to turn on/off Granite for Prompt Safety and LiteLLM for Prompt Optimizations to increase accuracy and LLM understanding of tasks. '''# Maximum rounds for any taskMAX_ROUNDS = 8# Threshold for confidence level to stop querying LLMCONFIDENCE_THRESHOLD = 3
class ARCDataLoader: """Handles loading and processing of ARC task data.""" def __init__(self, base_path: str = "/kaggle/input/evaluation2/evaluation"): 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_task_format(self, task: Dict) -> bool: """Validate that a task has the correct format.""" try: for example in task['train'] + task['test']: if not isinstance(example['input'], list) or not isinstance(example['output'], list): return False if not all(isinstance(row, list) for row in example['input'] + example['output']): return False if not all(isinstance(val, int) for row in example['input'] + example['output'] for val in row): return False return True except (KeyError, TypeError): 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: """Evaluates agent system performance on ARC tasks.""" def __init__(self, max_trials: int = 3): self.max_trials = max_trials self.results = [] def evaluate_output(self, predicted: List[List[int]], actual: List[List[int]]) -> bool: """Check if predicted output matches actual output exactly.""" if len(predicted) != len(actual) or any(len(pred_row) != len(act_row) for pred_row, act_row in zip(predicted, actual)): return False return all(all(p == a for p, a in zip(pred_row, act_row)) for pred_row, act_row in zip(predicted, actual)) def record_result(self, task_id: str, success: bool, trials_used: int): """Record the result of a task evaluation.""" self.results.append({ 'task_id': task_id, 'success': success, 'trials_used': trials_used }) def get_summary(self) -> Dict: """Generate summary statistics of evaluation results.""" total_tasks = len(self.results) successful_tasks = sum(1 for r in self.results if r['success']) avg_trials = sum(r['trials_used'] for r in self.results) / total_tasks if total_tasks > 0 else 0 return { 'total_tasks': total_tasks, 'successful_tasks': successful_tasks, 'success_rate': successful_tasks / total_tasks if total_tasks > 0 else 0, 'average_trials': avg_trials }
def load_grid_data(data: Dict) -> Tuple[List[Dict], List[Dict]]: """ Load grid transformation data from the provided dictionary. Args: data: Dictionary containing 'train' and 'test' data Returns: Tuple of training and test data lists """ return data['train'], data['test']
def process_grid_example(example: Dict) -> Tuple[torch.Tensor, torch.Tensor]: """ Convert a grid example into input and output tensors. Args: example: Dictionary containing 'input' and 'output' grids Returns: Tuple of input and output tensors """ input_grid = torch.tensor(example['input'], dtype=torch.float32) output_grid = torch.tensor(example['output'], dtype=torch.float32) return input_grid, output_grid
class GDesigner(nn.Module): def __init__( self, input_dim: int = 768, hidden_dim: int = 256, latent_dim: int = 128, temperature: float = 0.1, sparsity_factor: float = 0.1, learning_rate: float = 0.001 ): super().__init__() self.node_encoder = NodeEncoder(input_dim) self.graph_encoder = GCNEncoder(input_dim, hidden_dim, latent_dim) self.graph_decoder = GraphDecoder(latent_dim, hidden_dim) self.temperature = temperature self.sparsity_factor = sparsity_factor # Initialize optimizer self.optimizer = Adam(self.parameters(), lr=learning_rate) def create_anchor_topology(self, num_agents: int) -> torch.Tensor: """Create default chain structure anchor topology.""" topology = torch.zeros((num_agents, num_agents)) # Create bidirectional chain structure for i in range(num_agents-1): topology[i, i+1] = 1 topology[i+1, i] = 1 # Add reverse connections return topology def encode_agents( self, agents: List[Dict], query: str ) -> Tuple[torch.Tensor, torch.Tensor]: """Encode agents and query into node features.""" agent_features = [] for agent in agents: text = f"Base: {agent['base']}, Role: {agent['role']}, Plugins: {', '.join(agent['plugins'])}" agent_features.append(self.node_encoder(text)) task_features = self.node_encoder(query) node_features = torch.stack(agent_features) return node_features, task_features def compute_loss( self, mu: torch.Tensor, log_std: torch.Tensor, S: torch.Tensor, anchor_topology: torch.Tensor, ground_truth: Optional[torch.Tensor] = None ) -> torch.Tensor: """Compute the total loss for training.""" # 1. KL Divergence loss for VAE kl_loss = -0.5 * torch.sum(1 + 2 * log_std - mu.pow(2) - torch.exp(2 * log_std)) # 2. Reconstruction loss if ground_truth is not None: recon_loss = F.binary_cross_entropy(S, ground_truth) else: # If no ground truth, use anchor topology as soft target recon_loss = F.binary_cross_entropy(S, anchor_topology) # 3. Sparsity loss sparsity_loss = torch.norm(S, p=1) # L1 norm for sparsity # 4. Structural loss to maintain essential connections from anchor topology structural_loss = F.mse_loss(S * anchor_topology, anchor_topology) # Combine losses with weights total_loss = ( kl_loss * 0.1 + # KL weight recon_loss * 1.0 + # Reconstruction weight sparsity_loss * self.sparsity_factor + # Sparsity weight structural_loss * 0.5 # Structural weight ) return total_loss
def update_parameters(self, loss: torch.Tensor): """Update model parameters using computed loss.""" self.optimizer.zero_grad() loss.backward() # Gradient clipping to prevent exploding gradients torch.nn.utils.clip_grad_norm_(self.parameters(), max_norm=1.0) self.optimizer.step() def train_step( self, agents: List[Dict], query: str, ground_truth: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, torch.Tensor]: """Execute a single training step.""" self.train() # Create anchor topology anchor_topology = self.create_anchor_topology(len(agents)) # Forward pass node_features, task_features = self.encode_agents(agents, query) edge_index = anchor_topology.nonzero().t() mu, log_std = self.graph_encoder(node_features, edge_index) std = torch.exp(log_std) eps = torch.randn_like(std) z = mu + eps * std S = self.graph_decoder(z, task_features) # Compute loss loss = self.compute_loss(mu, log_std, S, anchor_topology, ground_truth) # Update parameters self.update_parameters(loss) return S, loss
def train( self, training_data: List[Tuple[List[Dict], str, Optional[torch.Tensor]]], num_epochs: int, batch_size: int = 32, validation_data: Optional[List[Tuple[List[Dict], str, torch.Tensor]]] = None ): """Train the model on a dataset of queries and agent configurations.""" for epoch in range(num_epochs): total_loss = 0.0 num_batches = 0 # Create batches for i in range(0, len(training_data), batch_size): batch = training_data[i:i + batch_size] batch_loss = 0.0 # Process each item in batch for agents, query, ground_truth in batch: _, loss = self.train_step(agents, query, ground_truth) batch_loss += loss.item() avg_batch_loss = batch_loss / len(batch) total_loss += avg_batch_loss num_batches += 1 epoch_loss = total_loss / num_batches print(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}") # Validation step if validation_data is not None: self.eval() with torch.no_grad(): val_loss = 0.0 for agents, query, ground_truth in validation_data: node_features, task_features = self.encode_agents(agents, query) anchor_topology = self.create_anchor_topology(len(agents)) edge_index = anchor_topology.nonzero().t() mu, log_std = self.graph_encoder(node_features, edge_index) std = torch.exp(log_std) eps = torch.randn_like(std) z = mu + eps * std S = self.graph_decoder(z, task_features) loss = self.compute_loss(mu, log_std, S, anchor_topology, ground_truth) val_loss += loss.item() avg_val_loss = val_loss / len(validation_data) print(f"Validation Loss: {avg_val_loss:.4f}")
def generate_communication_topology( self, agents: List[Dict], query: str, anchor_topology: Optional[torch.Tensor] = None ) -> torch.Tensor: """Generate communication topology for multi-agent system.""" self.eval() with torch.no_grad(): # Create default anchor topology if none provided if anchor_topology is None: anchor_topology = self.create_anchor_topology(len(agents)) # Encode agents and query node_features, task_features = self.encode_agents(agents, query) edge_index = anchor_topology.nonzero().t() # Generate topology mu, log_std = self.graph_encoder(node_features, edge_index) std = torch.exp(log_std) eps = torch.randn_like(std) z = mu + eps * std S = self.graph_decoder(z, task_features) # Apply sparsification and refinement S = (S / self.temperature).softmax(dim=-1) mask = torch.bernoulli(S) S = S * mask if self.sparsity_factor > 0: S = self.apply_sparsity(S, anchor_topology) return S
def apply_sparsity(self, S: torch.Tensor, anchor: torch.Tensor) -> torch.Tensor: """Apply sparsity regularization to maintain essential connections.""" U, s, V = torch.svd(S) s_sparse = torch.relu(s - self.sparsity_factor) S_refined = torch.mm(torch.mm(U, torch.diag(s_sparse)), V.t()) alpha = 0.5 S_final = alpha * S_refined + (1 - alpha) * anchor return S_final
class SpecializedAgent: """Represents an agent with specific roles and specializations.""" def __init__(self, base_model: str, role: str, plugins: List[str]): self.base = base_model self.role = role self.plugins = plugins
def get_description(self) -> str: return f"Base: {self.base}, Role: {self.role}, Plugins: {', '.join(self.plugins)}"
class NodeEncoder(nn.Module): def __init__(self, embedding_dim: int = 768): super().__init__() self.sentence_encoder = SentenceTransformer('all-MiniLM-L6-v2') self.projection = nn.Linear(384, embedding_dim) # MiniLM outputs 384-dim vectors def forward(self, text_data: str) -> torch.Tensor: """Encode text data into fixed-length embeddings.""" embeddings = self.sentence_encoder.encode(text_data, convert_to_tensor=True) return self.projection(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]: """Encode graph structure into latent representations.""" 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: """Decode latent representations into adjacency matrix.""" 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)
def __init__( self, input_dim: int = 768, hidden_dim: int = 256, latent_dim: int = 128, temperature: float = 0.1, sparsity_factor: float = 0.1, learning_rate: float = 0.001 ): super().__init__() # Grid processing layers self.conv1 = GCNConv(1, 16) self.conv2 = GCNConv(16, 16) self.conv3 = GCNConv(16, 1) # Graph design components self.node_encoder = NodeEncoder(input_dim) self.graph_encoder = GCNEncoder(input_dim, hidden_dim, latent_dim) self.graph_decoder = GraphDecoder(latent_dim, hidden_dim) self.temperature = temperature self.sparsity_factor = sparsity_factor # Initialize optimizer - Fixed by importing torch.optim and using torch's Adam optimizer from torch.optim import Adam self.optimizer = Adam(self.parameters(), lr=learning_rate)
def forward(self, x, edge_index): """Forward pass for grid processing""" x = F.relu(self.conv1(x, edge_index)) x = F.relu(self.conv2(x, edge_index)) x = self.conv3(x, edge_index) return x
def process_grid_example(self, example: Dict) -> Tuple[torch.Tensor, torch.Tensor]: """Convert a grid example into input and output tensors.""" input_grid = torch.tensor(example['input'], dtype=torch.float32) output_grid = torch.tensor(example['output'], dtype=torch.float32) return input_grid, output_grid
def _create_grid_edges(self, shape: Tuple[int, ...]) -> torch.Tensor: """Create edge connections for grid structure""" edges = [] rows, cols = shape for i in range(rows): for j in range(cols): if j < cols - 1: # horizontal connections edges.append((i * cols + j, i * cols + j + 1)) if i < rows - 1: # vertical connections edges.append((i * cols + j, (i + 1) * cols + j)) edges = torch.tensor(edges, dtype=torch.long).t() return edges
def create_anchor_topology(self, num_agents: int) -> torch.Tensor: """Create default chain structure anchor topology.""" topology = torch.zeros((num_agents, num_agents)) for i in range(num_agents-1): topology[i, i+1] = 1 topology[i+1, i] = 1 return topology
def encode_agents(self, agents: List[Dict], query: str) -> Tuple[torch.Tensor, torch.Tensor]: """Encode agents and query into node features.""" agent_features = [] for agent in agents: text = f"Base: {agent['base']}, Role: {agent['role']}, Plugins: {', '.join(agent['plugins'])}" agent_features.append(self.node_encoder(text)) task_features = self.node_encoder(query) node_features = torch.stack(agent_features) return node_features, task_features
def compute_loss( self, mu: torch.Tensor, log_std: torch.Tensor, S: torch.Tensor, anchor_topology: torch.Tensor, ground_truth: Optional[torch.Tensor] = None ) -> torch.Tensor: """Compute the total loss for graph design training.""" kl_loss = -0.5 * torch.sum(1 + 2 * log_std - mu.pow(2) - torch.exp(2 * log_std)) if ground_truth is not None: recon_loss = F.binary_cross_entropy(S, ground_truth) else: recon_loss = F.binary_cross_entropy(S, anchor_topology) sparsity_loss = torch.norm(S, p=1) structural_loss = F.mse_loss(S * anchor_topology, anchor_topology) total_loss = ( kl_loss * 0.1 + recon_loss * 1.0 + sparsity_loss * self.sparsity_factor + structural_loss * 0.5 ) return total_loss
def train_combined( self, grid_data: List[Dict], agent_data: List[Dict], query: str, num_epochs: int = 10, ground_truth: Optional[torch.Tensor] = None ): """Combined training method for both grid processing and graph design""" self.train() for epoch in range(num_epochs): total_grid_loss = 0 total_graph_loss = 0 # Train on grid data for example in grid_data: input_grid, target_grid = self.process_grid_example(example) edge_index = self._create_grid_edges(input_grid.shape) self.optimizer.zero_grad() output = self(input_grid.view(-1, 1), edge_index) grid_loss = F.mse_loss(output.view(target_grid.shape), target_grid) grid_loss.backward() self.optimizer.step() total_grid_loss += grid_loss.item()
# Train on graph design node_features, task_features = self.encode_agents(agent_data, query) anchor_topology = self.create_anchor_topology(len(agent_data)) mu, log_std = self.graph_encoder(node_features, task_features) S = self.graph_decoder(mu) graph_loss = self.compute_loss(mu, log_std, S, anchor_topology, ground_truth) graph_loss.backward() self.optimizer.step() total_graph_loss += graph_loss.item() print(f"Epoch {epoch+1}") print(f"Grid Loss: {total_grid_loss/len(grid_data):.4f}") print(f"Graph Loss: {total_graph_loss:.4f}") def update_parameters(self, loss: torch.Tensor): """Update model parameters using computed loss.""" self.optimizer.zero_grad() loss.backward() # Gradient clipping to prevent exploding gradients torch.nn.utils.clip_grad_norm_(self.parameters(), max_norm=1.0) self.optimizer.step() def train_step( self, agents: List[Dict], query: str, ground_truth: Optional[torch.Tensor] = None ) -> Tuple[torch.Tensor, torch.Tensor]: """Execute a single training step.""" self.train() # Create anchor topology anchor_topology = self.create_anchor_topology(len(agents)) # Forward pass node_features, task_features = self.encode_agents(agents, query) edge_index = anchor_topology.nonzero().t() mu, log_std = self.graph_encoder(node_features, edge_index) std = torch.exp(log_std) eps = torch.randn_like(std) z = mu + eps * std S = self.graph_decoder(z, task_features) # Compute loss loss = self.compute_loss(mu, log_std, S, anchor_topology, ground_truth) # Update parameters self.update_parameters(loss) return S, loss
def train( self, training_data: List[Tuple[List[Dict], str, Optional[torch.Tensor]]], num_epochs: int, batch_size: int = 32, validation_data: Optional[List[Tuple[List[Dict], str, torch.Tensor]]] = None ): """Train the model on a dataset of queries and agent configurations.""" for epoch in range(num_epochs): total_loss = 0.0 num_batches = 0 # Create batches for i in range(0, len(training_data), batch_size): batch = training_data[i:i + batch_size] batch_loss = 0.0 # Process each item in batch for agents, query, ground_truth in batch: _, loss = self.train_step(agents, query, ground_truth) batch_loss += loss.item() avg_batch_loss = batch_loss / len(batch) total_loss += avg_batch_loss num_batches += 1 epoch_loss = total_loss / num_batches print(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}") # Validation step if validation_data is not None: self.eval() with torch.no_grad(): val_loss = 0.0 for agents, query, ground_truth in validation_data: node_features, task_features = self.encode_agents(agents, query) anchor_topology = self.create_anchor_topology(len(agents)) edge_index = anchor_topology.nonzero().t() mu, log_std = self.graph_encoder(node_features, edge_index) std = torch.exp(log_std) eps = torch.randn_like(std) z = mu + eps * std S = self.graph_decoder(z, task_features) loss = self.compute_loss(mu, log_std, S, anchor_topology, ground_truth) val_loss += loss.item() avg_val_loss = val_loss / len(validation_data) print(f"Validation Loss: {avg_val_loss:.4f}")
def generate_communication_topology( self, agents: List[Dict], query: str, anchor_topology: Optional[torch.Tensor] = None ) -> torch.Tensor: """Generate communication topology for multi-agent system.""" self.eval() with torch.no_grad(): # Create default anchor topology if none provided if anchor_topology is None: anchor_topology = self.create_anchor_topology(len(agents)) # Encode agents and query node_features, task_features = self.encode_agents(agents, query) edge_index = anchor_topology.nonzero().t() # Generate topology mu, log_std = self.graph_encoder(node_features, edge_index) std = torch.exp(log_std) eps = torch.randn_like(std) z = mu + eps * std S = self.graph_decoder(z, task_features) # Apply sparsification and refinement S = (S / self.temperature).softmax(dim=-1) mask = torch.bernoulli(S) S = S * mask if self.sparsity_factor > 0: S = self.apply_sparsity(S, anchor_topology) return S
def apply_sparsity(self, S: torch.Tensor, anchor: torch.Tensor) -> torch.Tensor: """Apply sparsity regularization to maintain essential connections.""" U, s, V = torch.svd(S) s_sparse = torch.relu(s - self.sparsity_factor) S_refined = torch.mm(torch.mm(U, torch.diag(s_sparse)), V.t()) alpha = 0.5 S_final = alpha * S_refined + (1 - alpha) * anchor return S_final
@dataclassclass DialogueRound: """Structure to track dialogue history within a round.""" round_number: int agent_outputs: Dict[int, Dict[str, Any]] aggregated_result: Optional[str] = None
class Task: """Represents a user task and stores associated agents for potential reuse.""" description: str agents: List[SpecializedAgent] suggested_rounds: int # Track suggested rounds from LLM or system
from transformers import AutoModelForCausalLM, AutoTokenizerimport torchfrom typing import List, Dict, Tuple, Optional, Anyfrom dataclasses import dataclass
# Initialize the Chocolatine modelmodel_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised"tokenizer = AutoTokenizer.from_pretrained(model_name)model = AutoModelForCausalLM.from_pretrained( model_name, torch_dtype=torch.float16, device_map="auto", offload_folder="model_cache")
def generate_llm_response(prompt: str, max_length: int = 3,000, truncation=True, padding='max_length') -> str: """Generate response using Chocolatine model""" inputs = tokenizer(prompt, return_tensors="pt").to("cuda" if torch.cuda.is_available() else "cpu") outputs = model.generate(**inputs, max_length=max_length) response = tokenizer.decode(outputs[0], skip_special_tokens=True) return response
def generate_agent_specs(task_description: str) -> Tuple[List[Dict], int]: """Generate exactly 3 agent specifications and round count based on task using Chocolatine as boss LLM.""" boss_prompt = f"""Task: {task_description}
Keep you response concise and adhering to the following: As the boss AI, your job is to: 1. Define exactly 3 specialized AI agents that would be best suited for solving this task effectively 2. Specify how many discussion rounds (1-8) these agents need to solve the problem Consider the full scope of the task and create 3 agents with complementary skills. Note: A dedicated summarizer agent will be added automatically, so focus on task-specific agents.
Format your response as: AGENTS: 1. [Role1] Specialty: [Brief description of agent's specialty] Plugins: [comma-separated list of relevant plugins/tools] 2. [Role2] Specialty: [Brief description of agent's specialty] Plugins: [comma-separated list of relevant plugins/tools] 3. [Role3] Specialty: [Brief description of agent's specialty] Plugins: [comma-separated list of relevant plugins/tools] ROUNDS: [number 1-8]""" response = generate_llm_response(boss_prompt) # Parse the response to extract agents and rounds try: agents_section, rounds_section = response.split("ROUNDS:") # Parse agents agent_blocks = [block.strip() for block in agents_section.split("\n\n") if block.strip()] agent_specs = [] for block in agent_blocks[1:4]: # Always take exactly 3 agents lines = block.split("\n") role = lines[0].strip().split(".", 1)[-1].strip() specialty = next((line.split(":", 1)[1].strip() for line in lines if "Specialty:" in line), "") plugins = next((line.split(":", 1)[1].strip().split(",") for line in lines if "Plugins:" in line), []) agent_specs.append({ "base": model_name, "role": role, "specialty": specialty, "plugins": [p.strip() for p in plugins] }) # If we got fewer than 3 agents, add generic ones to reach 3 while len(agent_specs) < 3: agent_specs.append({ "base": model_name, "role": f"Assistant {len(agent_specs) + 1}", "specialty": "General problem solving", "plugins": ["analysis"] }) rounds = min(max(1, int(rounds_section.strip())), 8) # Ensure rounds is between 1-8 return agent_specs[:3], rounds # Ensure exactly 3 agents are returned except Exception as e: print(f"Error parsing LLM response: {e}") # Fallback default configuration with exactly 3 agents return [ {"base": model_name, "role": "Analyst", "specialty": "Data analysis", "plugins": ["data_analysis"]}, {"base": model_name, "role": "Researcher", "specialty": "Information gathering", "plugins": ["knowledge_base"]}, {"base": model_name, "role": "Expert", "specialty": "Domain expertise", "plugins": ["domain_expertise"]} ], 3 rounds = min(max(1, int(rounds_section.strip())), 8) # Ensure rounds is between 1-8 return agent_specs, rounds class MultiAgentSystem: def __init__(self, g_designer, temperature: float = 1.0): self.g_designer = g_designer self.temperature = temperature self.saved_tasks = {} self.feedback_data = {} # Fixed summarizer agent that never changes self.summarizer_agent = { "base": model_name, "role": "Summarizer", "specialty": "Information synthesis and consolidation", "plugins": ["text_analysis", "summary_generation"] } def execute_query(self, query: str, agent_specs: List[Dict], initial_rounds: int) -> str: """Execute query using dynamically generated agents plus fixed summarizer.""" # Add summarizer to agent specifications all_agents = agent_specs + [self.summarizer_agent] # Check if agents for a similar task exist task = self.load_agents_for_task(query) if task: agents = task.agents max_rounds = task.suggested_rounds else: # Initialize agents based on specifications agents = [SpecializedAgent( spec["base"], spec["role"], spec["plugins"] ) for spec in all_agents] max_rounds = self.get_feedback_adjusted_rounds(query, initial_rounds) self.save_agents_for_task(query, agents, max_rounds) print(f"\nExecuting query: {query} with {max_rounds} rounds.") print("\nActive agents:") for agent in agents[:-1]: # Print all except summarizer print(f"- {agent.get_description()}") print("- Summarizer (Fixed agent for result synthesis)") # Generate communication topology topology = self.g_designer.generate_communication_topology(agents, query) dialogue_history = [] current_state = {"query": query, "intermediate_results": {}} # Execute dialogue rounds for round_num in range(max_rounds): execution_order = self.determine_execution_order(topology) round_outputs = DialogueRound(round_num=round_num, agent_outputs={}) for agent_idx in execution_order: agent = agents[agent_idx] inputs = self.gather_agent_inputs(agent_idx, topology, current_state) result = self.execute_agent( agent, inputs, round_num, max_rounds ) round_outputs.agent_outputs[agent_idx] = result current_state["intermediate_results"][agent_idx] = result dialogue_history.append(round_outputs) # Final aggregation using fixed summarizer agent final_answer = self.aggregate_results(dialogue_history, query) # Collect feedback feedback = input(f"\nWere the {max_rounds} rounds sufficient? (yes/too few/too many): ").strip().lower() self.record_feedback(query, max_rounds, feedback) return final_answer
class MultiAgentSystem: def __init__(self, g_designer, temperature: float = 1.0): self.g_designer = g_designer self.temperature = temperature self.saved_tasks = {} self.feedback_data = {} # Fixed summarizer agent using Chocolatine self.summarizer_agent = { "base": model_name, "role": "Summarizer", "plugins": ["text_analysis"] } def execute_agent(self, agent: Dict, inputs: Dict, round_num: int, total_rounds: int) -> Dict: """Execute individual agent using Chocolatine model""" system_prompt = self.create_system_prompt(round_num, total_rounds) context = "Previous inputs:\n" for idx, result in inputs["connected_results"].items(): context += f"- From {result['role']}: {result['response']}\n" prompt = f"""System: {system_prompt} Query: {inputs['query']} {context} As {agent['role']}, provide your response:""" response = generate_llm_response(prompt) return { "role": agent["role"], "response": response }
def save_agents_for_task(self, task_description: str, agents: List[SpecializedAgent], suggested_rounds: int): """Save agents associated with a task for future use.""" self.saved_tasks[task_description] = Task(description=task_description, agents=agents, suggested_rounds=suggested_rounds)
def load_agents_for_task(self, task_description: str) -> Optional[Task]: """Load agents if they were previously saved for a similar task.""" return self.saved_tasks.get(task_description) def create_system_prompt(self, round_num: int, total_rounds: int) -> str: """Create appropriate system prompt based on dialogue round.""" if round_num < total_rounds - 1: return """You are participating in a multi-agent dialogue. Consider the inputs from other agents and provide your expertise while maintaining coherence with the ongoing discussion.""" else: return """You are in the final round of a multi-agent dialogue. Focus on synthesizing the key points and working towards a conclusive response.""" def create_summarizer_prompt(self, dialogue_history: List[DialogueRound], query: str) -> str: """Create prompt for the summarizer agent.""" prompt = f"""As a summarizer, your task is to synthesize the dialogue history from multiple expert agents regarding the query: "{query}" Consider the following dialogue history across {len(dialogue_history)} rounds: """ for round in dialogue_history: prompt += f"\nRound {round.round_number}:\n" for agent_idx, output in round.agent_outputs.items(): prompt += f"- {output['role']}: {output['response']}\n" prompt += "\nPlease provide a comprehensive final answer that:" prompt += "\n1. Synthesizes the key insights from all agents" prompt += "\n2. Resolves any contradictions or conflicts" prompt += "\n3. Presents a coherent and complete solution" return prompt def get_feedback_adjusted_rounds(self, task_description: str, initial_rounds: int) -> int: """Adjust the round count based on historical feedback data and confidence.""" rounds, confidence = self.feedback_data.get(task_description, (initial_rounds, 0)) # Stop querying LLM if confidence is high enough if confidence >= CONFIDENCE_THRESHOLD: return min(rounds, MAX_ROUNDS) else: return min(initial_rounds, MAX_ROUNDS) def record_feedback(self, task_description: str, rounds_used: int, feedback: str): """Record feedback to refine round estimates and build confidence.""" rounds, confidence = self.feedback_data.get(task_description, (rounds_used, 0))
if feedback == "too few": rounds = min(rounds + 1, MAX_ROUNDS) confidence = max(0, confidence - 1) # Decrease confidence on 'too few' feedback elif feedback == "too many": rounds = max(1, rounds - 1) confidence = max(0, confidence - 1) # Decrease confidence on 'too many' feedback elif feedback == "yes": confidence = min(confidence + 1, CONFIDENCE_THRESHOLD) # Increase confidence if feedback is "yes"
self.feedback_data[task_description] = (rounds, confidence) def execute_agent( self, agent: Dict, inputs: Dict, round_num: int, total_rounds: int ) -> Dict: """Execute individual agent with appropriate prompting.""" system_prompt = self.create_system_prompt(round_num, total_rounds) # Construct context from connected agents' results context = "Previous inputs:\n" for idx, result in inputs["connected_results"].items(): context += f"- From {result['role']}: {result['response']}\n" prompt = f"""System: {system_prompt} Query: {inputs['query']} {context} Based on your role as {agent['role']}, provide your response:""" # This would be replaced with actual GPT-4 API call response = { "role": agent["role"], "response": f"Processed input for {agent['role']} in round {round_num}" } return response
def execute_query(self, query: str, agent_specs: List[Dict], initial_rounds: int) -> str: """Execute query using agents, reusing previous agents if available and adjusting rounds based on feedback.""" # Check if agents for a similar task exist task = self.load_agents_for_task(query) if task: agents = task.agents max_rounds = task.suggested_rounds else: # Initialize agents based on given specifications agents = [SpecializedAgent(spec["base"], spec["role"], spec["plugins"]) for spec in agent_specs] # Adjust rounds based on feedback, capped at MAX_ROUNDS max_rounds = self.get_feedback_adjusted_rounds(query, initial_rounds) # Save agents and adjusted rounds for future reuse self.save_agents_for_task(query, agents, max_rounds) print(f"Executing query: {query} with {max_rounds} rounds.") for agent in agents: print(f"Agent: {agent.get_description()}") # Check if agents for a similar task exist agents = self.load_agents_for_task(query) if not agents: # Initialize agents based on given specifications agents = [SpecializedAgent(spec["base"], spec["role"], spec["plugins"]) for spec in agent_specs] #Reuse and Save agents code. # Save agents for future reuse self.save_agents_for_task(query, agents) # Generate communication topology topology = self.g_designer(agents, query) dialogue_history = [] current_state = {"query": query, "intermediate_results": {}} for round_num in range(max_rounds): # Get execution order for this round execution_order = self.determine_execution_order(topology) round_outputs = DialogueRound(round_num=round_num, agent_outputs={}) # Execute agents in order for agent_idx in execution_order: agent = agents[agent_idx] inputs = self.gather_agent_inputs(agent_idx, topology, current_state) result = self.execute_agent( agent, inputs, round_num, max_rounds ) round_outputs.agent_outputs[agent_idx] = result current_state["intermediate_results"][agent_idx] = result dialogue_history.append(round_outputs) # Final aggregation using summarizer agent final_answer = self.aggregate_results(dialogue_history, query) # Collect feedback from user (or other source) on the adequacy of rounds used feedback = input(f"Were the {max_rounds} rounds sufficient for '{query}'? (yes, too few, too many): ").strip().lower() self.record_feedback(query, max_rounds, feedback) return final_answer def aggregate_results( self, dialogue_history: List[DialogueRound], query: str ) -> str: """Aggregate results using a dedicated summarizer agent.""" summarizer_prompt = self.create_summarizer_prompt(dialogue_history, query) # This would be replaced with actual GPT-4 API call with temperature=0 # The implementation would use the OpenAI API with the following settings: # { # "model": "gpt-4-1106-preview", # "temperature": 0, # "messages": [{"role": "system", "content": summarizer_prompt}] # } final_summary = "Aggregated response from summarizer agent based on dialogue history" return final_summary def determine_execution_order(self, topology: torch.Tensor) -> List[int]: """Determine agent execution order based on topology (implementation unchanged).""" # Using the existing implementation from the original code return super().determine_execution_order(topology) def gather_agent_inputs( self, agent_idx: int, topology: torch.Tensor, current_state: Dict ) -> Dict: """Gather inputs from connected agents (implementation unchanged).""" # Using the existing implementation from the original code return super().gather_agent_inputs(agent_idx, topology, current_state)#This function doesn't do anything. #def generate_agent_specs(task_description: str) -> List[Dict]: #Need to use Final FLM model here for the LLM agents and spawner and probably also create some additional code so that all agents have access to the knowledge graph agents with shared knowledge (except the mutable one which is only for the spawner LLM). #"""Generate agent specifications based on the task using an LLM.""" # Hypothetical call to LLM to generate roles and plugins # This should be replaced with a real LLM call in practice # For example: `openai.ChatCompletion.create(model="gpt-4", messages=[{"role": "user", "content": f"Define agents for: {task_description}"}])` # Mock response simulating LLM output - Will need to change this so the LLM can store the Agent information here. # llm_response = [ # {"base": "gpt-4", "role": "Mathematician", "plugins": ["calculator", "equation_solver"]}, # {"base": "gpt-4", "role": "Programmer", "plugins": ["code_compiler", "debugger"]}, # {"base": "gpt-4", "role": "Physics Expert", "plugins": ["physics_simulator"]} # ] # Simulate complexity analysis response # suggested_rounds = 4 if "complex" in task_description.lower() else 2 #print(f"LLM generated agent specifications for task '{task_description}': {llm_response}") # print(f"Suggested rounds for task '{task_description}': {suggested_rounds}") # return llm_response, suggested_rounds
def get_user_task_description() -> str: """Prompt user for a task description.""" return input("Please describe the task you would like the AI to help with: ")import gradio as grimport os
def run_evaluation(): # Initialize components data_loader = ARCDataLoader() task_converter = ARCTaskConverter() g_designer = GDesigner() mas = MultiAgentSystem(g_designer) evaluator = ARCEvaluator() # Load all ARC tasks tasks = data_loader.load_all_tasks() # Initialize progress tracking progress_text = "" total_tasks = len(tasks) current_task = 0 for task in tasks: current_task += 1 progress_text += f"Processing task {current_task}/{total_tasks}: {task['filename']}\n" yield progress_text # Update progress in real-time # Convert ARC task to agent-compatible format task_description = task_converter.create_task_description(task['data']) # Generate agent specifications for this task agent_specs, suggested_rounds = generate_agent_specs(task_description) # Execute task with multi-agent system for test_pair in task['data']['test']: success = False trials_used = 0 while trials_used < evaluator.max_trials and not success: result = mas.execute_query( query=task_description + "\n\nCurrent test input:\n" + task_converter.grid_to_text(test_pair['input']), agent_specs=agent_specs, initial_rounds=suggested_rounds ) try: predicted_grid = parse_result_to_grid(result) success = evaluator.evaluate_output( predicted_grid, test_pair['output'] ) except: success = False trials_used += 1 evaluator.record_result(task['filename'], success, trials_used) # Generate final summary summary = evaluator.get_summary() final_report = f"""Evaluation Complete!
Summary:- Total tasks: {summary['total_tasks']}- Successful tasks: {summary['successful_tasks']}- Success rate: {summary['success_rate']:.2%}- Average trials per task: {summary['average_trials']:.2f}""" yield final_report
def create_gradio_interface(): with gr.Blocks() as demo: gr.Markdown("# ARC Task Evaluation System") with gr.Row(): start_button = gr.Button("Start Evaluation") output_text = gr.TextArea( label="Progress and Results", value="Click 'Start Evaluation' to begin...", lines=10, max_lines=20 ) start_button.click( fn=run_evaluation, outputs=output_text ) return demo
if __name__ == "__main__": demo = create_gradio_interface() demo.queue() demo.launch()app,pyAdded+1298