Spaces:
Build error
Build error
Update app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472485 unmodified lines2542552562572582592602612622632642 unmodified lines2672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803818 unmodified lines3903913923933943953962 unmodified lines39940040140240340440510 unmodified lines416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813792 unmodified lines13821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923import torchimport torch.nn as nnimport picklefrom datetime import datetimeimport torch.nn.functional as Ffrom torch_geometric.nn import GCNConvfrom typing import List, Dict, Tuple, Optional, Any, Unionfrom sentence_transformers import SentenceTransformerimport jsonimport gcimport numpy as npimport osimport signalimport sysimport timeimport statistics#import spacesimport gradio as grfrom typing import Iteratorfrom dataclasses import dataclass# Initialize optimizer - Fixed by importing torch.optim and using torch's Adam optimizerfrom torch.optim import Adamfrom transformers import AutoModelForCausalLM, AutoTokenizerimport torchfrom typing import List, Dict, Tuple, Optional, Anyfrom dataclasses import dataclass'''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.'''MAX_ROUNDS = 3# Threshold for confidence level to stop querying LLMCONFIDENCE_THRESHOLD = 3class ARCDataLoader:"""Handles loading and processing of ARC task data."""JSON_directory='./evaluation'def __init__(self, base_path: str = JSON_directory):self.base_path = base_pathif 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 Noneif not os.path.exists(file_path):print(f"File not found: {file_path}")return Noneif not os.access(file_path, os.R_OK):print(f"No read permission for file: {file_path}")return Nonewith open(file_path, 'r') as f:data = json.load(f)# Validate the expected structureif not isinstance(data, dict):print(f"Invalid data structure in {file_path}: not a dictionary")return Noneif '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 listsif 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 Nonereturn dataexcept json.JSONDecodeError:print(f"Invalid JSON format in file: {file_path}")return Noneexcept Exception as e:print(f"Unexpected error reading {file_path}: {str(e)}")return Nonedef 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'):continuefile_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 tasksdef 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 Falseif not all(isinstance(row, list) for row in example['input'] + example['output']):return Falseif not all(isinstance(val, int) for row in example['input'] + example['output'] for val in row):return Falsereturn Trueexcept (KeyError, TypeError):return Falseclass 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 0return 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 0out_rows, out_cols = len(output_grid), len(output_grid[0]) if output_grid else 0pattern = f"Transform {in_rows}x{in_cols} grid into {out_rows}x{out_cols} grid.\n"# Detect basic patternsif 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 patterndef 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 pairsdescription = "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 descriptionclass ARCEvaluator:"""Evaluates agent system performance on ARC tasks."""def __init__(self, max_trials: int = 3):self.max_trials = max_trialsself.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 Falsereturn 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 0return {'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' dataReturns: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' gridsReturns: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_gridclass SpecializedAgent:"""Represents an agent with specific roles and specializations."""def __init__(self, base_model: str, role: str, plugins: List[str]):self.base = base_modelself.role = roleself.plugins = pluginsdef get_description(self) -> str:"""Get a formatted description of the agent."""return f"Base: {self.base}, Role: {self.role}, Plugins: {', '.join(self.plugins)}"def to_dict(self) -> Dict[str, Any]:"""Convert agent to dictionary format."""return {"base": self.base,"role": self.role,"plugins": self.plugins}class GDesigner(nn.Module):def __init__(self,5 unmodified lineslearning_rate: float = 0.001,checkpoint_dir: str = "./checkpoints"):super().__init__()# Set device consistentlyself.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")print(f"Using device: {self.device}")# Initialize components and move them to deviceself.node_encoder = NodeEncoder(input_dim).to(self.device)self.graph_encoder = GCNEncoder(input_dim, hidden_dim, latent_dim).to(self.device)self.graph_decoder = GraphDecoder(latent_dim, hidden_dim).to(self.device)2 unmodified linesself.sparsity_factor = sparsity_factorself.optimizer = Adam(self.parameters(), lr=learning_rate)# Add experience buffer for learningself.experience_buffer = []self.performance_history = {}self.checkpoint_dir = checkpoint_dirif not os.path.exists(checkpoint_dir):os.makedirs(checkpoint_dir)# Load previous experiences and model state if they existself.load_checkpoint()# Move entire model to deviceself.to(self.device)def learn_from_experience(self, task_description: str, agents: List[SpecializedAgent],success: bool, execution_time: float, feedback: Dict):"""Learn from task execution experience"""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 update_model_from_experience(self):"""Update model parameters based on accumulated experience"""if len(self.experience_buffer) < 5: # Wait for minimum experiencesreturn# Extract successful patternssuccessful_experiences = [exp for exp in self.experience_buffer if exp['success']]if not successful_experiences:returnself.train()total_loss = 0for experience in successful_experiences:# Convert experience to training dataagents = [SpecializedAgent(**agent_dict) for agent_dict in experience['agents']]task = experience['task']target_topology = experience['topology']if target_topology is not None:# Forward passnode_features, task_features = self.encode_agents(agents, task)mu, log_std = self.graph_encoder(node_features, self.create_anchor_topology(len(agents)))# Compute lossloss = self.compute_loss(mu, log_std, target_topology,self.create_anchor_topology(len(agents)))# Backward passself.optimizer.zero_grad()loss.backward()torch.nn.utils.clip_grad_norm_(self.parameters(), max_norm=1.0)self.optimizer.step()total_loss += loss.item()# Update performance metricsavg_loss = total_loss / len(successful_experiences)self.performance_history[len(self.performance_history)] = avg_lossdef forward(self, agents: List[Dict], query: str, edge_index: Optional[torch.Tensor] = None) -> torch.Tensor:"""Forward pass for the entire graph design and agent encoding process."""# Encode agents and query into node featuresnode_features, task_features = self.encode_agents(agents, query)# Create anchor topology if not providedif edge_index is None:anchor_topology = self.create_anchor_topology(len(agents))edge_index = anchor_topology.nonzero().t().to(self.device)else:edge_index = edge_index.to(self.device)# Pass node features through graph encodermu, log_std = self.graph_encoder(node_features, edge_index)# Sample latent variablesstd = torch.exp(log_std)eps = torch.randn_like(std).to(self.device)z = mu + eps * std# Pass the latent variables and task features through the graph decoderoutput = self.graph_decoder(z, task_features)return outputdef create_anchor_topology(self, num_agents: int) -> torch.Tensor:"""Create default chain structure anchor topology."""topology = torch.zeros((num_agents, num_agents)).to(self.device)for i in range(num_agents-1):topology[i, i+1] = 1topology[i+1, i] = 1return topologydef save_checkpoint(self):"""Save model state, experiences, and performance history"""timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")checkpoint_path = os.path.join(self.checkpoint_dir, f"gdesigner_checkpoint_{timestamp}")# Move model state to CPU before savingcpu_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 vfor k, v in self.optimizer.state_dict().items()}8 unmodified linespickle.dump(self.experience_buffer, f)def load_checkpoint(self):"""Load most recent checkpoint if it exists"""try:checkpoints = [f for f in os.listdir(self.checkpoint_dir) if f.endswith('_model.pt')]if not checkpoints:2 unmodified lineslatest_checkpoint = max(checkpoints)checkpoint_base = latest_checkpoint.replace('_model.pt', '')# Load checkpoint to appropriate devicecheckpoint = torch.load(os.path.join(self.checkpoint_dir, latest_checkpoint),map_location=self.device10 unmodified linesprint(f"Error loading checkpoint: {str(e)}")self.experience_buffer = []self.performance_history = {}def encode_agents(self,agents: List[Union[Dict, SpecializedAgent]],query: str) -> Tuple[torch.Tensor, torch.Tensor]:"""Encode agents and query into node features."""agent_features = []for agent in agents:if isinstance(agent, dict):text = f"Base: {agent['base']}, Role: {agent['role']}, Plugins: {', '.join(agent['plugins'])}"else: # SpecializedAgent instancetext = 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_featuresdef 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 VAEkl_loss = -0.5 * torch.sum(1 + 2 * log_std - mu.pow(2) - torch.exp(2 * log_std))# 2. Reconstruction lossif ground_truth is not None:recon_loss = F.binary_cross_entropy(S, ground_truth)else:# If no ground truth, use anchor topology as soft targetrecon_loss = F.binary_cross_entropy(S, anchor_topology)# 3. Sparsity losssparsity_loss = torch.norm(S, p=1) # L1 norm for sparsity# 4. Structural loss to maintain essential connections from anchor topologystructural_loss = F.mse_loss(S * anchor_topology, anchor_topology)# Combine losses with weightstotal_loss = (kl_loss * 0.1 + # KL weightrecon_loss * 1.0 + # Reconstruction weightsparsity_loss * self.sparsity_factor + # Sparsity weightstructural_loss * 0.5 # Structural weight)return total_lossdef update_parameters(self, loss: torch.Tensor):"""Update model parameters using computed loss."""self.optimizer.zero_grad()loss.backward()# Gradient clipping to prevent exploding gradientstorch.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 topologyanchor_topology = self.create_anchor_topology(len(agents))# Forward passnode_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 * stdS = self.graph_decoder(z, task_features)# Compute lossloss = self.compute_loss(mu, log_std, S, anchor_topology, ground_truth)# Update parametersself.update_parameters(loss)return S, lossdef 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.0num_batches = 0# Create batchesfor i in range(0, len(training_data), batch_size):batch = training_data[i:i + batch_size]batch_loss = 0.0# Process each item in batchfor 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_lossnum_batches += 1epoch_loss = total_loss / num_batchesprint(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}")# Validation stepif validation_data is not None:self.eval()with torch.no_grad():val_loss = 0.0for 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 * stdS = 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 providedif anchor_topology is None:anchor_topology = self.create_anchor_topology(len(agents))# Encode agents and querynode_features, task_features = self.encode_agents(agents, query)edge_index = anchor_topology.nonzero().t()# Generate topologymu, log_std = self.graph_encoder(node_features, edge_index)std = torch.exp(log_std)eps = torch.randn_like(std)z = mu + eps * stdS = self.graph_decoder(z, task_features)# Apply sparsification and refinementS = (S / self.temperature).softmax(dim=-1)mask = torch.bernoulli(S)S = S * maskif self.sparsity_factor > 0:S = self.apply_sparsity(S, anchor_topology)return Sdef 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.5S_final = alpha * S_refined + (1 - alpha) * anchorreturn S_finalclass NodeEncoder(nn.Module):def __init__(self, input_dim):super().__init__()self.encoder = SentenceTransformer('all-MiniLM-L6-v2')self.linear = nn.Linear(384, input_dim) # MiniLM outputs 384-dim vectorsdef 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]:"""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_stdclass 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.devicerows = 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 layersself.conv1 = GCNConv(1, 16)self.conv2 = GCNConv(16, 16)self.conv3 = GCNConv(16, 1)# Graph design componentsself.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 = temperatureself.sparsity_factor = sparsity_factor# Initialize optimizer - Fixed by importing torch.optim and using torch's Adam optimizerfrom torch.optim import Adamself.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 xdef 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_griddef _create_grid_edges(self, shape: Tuple[int, ...]) -> torch.Tensor:"""Create edge connections for grid structure"""edges = []rows, cols = shapefor i in range(rows):for j in range(cols):if j < cols - 1: # horizontal connectionsedges.append((i * cols + j, i * cols + j + 1))if i < rows - 1: # vertical connectionsedges.append((i * cols + j, (i + 1) * cols + j))edges = torch.tensor(edges, dtype=torch.long).t()return edgesdef 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] = 1topology[i+1, i] = 1return topologydef encode_agents(self,agents: List[Union[Dict, SpecializedAgent]],query: str) -> Tuple[torch.Tensor, torch.Tensor]:"""Encode agents and query into node features."""agent_features = []for agent in agents:if isinstance(agent, dict):text = f"Base: {agent['base']}, Role: {agent['role']}, Plugins: {', '.join(agent['plugins'])}"else: # SpecializedAgent instancetext = 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_featuresdef 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_lossdef 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 = 0total_graph_loss = 0# Train on grid datafor 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 designnode_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 gradientstorch.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 topologyanchor_topology = self.create_anchor_topology(len(agents))# Forward passnode_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 * stdS = self.graph_decoder(z, task_features)# Compute lossloss = self.compute_loss(mu, log_std, S, anchor_topology, ground_truth)# Update parametersself.update_parameters(loss)return S, lossdef 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.0num_batches = 0# Create batchesfor i in range(0, len(training_data), batch_size):batch = training_data[i:i + batch_size]batch_loss = 0.0# Process each item in batchfor 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_lossnum_batches += 1epoch_loss = total_loss / num_batchesprint(f"Epoch {epoch+1}/{num_epochs}, Loss: {epoch_loss:.4f}")# Validation stepif validation_data is not None:self.eval()with torch.no_grad():val_loss = 0.0for 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 * stdS = 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 providedif anchor_topology is None:anchor_topology = self.create_anchor_topology(len(agents))# Encode agents and querynode_features, task_features = self.encode_agents(agents, query)edge_index = anchor_topology.nonzero().t()# Generate topologymu, log_std = self.graph_encoder(node_features, edge_index)std = torch.exp(log_std)eps = torch.randn_like(std)z = mu + eps * stdS = self.graph_decoder(z, task_features)# Apply sparsification and refinementS = (S / self.temperature).softmax(dim=-1)mask = torch.bernoulli(S)S = S * maskif self.sparsity_factor > 0:S = self.apply_sparsity(S, anchor_topology)return Sdef 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.5S_final = alpha * S_refined + (1 - alpha) * anchorreturn S_final@dataclassclass DialogueRound:"""Structure to track dialogue history within a round."""round_number: intagent_outputs: Dict[int, Dict[str, Any]]aggregated_result: Optional[str] = Noneclass Task:"""Represents a user task and stores associated agents for potential reuse."""description: stragents: List[SpecializedAgent]suggested_rounds: int # Track suggested rounds from LLM or systemdef generate_llm_response(prompt: str, max_length: int = 3000, truncation=True, padding='max_length') -> str:"""Use DynamicLLM instance directly"""return llm.generate_response(prompt, max_length=max_length)def generate_agent_specs(task_description: str) -> Tuple[List[Dict], int]:"""Use DynamicLLM for boss role"""return llm.generate_response(prompt=create_boss_prompt(task_description),role="boss",context={"task": task_description})def parse_result_to_grid(result: str) -> List[List[int]]:"""Convert LLM output to grid format"""try:# Extract grid-like structure from the result stringlines = [line.strip() for line in result.split('\n') if line.strip()]grid = []for line in lines:# Convert space-separated numbers to list of integersrow = [int(num) for num in line.split() if num.isdigit()]if row: # Only add non-empty rowsgrid.append(row)return gridexcept Exception as e:raise ValueError(f"Failed to parse result into grid: {str(e)}")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 your response concise and adhere 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 effectively2. Specify how many discussion rounds (1-8) these agents need to solve the problemConsider 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]"""@dataclassclass DialogueRound:round_num: intagent_outputs: Dict[int, Dict]@dataclassclass Task:description: stragents: List[Any] # SpecializedAgentsuggested_rounds: intclass RoleLearningManager:"""Manages separate learning experiences for different roles"""def __init__(self, checkpoint_dir: str = "./role_checkpoints"):self.checkpoint_dir = checkpoint_dirself.role_experiences = {'boss': [],'agent1': [],'agent2': [],'agent3': [],'summarizer': []}self.load_experiences()def save_experience(self, role: str, experience: Dict):"""Save learning experience for specific role"""self.role_experiences[role].append(experience)self.save_checkpoint(role)def get_role_experience(self, role: str) -> List[Dict]:"""Get learned experiences for a specific role"""return self.role_experiences.get(role, [])def save_checkpoint(self, role: str):"""Save role-specific checkpoint"""os.makedirs(self.checkpoint_dir, exist_ok=True)path = os.path.join(self.checkpoint_dir, f"{role}_experience.pkl")with open(path, 'wb') as f:pickle.dump(self.role_experiences[role], f)def load_experiences(self):"""Load all role experiences from checkpoints"""for role in self.role_experiences.keys():path = os.path.join(self.checkpoint_dir, f"{role}_experience.pkl")if os.path.exists(path):with open(path, 'rb') as f:self.role_experiences[role] = pickle.load(f)class GPUMemoryManager:def __init__(self):self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# More aggressive memory settingsos.environ['PYTORCH_CUDA_ALLOC_CONF'] = ('max_split_size_mb:128,''expandable_segments:True,''garbage_collection_threshold:0.6')# Enable cuda memory statsif torch.cuda.is_available():torch.cuda.memory.set_per_process_memory_fraction(0.9) # Use 90% of available VRAMtorch.cuda.empty_cache()gc.collect()def optimize_memory(self):gc.collect()torch.cuda.empty_cache()if torch.cuda.is_available():torch.cuda.synchronize()def force_memory_release(self):"""Force release of CUDA memory"""if torch.cuda.is_available():torch.cuda.empty_cache()gc.collect()torch.cuda.synchronize()# Reset peak memory statstorch.cuda.reset_peak_memory_stats()# Clear any remaining tensorsfor obj in gc.get_objects():try:if torch.is_tensor(obj):del objexcept Exception:passclass DynamicLLM:def __init__(self, g_designer: GDesigner):self.memory_manager = GPUMemoryManager()self.model_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised"# More conservative model configurationself.model_config = {'torch_dtype': torch.float16,'low_cpu_mem_usage': True,'device_map': {'transformer.word_embeddings': 0,'transformer.final_layernorm': 0,'transformer.prefix_encoder': 0,'transformer.layers': 0},'max_memory': {0: '40GB'},'offload_folder': 'offload_folder','revision': 'main','load_in_8bit': True, # Use 8-bit quantization'use_cache': False # Disable KV cache to save memory}# Initialize in chunksself._initialize_model_in_chunks()self.g_designer = g_designerself.current_role = Noneself.learning_manager = RoleLearningManager()def _initialize_model_in_chunks(self):"""Initialize model in chunks to manage memory better"""try:print("Loading tokenizer...")self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)print("Preparing for model load...")self.memory_manager.force_memory_release()print("Loading model in chunks...")# Load model configuration firstconfig = AutoConfig.from_pretrained(self.model_name)# Load model in chunksself.model = Nonechunk_size = 1000000 # Adjust based on your GPUfor param_chunk in range(0, config.num_parameters, chunk_size):self.memory_manager.optimize_memory()if self.model is None:# First chunk - initialize modelself.model = AutoModelForCausalLM.from_pretrained(self.model_name,config=config,**self.model_config)else:# Load subsequent chunkschunk = AutoModelForCausalLM.from_pretrained(self.model_name,config=config,state_dict_chunk=slice(param_chunk, param_chunk + chunk_size),**self.model_config)# Merge chunksself.model.load_state_dict({**self.model.state_dict(), **chunk.state_dict()},strict=False)del chunkself.memory_manager.optimize_memory()print("Model loaded successfully")except Exception as e:print(f"Error during model initialization: {str(e)}")self.memory_manager.force_memory_release()raisedef switch_role(self, role: str, context: Dict = None):"""Switch LLM to a different role and load relevant experience"""self.current_role = roleexperiences = self.learning_manager.get_role_experience(role)# Create role-specific contextrole_context = f"""You are now acting as {role}.Your past experiences and learning in this role include:{self._format_experiences(experiences)}Additional context: {context if context else ''}"""return role_contextdef _format_experiences(self, experiences: List[Dict]) -> str:"""Format past experiences for context"""if not experiences:return "No previous experience in this role."recent_experiences = experiences[-5:] # Use last 5 experiencesformatted = "Recent experiences:\n"for exp in recent_experiences:formatted += f"- Task: {exp['task']}\n"formatted += f" Success: {exp['success']}\n"formatted += f" Learning: {exp['learning']}\n"return formatteddef generate_response(self, prompt: str, role: str = None, context: Dict = None) -> str:"""Generate response with memory management"""try:self.memory_manager.optimize_memory()# Check if we have enough memoryif not self.memory_manager.check_memory(required_memory_mb=1000): # Adjust value as neededprint("Warning: Low GPU memory. Optimizing...")self.memory_manager.optimize_memory()# Process input with memory managementwith torch.cuda.amp.autocast(): # Use automatic mixed precisioninputs = self.tokenizer(prompt, return_tensors="pt")inputs = {k: v.to(self.memory_manager.device) for k, v in inputs.items()}outputs = self.model.generate(**inputs,max_length=512,temperature=0.7,do_sample=True,pad_token_id=self.tokenizer.eos_token_id,num_return_sequences=1)response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)# Clean up memory after generationdel inputs, outputsself.memory_manager.optimize_memory()return responseexcept Exception as e:print(f"Error during response generation: {str(e)}")self.memory_manager.optimize_memory()raisedef switch_role(self, role: str, context: Dict = None):"""Switch roles with memory optimization"""self.memory_manager.optimize_memory()def learn_from_interaction(self, role: str, task: str, success: bool, learning: str):"""Record learning from interaction"""experience = {'task': task,'success': success,'learning': learning,'timestamp': datetime.now().isoformat()}self.learning_manager.save_experience(role, experience)class MultiAgentSystem:def __init__(self, g_designer: GDesigner, temperature: float = 1.0):self.g_designer = g_designerself.temperature = temperatureself.feedback_data = {}self.saved_tasks = {}self.current_agents = []self.checkpoint_interval = 10self.tasks_since_checkpoint = 0self.llm = DynamicLLM(g_designer)def generate_llm_response(self, prompt: str, max_length: int = 3000) -> str:"""Generate response using the DynamicLLM instance"""return self.llm.generate_response(prompt, max_length=max_length)def generate_agent_specs(self, task_description: str) -> Tuple[List[Dict], int]:"""Generate agent specifications using DynamicLLM in boss role"""boss_prompt = self._create_boss_prompt(task_description)response = self.llm.generate_response(prompt=boss_prompt,role="boss",context={"task": task_description})# Parse the response to extract agents and roundstry:agents_section, rounds_section = response.split("ROUNDS:")# Parse agentsagent_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 agentslines = 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": self.llm.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 3while len(agent_specs) < 3:agent_specs.append({"base": self.llm.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-8except Exception as e:print(f"Error parsing LLM response: {e}")# Fallback default configurationreturn [{"base": self.llm.model_name, "role": "Analyst", "specialty": "Data analysis", "plugins": ["data_analysis"]},{"base": self.llm.model_name, "role": "Researcher", "specialty": "Information gathering", "plugins": ["knowledge_base"]},{"base": self.llm.model_name, "role": "Expert", "specialty": "Domain expertise", "plugins": ["domain_expertise"]}], 3return agent_specs[:3], roundsdef analyze_performance(self) -> Dict:"""Analyze system performance over time"""return {'learning_curve': self.g_designer.performance_history,'success_rate': sum(1 for exp in self.g_designer.experience_buffer if exp['success']) /len(self.g_designer.experience_buffer) if self.g_designer.experience_buffer else 0,'average_execution_time': statistics.mean(exp['execution_time']for exp in self.g_designer.experience_buffer)if self.g_designer.experience_buffer else 0}def determine_execution_order(self, topology: torch.Tensor) -> List[int]:"""Need proper implementation instead of super() call"""# Suggested implementation:node_scores = topology.sum(dim=1)return torch.argsort(node_scores, descending=True).tolist()def gather_agent_inputs(self, agent_idx: int, topology: torch.Tensor, current_state: Dict) -> Dict:"""Need proper implementation instead of super() call"""# Suggested implementation:connected_agents = (topology[agent_idx] > 0).nonzero().squeeze(1)connected_results = {idx: current_state["intermediate_results"].get(idx.item(), {})for idx in connected_agents}return {"query": current_state["query"],"connected_results": connected_results}def execute_query(self, query: str, agent_specs: List[Dict], initial_rounds: int) -> str:self.current_task = query# First act as boss to plan the interactionboss_response = self.llm.generate_response(prompt=self._create_boss_prompt(query),role="boss",context={"task_history": self.g_designer.experience_buffer})# Execute each agent in sequenceresults = []for idx, agent in enumerate(agent_specs):agent_role = f"agent{idx+1}"agent_context = {"previous_results": results,"agent_spec": agent}response = self.llm.generate_response(2 unmodified linescontext=agent_context)results.append(response)# Learn from interactionself.llm.learn_from_interaction(role=agent_role,task=query,success=self._evaluate_response(response),learning=self._extract_learning(response))# Finally, summarize resultsfinal_answer = self.llm.generate_response(prompt=self._create_summary_prompt(results),role="summarizer",context={"all_results": results})return final_answerdef _create_boss_prompt(self, query: str) -> str:# Get relevant experiences from g_designerboss_experiences = self.g_designer.experience_buffersuccess_patterns = [exp for exp in boss_experiences if exp['success']]# Extract learning patterns specific to task planningplanning_context = self._extract_planning_patterns(success_patterns)return f"""As the boss AI, analyze this task and plan the agent interaction:Task: {query}Previous successful planning patterns:{planning_context}Based on these learned patterns and the current task:1. Analyze the task requirements2. Determine optimal agent roles and specializations3. Plan the interaction flow4. Consider potential challenges based on past experiences"""def _create_agent_prompt(self, agent: Dict, previous_results: List[str]) -> str:# Get role-specific experiencesrole_experiences = [exp for exp in self.g_designer.experience_bufferif exp.get('agent_role') == agent['role']]# Extract relevant learning for this rolerole_learning = self._extract_role_learning(role_experiences, agent['role'])return f"""As {agent['role']}, address this task based on your specialized knowledge.Your past successful approaches:{role_learning}Previous agent outputs in current task:{self._format_previous_results(previous_results)}Apply your learned patterns while considering:1. Your specific role expertise2. The context from previous agents3. Past successful strategies4. Potential improvements based on previous attempts"""def _create_summary_prompt(self, results: List[str]) -> str:# Get successful summarization patternssummary_experiences = [exp for exp in self.g_designer.experience_bufferif exp.get('role') == 'summarizer' and exp['success']]summary_patterns = self._extract_summary_patterns(summary_experiences)return f"""Synthesize the following agent outputs into a final response.Previous successful synthesis patterns:{summary_patterns}Agent outputs to synthesize:{self._format_results(results)}Create a comprehensive response that:1. Integrates all agent contributions2. Resolves any contradictions3. Applies successful patterns from past experiences4. Ensures consistency and completeness"""def _extract_planning_patterns(self, experiences: List[Dict]) -> str:patterns = []for exp in experiences[-5:]: # Use last 5 successful experiencespatterns.append(f"""Task: {exp['task_description']}Successful approach: {exp['planning_strategy']}Key factors: {exp['success_factors']}Performance metrics: {exp['performance_metrics']}""")return "\n".join(patterns)def _extract_role_learning(self, experiences: List[Dict], role: str) -> str:role_patterns = []for exp in experiences[-3:]: # Use last 3 experiences for this rolerole_patterns.append(f"""Task: {exp['task_description']}Approach: {exp['approach']}Success: {exp['success']}Key learnings: {exp['learning_points']}""")return "\n".join(role_patterns)def _extract_summary_patterns(self, experiences: List[Dict]) -> str:summary_patterns = []for exp in experiences[-3:]:summary_patterns.append(f"""Context: {exp['context']}Integration strategy: {exp['integration_strategy']}Success factors: {exp['success_factors']}""")return "\n".join(summary_patterns)def learn_from_interaction(self, role: str, task: str, response: str, success: bool):"""Enhanced learning function that integrates with g_designer"""# Extract learning points from responselearning_points = self._extract_learning_points(response)# Create experience recordexperience = {'role': role,'task_description': task,'approach': response,'success': success,'learning_points': learning_points,'timestamp': datetime.now().isoformat()}# Add role-specific metricsif role == 'boss':experience['planning_strategy'] = self._extract_planning_strategy(response)experience['success_factors'] = self._extract_success_factors(response)elif role == 'summarizer':experience['integration_strategy'] = self._extract_integration_strategy(response)# Update g_designer's experience bufferself.g_designer.learn_from_experience(task_description=task,agents=self.current_agents,success=success,execution_time=time.time() - self.start_time,feedback={'role_specific_learning': experience})# Update role-specific learning bufferself.llm.role_specific_buffers[role].append(experience)return experiencedef _extract_learning_points(self, response: str) -> List[str]:"""Extract key learning points from response using existing mechanisms"""# Implement using g_designer's learning extraction methodsreturn self.g_designer.extract_learning_points(response)def _format_previous_results(self, results: List[str]) -> str:"""Format previous results with learned patterns"""formatted = []for idx, result in enumerate(results):formatted.append(f"""Agent {idx + 1} Output:{result}Key Points: {self._extract_key_points(result)}""")return "\n".join(formatted)def _format_results(self, results: List[str]) -> str:"""Format results with integration patterns"""return "\n".join([f"Agent {idx + 1} Contribution:\n{result}\n"for idx, result in enumerate(results)])def get_feedback_adjusted_rounds(self, task_description: str, initial_rounds: int) -> int:"""Adjust round count based on historical feedback and confidence."""rounds, confidence = self.feedback_data.get(task_description, (initial_rounds, 0))if confidence >= CONFIDENCE_THRESHOLD:return min(rounds, MAX_ROUNDS)else:return min(initial_rounds, MAX_ROUNDS)def save_agents_for_task(self, task_description: str, agents: List[Any], 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 record_feedback(self, task_description: str, rounds_used: int, feedback: str):"""Record feedback to refine round estimates."""current_rounds, confidence = self.feedback_data.get(task_description, (rounds_used, 0))if feedback == "too few":rounds = min(current_rounds + 1, MAX_ROUNDS)confidence = max(0, confidence - 1)elif feedback == "too many":rounds = max(1, current_rounds - 1)confidence = max(0, confidence - 1)elif feedback == "yes":rounds = current_roundsconfidence = min(confidence + 1, CONFIDENCE_THRESHOLD)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 Chocolatine model."""system_prompt = self.create_system_prompt(round_num, total_rounds)context = "Previous inputs:\n"for idx, result in inputs.get("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:"""# Generate response using Chocolatine modelinputs = tokenizer(prompt, return_tensors="pt")outputs = model.generate(**inputs,max_length=512,temperature=self.temperature,do_sample=True)response_text = tokenizer.decode(outputs[0], skip_special_tokens=True)response = {"role": agent["role"],"response": response_text}return responsedef 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 agentsand 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 keypoints 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 agentsregarding the query: "{query}"Consider the following dialogue history across {len(dialogue_history)} rounds:"""for round in dialogue_history:prompt += f"\nRound {round.round_num}:\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 promptdef aggregate_results(self, dialogue_history: List[DialogueRound], query: str) -> str:"""Aggregate results using the Chocolatine summarizer agent."""summarizer_prompt = self.create_summarizer_prompt(dialogue_history, query)# Generate summary using Chocolatine modelinputs = tokenizer(summarizer_prompt, return_tensors="pt")outputs = model.generate(**inputs,max_length=1024,temperature=0.0, # Use temperature 0 for more deterministic summarizationdo_sample=False)final_summary = tokenizer.decode(outputs[0], skip_special_tokens=True)return final_summarydef 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 codereturn 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 codereturn super().gather_agent_inputs(agent_idx, topology, current_state)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: ")def run_evaluation(progress=gr.Progress()) -> Iterator[str]:try:# Initialize componentsdata_loader = ARCDataLoader()task_converter = ARCTaskConverter()g_designer = GDesigner(checkpoint_dir="./checkpoints")mas = MultiAgentSystem(g_designer)evaluator = ARCEvaluator()# Load all ARC taskstasks = data_loader.load_all_tasks()# Initialize progress trackingtotal_tasks = len(tasks)current_task = 0# Initialize progress barprogress(0, desc="Starting evaluation...")progress_text = "Starting evaluation...\n"yield progress_textperformance_history = []for task in tasks:current_task += 1progress_text = f"Processing task {current_task}/{total_tasks}: {task['filename']}\n"progress(current_task / total_tasks, desc=f"Processing task {current_task}/{total_tasks}")# Record performance after each taskperformance = mas.analyze_performance()performance_history.append(performance)# Log learning progressprogress_text += f"\nLearning progress:"progress_text += f"\n- Success rate: {performance['success_rate']:.2%}"progress_text += f"\n- Average execution time: {performance['average_execution_time']:.2f}s"yield progress_text# Convert ARC task to agent-compatible formattask_description = task_converter.create_task_description(task['data'])# Generate agent specifications for this taskagent_specs, suggested_rounds = generate_agent_specs(task_description)# Execute task with multi-agent system for each test pair in the datasetfor test_pair in task['data']['test']:success = Falsetrials_used = 0while 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 Exception as e:print(f"Error processing task {task['filename']} with test pair {test_pair['input']}: {str(e)}")success = Falsetrials_used += 1evaluator.record_result(task['filename'], success, trials_used)# Generate final summarysummary = evaluator.get_summary()final_report = f"""Evaluation Complete!Results Summary:{summary}"""# Add learning curves to final reportfinal_report += "\n\nLearning Progress:"final_report += f"\nFinal success rate: {performance_history[-1]['success_rate']:.2%}"final_report += f"\nExecution time improvement: {((performance_history[0]['average_execution_time'] - performance_history[-1]['average_execution_time']) / performance_history[0]['average_execution_time']):.2%}"yield f"Finished task {current_task}/{total_tasks}: {task['filename']}\n"# Generate final summarysummary = evaluator.get_summary()final_report = f"""Evaluation Complete!FSummary:- Total tasks: {summary['total_tasks']}- Successful tasks: {summary['successful_tasks']}- Success rate: {summary['success_rate']:.2%}- Average trials per task: {summary['average_trials']:.2f}"""progress(1.0, desc="Evaluation complete")yield final_reportexcept Exception as e:error_message = f"Error during evaluation: {str(e)}"print(error_message)yield error_messageif 'g_designer' in locals():g_designer.save_checkpoint()def signal_handler(sig, frame):print("\nSaving checkpoint before exit...")g_designer.save_checkpoint()print("Checkpoint saved. Exiting...")sys.exit(0)def verify_system_setup(g_designer: GDesigner):"""Verify tensor device consistency and learning persistence"""print("\n=== System Verification ===")# 1. Check device consistencydevice = g_designer.deviceprint(f"Main device: {device}")all_parameters = list(g_designer.parameters())devices = {param.device for param in all_parameters}print(f"Found devices for parameters: {devices}")if len(devices) > 1:raise RuntimeError(f"Inconsistent devices found: {devices}")# 2. Verify components are on correct deviceprint("\nComponent Device Check:")print(f"Node Encoder: {next(g_designer.node_encoder.parameters()).device}")print(f"Graph Encoder: {next(g_designer.graph_encoder.parameters()).device}")print(f"Graph Decoder: {next(g_designer.graph_decoder.parameters()).device}")# 3. Test learning persistencetest_task = "Test task for verification"test_agents = [SpecializedAgent("test_model", "test_role", ["test_plugin"])for _ in range(3)]# Record initial stateinitial_buffer_size = len(g_designer.experience_buffer)print(f"\nInitial experience buffer size: {initial_buffer_size}")# Add test experienceg_designer.learn_from_experience(task_description=test_task,agents=test_agents,success=True,execution_time=1.0,feedback={"test": "feedback"})# Save checkpointg_designer.save_checkpoint()# Create new instance and load checkpointnew_g_designer = GDesigner(checkpoint_dir=g_designer.checkpoint_dir)# Verify persistenceprint(f"New experience buffer size: {len(new_g_designer.experience_buffer)}")if len(new_g_designer.experience_buffer) <= initial_buffer_size:print("WARNING: Learning persistence may not be working correctly!")else:print("Learning persistence verified successfully!")print("\n=== Verification Complete ===")return Truedef 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 demoif __name__ == "__main__":try:# Clear any existing CUDA memoryif torch.cuda.is_available():torch.cuda.empty_cache()gc.collect()# Initialize memory managermemory_manager = GPUMemoryManager()print("Initializing GPU memory management...")memory_manager.optimize_memory()# Create single LLM instanceprint("Creating single LLM instance...")llm = DynamicLLM(None)# Initialize g_designer with the existing LLM instanceprint("Initializing g_designer...")g_designer = GDesigner()llm.g_designer = g_designer# Create MultiAgentSystem using the existing LLM instanceprint("Initializing MultiAgentSystem...")mas = MultiAgentSystem(g_designer)# Monitor memory usagestats = memory_manager.get_memory_stats()print(f"\nCurrent GPU memory stats:")print(f"Allocated: {stats['allocated']:.2f} MB")print(f"Cached: {stats['cached']:.2f} MB")print(f"Peak: {stats['max_allocated']:.2f} MB")if memory_manager.check_memory(required_memory_mb=1000):demo = create_gradio_interface()demo.queue()demo.launch(server_name="0.0.0.0",share=True,debug=True)else:print("Error: Insufficient GPU memory for launch")sys.exit(1)except Exception as e:1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791805 unmodified lines1861871881891901911921932 unmodified lines1961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442458 unmodified lines2542552562572582592 unmodified lines26226326426526626710 unmodified lines2782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274282 unmodified lines431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509import torchimport torch.nn as nnimport torch.nn.functional as Ffrom torch_geometric.nn import GCNConvimport gcimport osimport jsonimport pickleimport signalimport sysimport timeimport statisticsimport gradio as grfrom datetime import datetimefrom typing import Dict, List, Optional, Any, Union, Tuple, Iteratorfrom dataclasses import dataclassfrom sentence_transformers import SentenceTransformerfrom transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfigfrom torch.optim import Adam# ConstantsMAX_ROUNDS = 3CONFIDENCE_THRESHOLD = 3JSON_DIRECTORY = './evaluation'class GPUMemoryManager:def __init__(self):self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")os.environ['PYTORCH_CUDA_ALLOC_CONF'] = ('max_split_size_mb:128,''expandable_segments:True,''garbage_collection_threshold:0.6,''roundup_power2:True')if torch.cuda.is_available():torch.cuda.set_per_process_memory_fraction(0.8)self.force_memory_release()def optimize_memory(self):gc.collect()torch.cuda.empty_cache()if torch.cuda.is_available():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()for obj in gc.get_objects():try:if torch.is_tensor(obj):del objexcept Exception:passdef check_memory(self, required_memory_mb: int = 1000) -> bool:if not torch.cuda.is_available():return Truefree_memory = torch.cuda.get_device_properties(0).total_memory - torch.cuda.memory_allocated()free_memory_mb = free_memory / (1024 * 1024)return free_memory_mb >= required_memory_mbdef 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_diros.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'] += 1metrics['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_stdclass 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.devicerows = 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 GDesigner(nn.Module):def __init__(self,5 unmodified lineslearning_rate: float = 0.001,checkpoint_dir: str = "./checkpoints"):super().__init__()self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")self.node_encoder = NodeEncoder(input_dim).to(self.device)self.graph_encoder = GCNEncoder(input_dim, hidden_dim, latent_dim).to(self.device)self.graph_decoder = GraphDecoder(latent_dim, hidden_dim).to(self.device)2 unmodified linesself.sparsity_factor = sparsity_factorself.optimizer = Adam(self.parameters(), lr=learning_rate)self.experience_buffer = []self.performance_history = {}self.checkpoint_dir = checkpoint_dirif not os.path.exists(checkpoint_dir):os.makedirs(checkpoint_dir)self.load_checkpoint()self.to(self.device)def forward(self, agents: List[Dict], query: str, edge_index: Optional[torch.Tensor] = None) -> torch.Tensor:node_features, task_features = self.encode_agents(agents, query)if edge_index is None:anchor_topology = self.create_anchor_topology(len(agents))edge_index = anchor_topology.nonzero().t().to(self.device)else:edge_index = edge_index.to(self.device)mu, log_std = self.graph_encoder(node_features, edge_index)std = torch.exp(log_std)eps = torch.randn_like(std).to(self.device)z = mu + eps * stdoutput = self.graph_decoder(z, task_features)return outputdef 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 vfor k, v in self.optimizer.state_dict().items()}8 unmodified linespickle.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:2 unmodified lineslatest_checkpoint = max(checkpoints)checkpoint_base = latest_checkpoint.replace('_model.pt', '')checkpoint = torch.load(os.path.join(self.checkpoint_dir, latest_checkpoint),map_location=self.device10 unmodified linesprint(f"Error loading checkpoint: {str(e)}")self.experience_buffer = []self.performance_history = {}class DynamicLLM:_instance = None_model = None_tokenizer = Nonedef __new__(cls, *args, **kwargs):if cls._instance is None:cls._instance = super().__new__(cls)cls._instance._initialized = Falsereturn cls._instancedef __init__(self, g_designer=None):if self._initialized:returnself.memory_manager = GPUMemoryManager()self.model_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised"self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")self._initialize_model()self.g_designer = g_designerself._initialized = Trueself.current_role = Noneself.learning_manager = RoleLearningManager()self.performance_history = {}self.role_performance = {role: [] for role in self.learning_manager.role_experiences.keys()}def _initialize_model(self):try:if DynamicLLM._tokenizer is None:DynamicLLM._tokenizer = AutoTokenizer.from_pretrained(self.model_name)self.tokenizer = DynamicLLM._tokenizerif DynamicLLM._model is None:self.memory_manager.force_memory_release()config = AutoConfig.from_pretrained(self.model_name)DynamicLLM._model = AutoModelForCausalLM.from_pretrained(self.model_name,config=config,load_in_8bit=True,torch_dtype=torch.float16,low_cpu_mem_usage=True,device_map='auto')self.model = DynamicLLM._modelexcept Exception as e:print(f"Error during model initialization: {str(e)}")raisedef generate_response(self, prompt: str, role: str = None, context: Dict = None) -> str:try:if role and role != self.current_role:self.switch_role(role, context)with torch.cuda.amp.autocast():role_context = self._get_role_context() if self.current_role else ""enhanced_prompt = f"{role_context}\n{prompt}" if role_context else promptinputs = self.tokenizer(enhanced_prompt, return_tensors="pt")inputs = {k: v.to(self.device) for k, v in inputs.items()}outputs = self.model.generate(**inputs,max_length=512,temperature=0.7,do_sample=True,pad_token_id=self.tokenizer.eos_token_id)response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)del inputs, outputstorch.cuda.empty_cache()return responseexcept Exception as e:print(f"Error during response generation: {str(e)}")torch.cuda.empty_cache()raisedef switch_role(self, role: str, context: Dict = None):self.current_role = roleexperiences = 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 MultiAgentSystem:def __init__(self, g_designer):self.g_designer = g_designerself.llm = DynamicLLM._instanceif self.llm is None:raise RuntimeError("LLM must be initialized before MultiAgentSystem")self.feedback_data = {}self.saved_tasks = {}self.current_agents = []def execute_query(self, query: str, agent_specs: List[Dict], initial_rounds: int) -> str:self.current_task = querystart_time = datetime.now()boss_response = self.llm.generate_response(prompt=self._create_boss_prompt(query),role="boss",context={"task_history": self.g_designer.experience_buffer})results = []for idx, agent in enumerate(agent_specs):agent_role = f"agent{idx+1}"agent_context = {"previous_results": results,"agent_spec": agent,"task": query}response = self.llm.generate_response(2 unmodified linescontext=agent_context)results.append(response)self._evaluate_and_learn(agent_role, query, response)final_answer = self.llm.generate_response(prompt=self._create_summary_prompt(results),role="summarizer",context={"all_results": results, "task": query})execution_time = (datetime.now() - start_time).total_seconds()self._record_task_completion(query, final_answer, execution_time)return final_answerdef create_gradio_interface():def process_query(query: str) -> str:try:g_designer = GDesigner()llm = DynamicLLM(g_designer)mas = MultiAgentSystem(g_designer)agent_specs = [{"base": llm.model_name, "role": "Analyst", "plugins": ["analysis"]},{"base": llm.model_name, "role": "Expert", "plugins": ["domain"]},{"base": llm.model_name, "role": "Critic", "plugins": ["evaluation"]}]response = mas.execute_query(query, agent_specs, initial_rounds=3)return responseexcept Exception as e:return f"Error processing query: {str(e)}"with gr.Blocks() as demo:gr.Markdown("# Multi-Agent LLM System")with gr.Row():input_text = gr.Textbox(label="Enter your query",placeholder="Type your question here...",lines=3)output_text = gr.Textbox(label="Response",lines=10)submit_btn = gr.Button("Submit")submit_btn.click(fn=process_query,inputs=input_text,outputs=output_text)return demoif __name__ == "__main__":try:memory_manager = GPUMemoryManager()memory_manager.force_memory_release()print("Initializing system...")g_designer = GDesigner()llm = DynamicLLM(g_designer)if memory_manager.check_memory(required_memory_mb=1000):demo = create_gradio_interface()demo.launch(server_name="0.0.0.0",share=True,debug=True)else:print("Error: Insufficient GPU memory")sys.exit(1)except Exception as e:
app.py+298-1712