Spaces:
Build error
Build error
Update app.py
Browse files184 unmodified lines185186187188189190191192193194195196197198199200201202203204205206207208209210211508 unmodified lines72072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876984 unmodified lines854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902184 unmodified linesdef __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.Only exact matches (all cells) are considered correct."""try:if not predicted or not actual:return False# Check dimensions matchif len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]):return False# Check all values match exactlyreturn all(predicted[i][j] == actual[i][j]for i in range(len(predicted))for j in range(len(predicted[0])))except Exception:return Falsedef record_result(self, task_id: str, trial: int, success: bool):508 unmodified linesself.memory_manager.force_memory_release()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)# Add safety checks before generationif not self.model or not self.tokenizer:raise RuntimeError("Model or tokenizer not properly initialized")self.memory_manager.optimize_memory()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",truncation=True,max_length=512)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)response = self.tokenizer.decode(outputs[0], skip_special_tokens=True)# Clean updel inputs, outputsself.memory_manager.optimize_memory()return responseexcept Exception as e:print(f"Response generation error: {str(e)}")self.memory_manager.force_memory_release()return f"Error generating response: {str(e)}"def switch_role(self, role: str, context: Dict = None):self.current_role = roleexperiences = self.learning_manager.get_role_experience(role)84 unmodified linesreturn final_answerdef parse_grid_from_response(response) -> Optional[List[List[int]]]:"""Parse the grid from the agent's response.Args:response: The response containing the gridReturns:Optional[List[List[int]]]: The parsed grid or None if parsing fails"""try:# Handle case where response is already a gridif isinstance(response, list) and all(isinstance(row, list) for row in response):return response# Otherwise parse from stringgrid_lines = []in_grid = Falsefor line in str(response).split('\n'):if '[' in line and ']' in line and any(c.isdigit() for c in line):in_grid = Trueclean_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:break# Validate gridif not grid_lines:return Nonewidth = len(grid_lines[0])if not all(len(row) == width for row in grid_lines):return Noneif not all(all(0 <= val <= 9 for val in row) for row in grid_lines):return Nonereturn grid_linesexcept 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]]:"""184 unmodified lines185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214508 unmodified lines72372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483584 unmodified lines920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970184 unmodified linesdef __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):508 unmodified linesself.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)84 unmodified linesreturn 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]]:"""
app.py+143-75