Spaces:
Build error
Build error
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212839 unmodified lines129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499import 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, BitsAndBytesConfigfrom transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfigfrom torch.optim import Adam# ConstantsMAX_ROUNDS = 3CONFIDENCE_THRESHOLD = 3JSON_DIRECTORY = './evaluation'class ARCDataLoader:"""Handles loading and processing of ARC task data."""JSON_directory='./evaluation'def __init__(self, base_path: str = JSON_directory):self.base_path = base_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_grid(self, grid: List[List[int]]) -> bool:"""Validate a grid according to ARC specifications."""if not grid or not grid[0]:return Falserows, cols = len(grid), len(grid[0])# Check size constraintsif rows < 1 or rows > 30 or cols < 1 or cols > 30:return False# Check all rows have same length and valid valuesreturn all(len(row) == cols and all(0 <= val <= 9 for val in row)for row in grid)def validate_task_format(self, task: Dict) -> bool:"""Validate that a task follows ARC format specifications."""try:# Verify required fieldsif not isinstance(task.get('train'), list) or not isinstance(task.get('test'), list):return False# Validate all pairsfor pair in task['train'] + task['test']:if not isinstance(pair, dict):return Falseif 'input' not in pair or 'output' not in pair:return Falseif not self.validate_grid(pair['input']) or not self.validate_grid(pair['output']):return Falsereturn Trueexcept Exception: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 = {} # Dictionary to track results per taskdef evaluate_output(self, predicted: List[List[int]], actual: List[List[int]]) -> bool:"""Check if predicted output matches actual output exactly."""try:if not predicted or not actual:return False# Check dimensions matchif len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]):print("Dimension mismatch")return False# Check all values match exactlyfor i in range(len(predicted)):for j in range(len(predicted[0])):if predicted[i][j] != actual[i][j]:print(f"Mismatch at position [{i}][{j}]: "f"predicted={predicted[i][j]}, actual={actual[i][j]}")return Falsereturn Trueexcept Exception as e:print(f"Error in evaluate_output: {str(e)}")return Falsedef record_result(self, task_id: str, trial: int, success: bool):"""Record the result of a specific trial for a task."""if task_id not in self.results:self.results[task_id] = {'trials': [], 'success': False}self.results[task_id]['trials'].append(success)if success:self.results[task_id]['success'] = Truedef get_summary(self) -> Dict:"""Generate summary statistics of evaluation results."""total_tasks = len(self.results)if total_tasks == 0:return {'total_tasks': 0,'successful_tasks': 0,'success_rate': 0.0,'average_trials_to_success': 0.0}successful_tasks = sum(1 for result in self.results.values() if result['success'])# Calculate average trials for successful taskstrials_to_success = []for result in self.results.values():if result['success']:trial_num = next(i + 1 for i, success in enumerate(result['trials']) if success)trials_to_success.append(trial_num)avg_trials = statistics.mean(trials_to_success) if trials_to_success else 0return {'total_tasks': total_tasks,'successful_tasks': successful_tasks,'success_rate': successful_tasks / total_tasks,'average_trials_to_success': avg_trials}class GPUMemoryManager:def __init__(self):self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# Simplified CUDA allocation configos.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'# Set CUDA_LAUNCH_BLOCKING for debuggingos.environ['CUDA_LAUNCH_BLOCKING'] = '1'if torch.cuda.is_available():# More conservative memory fractiontorch.cuda.set_per_process_memory_fraction(0.7)self.force_memory_release()def optimize_memory(self):gc.collect()if torch.cuda.is_available():torch.cuda.empty_cache()torch.cuda.synchronize()def force_memory_release(self):if torch.cuda.is_available():torch.cuda.empty_cache()gc.collect()torch.cuda.synchronize()torch.cuda.reset_peak_memory_stats()# Clear CUDA cache more aggressivelywith torch.cuda.device('cuda'):torch.cuda.empty_cache()torch.cuda.ipc_collect()def check_memory(self, required_memory_mb: int = 1000) -> bool:if not torch.cuda.is_available():return Truetry:with torch.cuda.device('cuda'):total = torch.cuda.get_device_properties(0).total_memoryallocated = torch.cuda.memory_allocated()free_memory = (total - allocated) / (1024 * 1024) # Convert to MBreturn free_memory >= required_memory_mbexcept Exception:return Falsedef 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,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,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)self.temperature = temperatureself.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()}torch.save({'model_state_dict': cpu_state_dict,'optimizer_state_dict': cpu_optimizer_state,'performance_history': self.performance_history,}, f"{checkpoint_path}_model.pt")with open(f"{checkpoint_path}_experiences.pkl", 'wb') as f:pickle.dump(self.experience_buffer, f)def load_checkpoint(self):try:checkpoints = [f for f in os.listdir(self.checkpoint_dir) if f.endswith('_model.pt')]if not checkpoints:returnlatest_checkpoint = max(checkpoints)checkpoint_base = latest_checkpoint.replace('_model.pt', '')checkpoint = torch.load(os.path.join(self.checkpoint_dir, latest_checkpoint),map_location=self.device)self.load_state_dict(checkpoint['model_state_dict'])self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])self.performance_history = checkpoint['performance_history']with open(os.path.join(self.checkpoint_dir, f"{checkpoint_base}_experiences.pkl"), 'rb') as f:self.experience_buffer = pickle.load(f)except Exception as e:print(f"Error loading checkpoint: {str(e)}")self.experience_buffer = []self.performance_history = {}def _create_boss_prompt(self, query: str) -> str:"""Creates a structured prompt for the boss agent to interpret tasks and define specialized agents.Args:query (str): The user's input query/task descriptionReturns:str: A formatted prompt for the boss agent"""# Get historical performance if availabletask_history = self.g_designer.experience_buffer[-5:] if self.g_designer.experience_buffer else []historical_insights = "\n".join([f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s"for exp in task_history])boss_prompt = f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks.CURRENT TASK: {query}HISTORICAL CONTEXT:{historical_insights if task_history else 'No previous task history available.'}YOUR RESPONSIBILITIES:1. Analyze the given task thoroughly2. Define exactly 3 specialized AI agents that would be best suited for solving this task3. Ensure the agents have complementary skills and clear responsibilities4. Consider any insights from previous similar tasks5. Provide structured response in the required formatRemember:- A dedicated summarizer agent will be added automatically- Focus on creating agents with distinct, complementary roles- Consider both general capabilities and specialized knowledge needed- Agents should collaborate effectively to solve the taskPlease provide your response in the following format:TASK ANALYSIS:[Provide a brief analysis of the task's requirements and complexity]AGENT SPECIFICATIONS:1. [Role1]Primary Function: [Main responsibility]Specialty: [Key areas of expertise]Plugins: [Relevant tools/capabilities]Reasoning: [Why this agent is needed]2. [Role2]Primary Function: [Main responsibility]Specialty: [Key areas of expertise]Plugins: [Relevant tools/capabilities]Reasoning: [Why this agent is needed]3. [Role3]Primary Function: [Main responsibility]Specialty: [Key areas of expertise]Plugins: [Relevant tools/capabilities]Reasoning: [Why this agent is needed]COLLABORATION STRATEGY:[Brief description of how these agents should work together]EXECUTION PLAN:Recommended Rounds: [Number between 1-8]Rationale: [Brief explanation for the number of rounds]Based on your analysis, provide the complete response following this format."""return boss_promptdef _parse_boss_response(self, response: str) -> Tuple[List[Dict], int]:"""Parses the boss's response to extract agent specifications and round count.Args:response (str): The boss agent's formatted responseReturns:Tuple[List[Dict], int]: A tuple containing the list of agent specifications and recommended rounds"""try:# Extract agent specificationsagent_specs = []agent_sections = response.split('\n\n')for section in agent_sections:if 'Primary Function:' in section:lines = section.strip().split('\n')role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip()plugins = [p.strip() for p innext(l for l in lines if 'Plugins:' in l).replace('Plugins:', '').strip().split(',')]agent_specs.append({"role": role,"base": self.llm.model_name,"plugins": plugins})# Extract recommended roundsrounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response)rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8)# Ensure exactly 3 agentsif len(agent_specs) != 3:raise ValueError("Boss must specify exactly 3 agents")return agent_specs, roundsexcept Exception as e:print(f"Error parsing boss response: {str(e)}")# Return default specifications if parsing failsreturn [{"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]},{"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]},{"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]}], 3class 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")try: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()}except Exception as e:print(f"Initialization error: {str(e)}")self._initialized = Falseraisedef _initialize_model(self):try:# Clear any existing model firstif DynamicLLM._model is not None:del DynamicLLM._modelself.memory_manager.force_memory_release()if DynamicLLM._tokenizer is None:DynamicLLM._tokenizer = AutoTokenizer.from_pretrained(self.model_name,use_fast=False)self.tokenizer = DynamicLLM._tokenizer# Modified quantization configurationquantization_config = BitsAndBytesConfig(load_in_4bit=True, # Changed to 4-bit quantizationbnb_4bit_compute_dtype=torch.float16,bnb_4bit_quant_type="nf4",bnb_4bit_use_double_quant=False)# Load model with proper error handlingif DynamicLLM._model is None:self.memory_manager.force_memory_release()# Load model configuration firstconfig = AutoConfig.from_pretrained(self.model_name)config.use_cache = False # Disable KV cache to save memory# Modified model loading with safer defaultsDynamicLLM._model = AutoModelForCausalLM.from_pretrained(self.model_name,config=config,quantization_config=quantization_config,device_map='auto',torch_dtype=torch.float16,low_cpu_mem_usage=True,offload_folder="offload_folder",offload_state_dict=True,trust_remote_code=False # Added safety measure)# Add model verificationif DynamicLLM._model is None:raise RuntimeError("Model failed to load")# Verify model is on correct deviceif torch.cuda.is_available():assert next(DynamicLLM._model.parameters()).is_cuda, "Model not loaded on GPU"self.model = DynamicLLM._modelexcept Exception as e:print(f"Model initialization error: {str(e)}")self.memory_manager.force_memory_release()raisedef generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]:"""Generate a prediction for a test input using the multi-agent system."""try:# Create more specific task descriptiontask_description = ("Analyze these training examples and predict the output for the test input.\n""Rules:\n""1. Only use numbers 0-9\n""2. Maintain grid structure\n""3. Look for consistent patterns between input and output\n\n""Training Examples:\n")# Add formatted training examplesfor idx, pair in enumerate(train_pairs, 1):task_description += f"\nExample {idx}:\n"task_description += "Input:\n"task_description += grid_to_string(pair['input']) + "\n"task_description += "Output:\n"task_description += grid_to_string(pair['output']) + "\n"# Add test inputtask_description += "\nTest Input:\n"task_description += grid_to_string(test_input)# Initialize agents with more specific rolesagent_specs = [{"role": "Pattern Analyst","specialty": "grid_analysis","context": {"task": "Identify the exact transformation pattern from input to output grids","trial": trial + 1,"examples": train_pairs}},{"role": "Grid Transformer","specialty": "transformation","context": {"task": "Apply the identified pattern to generate the output grid","trial": trial + 1,"test_input": test_input}},{"role": "Validator","specialty": "validation","context": {"task": "Verify the generated grid follows the pattern and constraints","trial": trial + 1,"valid_values": list(range(10))}}]# Execute the prediction pipeline with better error handlingpattern_analysis = Nonetransformation_result = Nonevalidation_result = Nonetry:pattern_analysis = mas.execute_agent_query(task_description,agent_specs[0],context={"phase": "analysis", "trial": trial})if not pattern_analysis:raise ValueError("Pattern analysis failed")transformation_result = mas.execute_agent_query(task_description,agent_specs[1],context={"phase": "transformation","pattern_analysis": pattern_analysis,"trial": trial})if not transformation_result:raise ValueError("Transformation failed")validation_result = mas.execute_agent_query(task_description,agent_specs[2],context={"phase": "validation","transformed_grid": transformation_result,"trial": trial})if not validation_result:raise ValueError("Validation failed")except Exception as e:print(f"Agent pipeline error: {str(e)}")return None# Parse and validate the final gridpredicted_grid = parse_grid_from_response(validation_result)if predicted_grid and is_valid_grid(predicted_grid):return predicted_gridreturn Noneexcept Exception as e:print(f"Error in generate_prediction: {str(e)}")return Nonedef 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})#agent_specs, rounds = self._parse_boss_response(boss_response)# Use agent_specs instead of the input agent_specs parameter# Use rounds instead of initial_rounds parameter#Has the Boss LLM chose the amount of rounds and learn the minimum amount of rounds needed for an answer instead of it being preset which is how it is currently set-up.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(prompt=self._create_agent_prompt(agent, results),role=agent_role,context=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})# Add this line to print the summaryprint(f"Final Summary:\n{final_answer}")execution_time = (datetime.now() - start_time).total_seconds()self._record_task_completion(query, final_answer, execution_time)return final_answerdef parse_grid_from_response(response) -> Optional[List[List[int]]]:"""Parse the grid from the agent's response."""try:# First try to extract grid from structured responseif isinstance(response, dict) and 'grid' in response:return response['grid']# Handle case where response is already a gridif isinstance(response, list) and all(isinstance(row, list) for row in response):if all(all(isinstance(val, int) and 0 <= val <= 9 for val in row) for row in response):return response# Parse from string responsegrid_lines = []in_grid = Falsefor line in str(response).split('\n'):# Look for grid-like patternsif ('[' in line and ']' in line) or any(str(i) for i in range(10) if str(i) in line):in_grid = True# Clean and parse numbersclean_line = (line.strip().strip('[]').replace(',', ' ').replace(' ', ' '))try:row = [int(x) for x in clean_line.split() if x.isdigit()]if row:grid_lines.append(row)except ValueError:continueelif in_grid and not line.strip():break# Validate parsed gridif grid_lines:width = len(grid_lines[0])if (all(len(row) == width for row in grid_lines) andall(all(0 <= val <= 9 for val in row) for row in grid_lines)):return grid_linesreturn Noneexcept Exception as e:print(f"Error parsing grid: {str(e)}")return Nonedef generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]:"""Generate a prediction for a test input using the multi-agent system.Args:train_pairs: List of training input/output pairstest_input: The input grid for predictiontrial: Current trial number (0-2)Returns:List[List[int]]: Predicted output grid"""try:# Initialize agents with specific rolesagent_specs = [{"role": "Pattern Analyst","specialty": "grid_analysis","context": {"task": "Analyze patterns in training examples and identify transformation rules","trial": trial + 1}},{"role": "Grid Transformer","specialty": "transformation","context": {"task": "Apply identified patterns to generate output grid","trial": trial + 1}},{"role": "Validator","specialty": "validation","context": {"task": "Verify generated grid follows identified patterns","trial": trial + 1}}]# Create task description for the agentstask_description = create_task_description(train_pairs, test_input)# Initialize the multi-agent systemg_designer = GDesigner()llm = DynamicLLM(g_designer)mas = MultiAgentSystem(g_designer)# Execute the prediction pipeline# 1. Pattern Analysispattern_analysis = mas.execute_agent_query(task_description,agent_specs[0],context={"phase": "analysis", "trial": trial})# 2. Grid Transformationtransformation_result = mas.execute_agent_query(task_description,agent_specs[1],context={"phase": "transformation","pattern_analysis": pattern_analysis,"trial": trial})# 3. Validationvalidation_result = mas.execute_agent_query(task_description,agent_specs[2],context={"phase": "validation","transformed_grid": transformation_result,"trial": trial})# Parse the final grid from the validation resultpredicted_grid = parse_grid_from_response(validation_result)# Verify grid formatif not is_valid_grid(predicted_grid):raise ValueError("Invalid grid format generated")return predicted_gridexcept Exception as e:print(f"Error in generate_prediction: {str(e)}")return Nonedef process_all_tasks() -> Iterator[str]:"""Process all evaluation tasks sequentially with progress tracking.Returns:Iterator[str]: Yields status updates and results as strings"""try:tasks = load_evaluation_tasks()total_tasks = len(tasks)results = []progress = gr.Progress()progress(0, desc="Initializing...")for idx, (filename, task) in enumerate(tasks):try:progress((idx / total_tasks),desc=f"Processing task {idx + 1}/{total_tasks}: {filename}")# Process task and get resultstask_result = process_query(task) # Now passing task dict directlyresults.append(f"\nTask {idx + 1}/{total_tasks}: {filename}\n{task_result}")yield "\n".join(results)except Exception as e:error_msg = f"\nError processing {filename}: {str(e)}\n"results.append(error_msg)yield "\n".join(results)progress(1.0, desc="Processing complete!")# Add final summarysummary = ARCEvaluator.get_summary()summary_text = "\nEvaluation Complete!\n"summary_text += f"Total tasks processed: {total_tasks}\n"summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n"results.append(summary_text)yield "\n".join(results)except Exception as e:yield f"Fatal error during task processing: {str(e)}"def process_query(task: Dict) -> str:try:arc_loader = ARCDataLoader()arc_evaluator = ARCEvaluator(max_trials=3)# Validate the taskif not arc_loader.validate_task_format(task):return "Error: Invalid ARC task format"# Process each test case with up to 3 trialsresults = []for test_idx, test_case in enumerate(task['test']):success = Falsepredicted_grid = Nonefor trial in range(3): # 3 trials per test casetry:# Generate prediction using the agent systempredicted_grid = generate_prediction(task['train'], test_case['input'], trial)if predicted_grid:# Parse the grid from the responsepredicted_grid = parse_grid_from_response(predicted_grid)if predicted_grid:success = arc_evaluator.evaluate_output(predicted_grid, test_case['output'])arc_evaluator.record_result(f"task_{test_idx}", trial + 1, success)if success:break # Stop trials if successfulexcept Exception as e:print(f"Trial {trial + 1} failed: {str(e)}")continueresults.append({'test_case': test_idx + 1,'success': success,'predicted_grid': predicted_grid})# Format responseresponse = "Evaluation Results:\n\n"for result in results:response += f"Test Case {result['test_case']}:\n"response += f"Success: {result['success']}\n"if result['predicted_grid']:response += "Predicted Grid:\n"response += "\n".join(" ".join(str(cell) for cell in row)for row in result['predicted_grid'])response += "\n\n"# Add summary statisticssummary = arc_evaluator.get_summary()response += f"Overall Success Rate: {summary['success_rate']*100:.2f}%\n"response += f"Average Trials to Success: {summary['average_trials_to_success']:.2f}\n"return responseexcept Exception as e:return f"Error processing query: {str(e)}"def create_task_description(train_pairs: List[Dict], test_input: List[List[int]]) -> str:"""Create a detailed task description from training pairs and test input."""description = "ARC Task Analysis:\n\nTraining Examples:\n"# Add training examplesfor idx, pair in enumerate(train_pairs):description += f"\nExample {idx + 1}:\n"description += "Input Grid:\n"description += grid_to_string(pair['input'])description += "\nOutput Grid:\n"description += grid_to_string(pair['output'])description += "\n"# Add test inputdescription += "\nTest Input Grid:\n"description += grid_to_string(test_input)return descriptiondef grid_to_string(grid: List[List[int]]) -> str:"""Convert a grid to a string representation."""return "\n".join(" ".join(str(cell) for cell in row) for row in grid)def is_valid_grid(grid: List[List[int]]) -> bool:"""Validate grid format according to ARC specifications."""if not grid or not isinstance(grid, list) or not all(isinstance(row, list) for row in grid):return False# Check dimensionsrows = len(grid)cols = len(grid[0]) if rows > 0 else 0if rows < 1 or rows > 30 or cols < 1 or cols > 30:return False# Check values and consistencyreturn all(len(row) == cols and all(isinstance(val, int) and 0 <= val <= 9 for val in row)for row in grid)def execute_agent_query(self, task_description: str, agent_spec: Dict, context: Dict) -> str:"""Execute a query for a specific agent role.Args:task_description: Description of the taskagent_spec: Specification of the agent rolecontext: Additional context for the queryReturns:str: Agent's response"""try:# Create role-specific promptrole = agent_spec["role"]specialty = agent_spec["specialty"]phase = context.get("phase", "unknown")trial = context.get("trial", 0)prompt = f"""As the {role} with expertise in {specialty}, analyze the following task.Task Phase: {phase}Trial: {trial + 1}/3{task_description}Previous Context:{json.dumps(context, indent=2)}Your task is to {agent_spec['context']['task']}.Provide your response in the following format:1. Analysis: Describe your understanding and approach2. Implementation: Show your work step by step3. Result: Provide the final output in grid format using integers 0-9Response:"""# Generate response using the LLMresponse = self.llm.generate_response(prompt, role=role)# Record the interaction for learningself.llm.learn_from_interaction(role=role,task=task_description,success=True, # This should be based on validationlearning="Interaction completed successfully",feedback=context)return responseexcept Exception as e:print(f"Error in execute_agent_query: {str(e)}")return Nonedef load_evaluation_tasks():"""Load all JSON files from evaluation directory."""eval_path = './evaluation'tasks = []for filename in sorted(os.listdir(eval_path)):if filename.endswith('.json'):with open(os.path.join(eval_path, filename), 'r') as f:tasks.append((filename, json.load(f)))return tasksdef grid_to_string(grid: List[List[int]]) -> str:"""Convert a grid to a formatted string representation."""9 unmodified linesfor row in grid)def load_evaluation_tasks() -> List[Tuple[str, Dict]]:"""Load all JSON files from evaluation directory."""eval_path = './evaluation'if not os.path.exists(eval_path):raise ValueError(f"Evaluation directory not found: {eval_path}")tasks = []for filename in sorted(os.listdir(eval_path)):if filename.endswith('.json'):try:with open(os.path.join(eval_path, filename), 'r') as f:task_data = json.load(f)# Validate task formatif 'train' in task_data and 'test' in task_data:tasks.append((filename, task_data))else:print(f"Warning: Invalid task format in {filename}")except Exception as e:print(f"Error loading {filename}: {str(e)}")if not tasks:raise ValueError("No valid task files found in evaluation directory")return tasksdef create_gradio_interface():"""Create and configure the Gradio interface for the ARC system."""import gradio as grfrom datetime import datetime# Initialize system componentsarc_loader = ARCDataLoader()arc_evaluator = ARCEvaluator()def save_summary(results: str) -> str:"""Save evaluation results to a file and return the file path."""timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")filename = f"arc_evaluation_summary_{timestamp}.txt"with open(filename, "w") as f:f.write(results)return filenamedef process_and_save():"""Process tasks and generate downloadable summary."""results_generator = process_all_tasks()final_results = None# Process all results from generatorfor results in results_generator:final_results = resultsyield results, None # Update display but not file yet# Save final results to fileif final_results:summary_file = save_summary(final_results)yield final_results, summary_filewith gr.Blocks() as interface:gr.Markdown("# ARC Task Solver - Automated Evaluation")gr.Markdown("""Automated evaluation of ARC tasks using AI agents.Processing tasks from ./evaluation directory.Results will update in real-time as tasks are processed.""")with gr.Row():start_button = gr.Button("Start Evaluation")status = gr.HTML("<div id='progress-status'>Ready to start evaluation...</div>")with gr.Row():# Results displayoutput = gr.Textbox(label="Evaluation Results",lines=20,max_lines=50,autoscroll=True)# Download button for summarysummary_file = gr.File(label="Download Evaluation Summary",visible=True,interactive=False)# Add custom CSSgr.HTML("""<style>#progress-status {margin: 10px 0;padding: 10px;background-color: #f0f0f0;border-radius: 5px;}.progress-bar {height: 20px;background-color: #4CAF50;transition: width 0.5s ease-in-out;}.output-box {max-height: 500px;overflow-y: auto;}</style>""")# Connect the start button to the processing functionstart_button.click(fn=process_and_save,outputs=[output, summary_file])return interfacedef process_all_tasks() -> Iterator[str]:"""Process all evaluation tasks sequentially with progress tracking."""try:tasks = load_evaluation_tasks()total_tasks = len(tasks)results = []# Add header with timestamptimestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")results.append(f"ARC Evaluation Summary\nGenerated: {timestamp}\n")results.append("=" * 50 + "\n")progress = gr.Progress()progress(0, desc="Initializing...")for idx, (filename, task) in enumerate(tasks):try:progress((idx / total_tasks),desc=f"Processing task {idx + 1}/{total_tasks}: {filename}")# Process task and get resultstask_result = process_query(task)results.append(f"\nTask {idx + 1}/{total_tasks}: {filename}\n{task_result}")results.append("-" * 30 + "\n")yield "\n".join(results)except Exception as e:error_msg = f"\nError processing {filename}: {str(e)}\n"results.append(error_msg)yield "\n".join(results)progress(1.0, desc="Processing complete!")arc_evaluator = ARCEvaluator()# Add final summary with detailed statisticssummary = arc_evaluator.get_summary()summary_text = "\nFINAL EVALUATION SUMMARY\n"summary_text += "=" * 50 + "\n"summary_text += f"Total tasks processed: {total_tasks}\n"summary_text += f"Successful tasks: {summary['successful_tasks']}\n"summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n"summary_text += f"Average trials to success: {summary['average_trials_to_success']:.2f}\n"summary_text += "\nDetailed Statistics:\n"summary_text += "-" * 30 + "\n"summary_text += f"Tasks completed: {total_tasks}\n"summary_text += f"Tasks successful: {summary['successful_tasks']}\n"summary_text += f"Tasks failed: {total_tasks - summary['successful_tasks']}\n"results.append(summary_text)yield "\n".join(results)except Exception as e:yield f"Fatal error during task processing: {str(e)}"if __name__ == "__main__":try:# Initialize system componentsmemory_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):# Create and launch Gradio interfacedemo = create_gradio_interface()if demo is not None:demo.queue() # Enable queuing for progress updatesdemo.launch(server_name="0.0.0.0",share=True,debug=True,show_error=True)else:print("Error: Failed to create Gradio interface")sys.exit(1)else:print("Error: Insufficient GPU memory")sys.exit(1)except Exception as e:print(f"Error during initialization: {str(e)}")if 'g_designer' in locals():g_designer.save_checkpoint()sys.exit(1)12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576779 unmodified lines87888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156def evaluate_prediction(predicted: List[List[int]], actual: List[List[int]]) -> bool:"""Evaluate if predicted grid matches actual grid."""try:if not predicted or not actual:print("Empty prediction or actual grid")return False# Check dimensions matchif len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]):print(f"Dimension mismatch: predicted {len(predicted)}x{len(predicted[0])} "f"vs actual {len(actual)}x{len(actual[0])}")return False# Check all values match exactlyfor i in range(len(predicted)):for j in range(len(predicted[0])):if predicted[i][j] != actual[i][j]:print(f"Mismatch at position [{i}][{j}]: "f"predicted={predicted[i][j]}, actual={actual[i][j]}")return Falsereturn Trueexcept Exception as e:print(f"Error in evaluate_prediction: {str(e)}")return Falsedef save_results(results: List[Dict], output_file: str) -> None:"""Save evaluation results to JSON file with additional metrics."""try:# Calculate additional metricstask_metrics = {'total_tasks_processed': len(results),'successful_tasks': sum(1 for r in results if r.get('success', False)),'average_rounds': statistics.mean(r['rounds'] for r in results),'average_performance': statistics.mean(r['performance'] for r in results),'boss_strategy_distribution': _calculate_strategy_distribution(results)}# Prepare output dataoutput_data = {'timestamp': datetime.now().isoformat(),'metrics': task_metrics,'detailed_results': results}# Save to filewith open(output_file, 'w') as f:json.dump(output_data, f, indent=2)except Exception as e:print(f"Error saving results: {str(e)}")def _calculate_strategy_distribution(results: List[Dict]) -> Dict:"""Calculate distribution of boss strategies used."""try:strategy_counts = {}for result in results:boss_strategy = str(result.get('boss_strategy', [])) # Convert to string for hashingstrategy_counts[boss_strategy] = strategy_counts.get(boss_strategy, 0) + 1# Calculate percentagestotal = len(results)return {strategy: {'count': count,'percentage': (count / total) * 100 if total > 0 else 0}for strategy, count in strategy_counts.items()}except Exception as e:print(f"Error calculating strategy distribution: {str(e)}")return {}def grid_to_string(grid: List[List[int]]) -> str:"""Convert a grid to a formatted string representation."""9 unmodified linesfor row in grid)def evaluate_arc_tasks(task_files: List[str], output_file: str):"""Evaluate ARC tasks using the new learning framework."""results = []total_tasks = len(task_files)successful_tasks = 0try:for trial, task_file in enumerate(task_files):# Load taskwith open(task_file, 'r') as f:task_data = json.load(f)# Process taskresult = process_arc_task(task_data, trial)if result:# Evaluate predictioncorrect = evaluate_prediction(result['prediction'],task_data['test'][0]['output'])# Store results with additional metricstask_result = {'task_id': task_data.get('id', f"task_{trial}"),'success': correct,'performance': result['performance'],'rounds': result['rounds'],'boss_strategy': result['boss_specs']['role_specs'],'grid_size': {'input': [len(task_data['test'][0]['input']),len(task_data['test'][0]['input'][0])],'output': [len(task_data['test'][0]['output']),len(task_data['test'][0]['output'][0])]},'prediction_visualization': grid_to_string(result['prediction'])}results.append(task_result)if correct:successful_tasks += 1# Save progress periodically with detailed metricsif (trial + 1) % 10 == 0:save_results(results, output_file)# Calculate final statistics with additional metricsfinal_stats = {'total_tasks': total_tasks,'successful_tasks': successful_tasks,'success_rate': successful_tasks / total_tasks if total_tasks > 0 else 0,'average_rounds': statistics.mean(r['rounds'] for r in results) if results else 0,'performance_distribution': {'mean': statistics.mean(r['performance'] for r in results) if results else 0,'std': statistics.stdev(r['performance'] for r in results) if len(results) > 1 else 0},'timestamp': datetime.now().isoformat()}# Save final results with all metricssave_results(results + [final_stats], output_file)return results, final_statsexcept Exception as e:print(f"Error in ARC evaluation: {str(e)}")return None, None
app.py+111-1454