Spaces:
Build error
Build error
Update app.py
Browse files184 unmodified lines185186187188188189190191192193190191192193194195196197198199200203204205206207208201202203204205206207208209210211212213214508 unmodified lines72372472572372672772872572672973073173273373473573673773872872973073974074174274374474574673274774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478573473573673773873974074174278678778878979079174474574674774874975075175279279379479579679779879980080180280380480580680780880981081181281381481581681781881982082175575675775875976076176282282382482582682782882976476576683083183283383483584 unmodified lines920921922857858859860861862863864865923924925926927928929930931869932933871934935936937875938939940941942943944945877878879880881946947948949950951952953954884885886887888889890891892893955956957958959960961895962963964965966967968969970184 unmodified lines def __init__(self, max_trials: int = 3): self.max_trials = max_trials self.results = {} # Dictionary to track results per task
def evaluate_output(self, predicted: List[List[int]], actual: List[List[int]]) -> bool: """ Check if predicted output matches actual output exactly. Only exact matches (all cells) are considered correct. """ """Check if predicted output matches actual output exactly.""" try: if not predicted or not actual: return False # Check dimensions match if len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]): print("Dimension mismatch") return False # Check all values match exactly return all( predicted[i][j] == actual[i][j] for i in range(len(predicted)) for j in range(len(predicted[0])) ) except Exception: for i in range(len(predicted)): for j in range(len(predicted[0])): if predicted[i][j] != actual[i][j]: print(f"Mismatch at position [{i}][{j}]: " f"predicted={predicted[i][j]}, actual={actual[i][j]}") return False return True except Exception as e: print(f"Error in evaluate_output: {str(e)}") return False def record_result(self, task_id: str, trial: int, success: bool):508 unmodified lines self.memory_manager.force_memory_release() raise
def generate_response(self, prompt: str, role: str = None, context: Dict = None) -> str: def generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]: """Generate a prediction for a test input using the multi-agent system.""" try: if role and role != self.current_role: self.switch_role(role, context) # Create more specific task description task_description = ( "Analyze these training examples and predict the output for the test input.\n" "Rules:\n" "1. Only use numbers 0-9\n" "2. Maintain grid structure\n" "3. Look for consistent patterns between input and output\n\n" "Training Examples:\n" ) # Add safety checks before generation if not self.model or not self.tokenizer: raise RuntimeError("Model or tokenizer not properly initialized") # Add formatted training examples for idx, pair in enumerate(train_pairs, 1): task_description += f"\nExample {idx}:\n" task_description += "Input:\n" task_description += grid_to_string(pair['input']) + "\n" task_description += "Output:\n" task_description += grid_to_string(pair['output']) + "\n" self.memory_manager.optimize_memory() # Add test input task_description += "\nTest Input:\n" task_description += grid_to_string(test_input)
# Initialize agents with more specific roles agent_specs = [ { "role": "Pattern Analyst", "specialty": "grid_analysis", "context": { "task": "Identify the exact transformation pattern from input to output grids", "trial": trial + 1, "examples": train_pairs } }, { "role": "Grid Transformer", "specialty": "transformation", "context": { "task": "Apply the identified pattern to generate the output grid", "trial": trial + 1, "test_input": test_input } }, { "role": "Validator", "specialty": "validation", "context": { "task": "Verify the generated grid follows the pattern and constraints", "trial": trial + 1, "valid_values": list(range(10)) } } ] # Execute the prediction pipeline with better error handling pattern_analysis = None transformation_result = None validation_result = None 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 prompt inputs = self.tokenizer( enhanced_prompt, return_tensors="pt", truncation=True, max_length=512 try: pattern_analysis = mas.execute_agent_query( task_description, agent_specs[0], context={"phase": "analysis", "trial": trial} ) 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, num_return_sequences=1 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 response = self.tokenizer.decode(outputs[0], skip_special_tokens=True) # Clean up del inputs, outputs self.memory_manager.optimize_memory() return response # Parse and validate the final grid predicted_grid = parse_grid_from_response(validation_result) if predicted_grid and is_valid_grid(predicted_grid): return predicted_grid return None
except Exception as e: print(f"Response generation error: {str(e)}") self.memory_manager.force_memory_release() return f"Error generating response: {str(e)}" print(f"Error in generate_prediction: {str(e)}") return None
def switch_role(self, role: str, context: Dict = None): self.current_role = role experiences = self.learning_manager.get_role_experience(role)84 unmodified lines return final_answer def parse_grid_from_response(response) -> Optional[List[List[int]]]: """ Parse the grid from the agent's response. Args: response: The response containing the grid Returns: Optional[List[List[int]]]: The parsed grid or None if parsing fails """ """Parse the grid from the agent's response.""" try: # First try to extract grid from structured response if isinstance(response, dict) and 'grid' in response: return response['grid'] # Handle case where response is already a grid if isinstance(response, list) and all(isinstance(row, list) for row in response): if all(all(isinstance(val, int) and 0 <= val <= 9 for val in row) for row in response): return response return response # Otherwise parse from string # Parse from string response grid_lines = [] in_grid = False for line in str(response).split('\n'): if '[' in line and ']' in line and any(c.isdigit() for c in line): # Look for grid-like patterns if ('[' in line and ']' in line) or any(str(i) for i in range(10) if str(i) in line): in_grid = True # Clean and parse numbers clean_line = (line.strip() .strip('[]') .replace(',', ' ') .replace(' ', ' ')) clean_line = line.strip().strip('[]').replace(',', ' ') row = [int(x) for x in clean_line.split() if x.isdigit()] if row: grid_lines.append(row) elif in_grid and line.strip() and '[' not in line: try: row = [int(x) for x in clean_line.split() if x.isdigit()] if row: grid_lines.append(row) except ValueError: continue elif in_grid and not line.strip(): break
# Validate grid if not grid_lines: return None width = len(grid_lines[0]) if not all(len(row) == width for row in grid_lines): return None if not all(all(0 <= val <= 9 for val in row) for row in grid_lines): return None # Validate parsed grid if grid_lines: width = len(grid_lines[0]) if (all(len(row) == width for row in grid_lines) and all(all(0 <= val <= 9 for val in row) for row in grid_lines)): return grid_lines
return grid_lines return None
except Exception as e: print(f"Error parsing grid: {str(e)}") return None
def generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]: """app.py+143-75