Spaces:
Build error
Build error
Update app.py
Browse files18 unmodified lines192021222324252627287 unmodified lines36373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687680 unmodified lines768769770771772773774775776777778779780781782218 unmodified lines100110021003100410051006100710081009101010111012101310141015101610171018101935 unmodified lines1055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111045 unmodified lines1156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124774 unmodified lines1322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346551 unmodified lines1898189919001901190219031904190519061907190819091910191119121913191419156 unmodified lines192219231924192519261927192819291 unmodified line19311932193319341935193619371938193918 unmodified linesfrom dataclasses import dataclass# Initialize optimizer - Fixed by importing torch.optim and using torch's Adam optimizerfrom torch.optim import Adamimport torch.cudaimport gcfrom torch.cuda import empty_cacheimport osfrom transformers import AutoModelForCausalLM, AutoTokenizerimport torch7 unmodified lines# Threshold for confidence level to stop querying LLMCONFIDENCE_THRESHOLD = 3class SharedLLM:"""Singleton class to manage a single LLM instance"""_instance = None_model = None_tokenizer = None@classmethoddef get_instance(cls):if cls._instance is None:cls._instance = cls()return cls._instancedef __init__(self):if SharedLLM._instance is not None:raise Exception("This class is a singleton! Use get_instance() instead.")else:self.model_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised"self._tokenizer = AutoTokenizer.from_pretrained(self.model_name)self._model = AutoModelForCausalLM.from_pretrained(self.model_name,torch_dtype=torch.float16,device_map="auto" if torch.cuda.is_available() else None,low_cpu_mem_usage=True)SharedLLM._instance = self@propertydef model(self):return self._model@propertydef tokenizer(self):return self._tokenizerdef generate_response(self, prompt: str, max_length: int = 512) -> str:inputs = self.tokenizer(prompt, return_tensors="pt")inputs = {k: v.to(self.model.device) for k, v in inputs.items()}outputs = self.model.generate(**inputs,max_length=max_length,temperature=0.7,do_sample=True)return self.tokenizer.decode(outputs[0], skip_special_tokens=True)class ARCDataLoader:"""Handles loading and processing of ARC task data."""JSON_directory='./evaluation'680 unmodified linesagents: 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_features218 unmodified linessuggested_rounds: int # Track suggested rounds from LLM or systemdef generate_llm_response(prompt: str, max_length: int = 3000, truncation=True, padding='max_length') -> str:"""Generate response using Chocolatine model"""inputs = tokenizer(prompt, return_tensors="pt") # Changed boss_prompt to prompt# Move inputs and model to the same device (GPU or CPU)device = torch.device("cuda" if torch.cuda.is_available() else "cpu")model.to(device)inputs = {k: v.to(device) for k, v in inputs.items()}# Generate responseoutputs = model.generate(**inputs, max_length=max_length)response = tokenizer.decode(outputs[0], skip_special_tokens=True)return response # Return is inside the function nowdef parse_result_to_grid(result: str) -> List[List[int]]:"""Convert LLM output to grid format"""35 unmodified linesROUNDS: [number 1-8]"""response = generate_llm_response(boss_prompt)# 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": 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": 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 configuration with exactly 3 agentsreturn [{"base": model_name, "role": "Analyst", "specialty": "Data analysis", "plugins": ["data_analysis"]},{"base": model_name, "role": "Researcher", "specialty": "Information gathering", "plugins": ["knowledge_base"]},{"base": model_name, "role": "Expert", "specialty": "Domain expertise", "plugins": ["domain_expertise"]}], 3# Ensure exactly 3 agents are returnedrounds = min(max(1, int(rounds_section.strip())), 8) # Ensure rounds is between 1-8return agent_specs[:3], rounds@dataclass45 unmodified linesself.role_experiences[role] = pickle.load(f)class GPUMemoryManager:"""Manages GPU memory allocation and cleanup"""def __init__(self):self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")# Set memory management environment variablesos.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:512,expandable_segments:True'# Initialize memory trackingself.peak_memory = 0self.current_memory = 0def optimize_memory(self):"""Optimize GPU memory usage"""gc.collect()empty_cache()if torch.cuda.is_available():torch.cuda.synchronize()def get_memory_stats(self):"""Get current GPU memory statistics"""if torch.cuda.is_available():return {'allocated': torch.cuda.memory_allocated() / 1024**2,'cached': torch.cuda.memory_reserved() / 1024**2,'max_allocated': torch.cuda.max_memory_allocated() / 1024**2}return {'allocated': 0, 'cached': 0, 'max_allocated': 0}def check_memory(self, required_memory_mb: int = 0) -> bool:"""Check if there's enough GPU memory available"""if not torch.cuda.is_available():return Truestats = self.get_memory_stats()available = torch.cuda.get_device_properties(0).total_memory / 1024**2currently_available = available - stats['allocated']return currently_available >= required_memory_mbclass DynamicLLM:def __init__(self, g_designer: GDesigner):self.memory_manager = GPUMemoryManager()self.model_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised"# Configure model loading with memory optimizationself.model_config = {'torch_dtype': torch.float16,'low_cpu_mem_usage': True,'device_map': 'auto','max_memory': {0: '40GB'}, # Adjust based on your GPU'offload_folder': 'offload_folder','revision': 'main'}# Initialize tokenizer and model with memory managementself._initialize_model()# Other initializations...self.g_designer = g_designerself.current_role = Noneself.learning_manager = RoleLearningManager()def _initialize_model(self):"""Initialize model with memory management"""try:self.memory_manager.optimize_memory()print("Loading tokenizer...")self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)print("Loading model...")self.model = AutoModelForCausalLM.from_pretrained(self.model_name,**self.model_config)# Move model to GPU with memory optimizationif torch.cuda.is_available():self.model = self.model.half() # Use half precisionself.model = self.model.to(self.memory_manager.device)except Exception as e:print(f"Error during model initialization: {str(e)}")raisedef switch_role(self, role: str, context: Dict = None):"""Switch LLM to a different role and load relevant experience"""self.current_role = role74 unmodified linesself.learning_manager.save_experience(role, experience)class MultiAgentSystem:def __init__(self, g_designer: GDesigner):self.g_designer = g_designerself.llm = DynamicLLM()self.current_task = None# Use shared LLM instance instead of creating new oneself.llm = SharedLLM.get_instance()#Add checkpoint intervalself.checkpoint_interval = 10 # Save every 10 tasksself.tasks_since_checkpoint = 0# Fixed summarizer agentself.summarizer_agent = {"base": self.model_name,"role": "Summarizer","specialty": "Information synthesis and consolidation","plugins": ["text_analysis", "summary_generation"]}551 unmodified linesprint("Initializing GPU memory management...")memory_manager.optimize_memory()# Print initial memory statsstats = memory_manager.get_memory_stats()print(f"Initial GPU memory stats:")print(f"Allocated: {stats['allocated']:.2f} MB")print(f"Cached: {stats['cached']:.2f} MB")print("Initializing shared LLM...")shared_llm = DynamicLLM(g_designer=None) # Initialize g_designer separately# Initialize other components with memory managementg_designer = GDesigner()shared_llm.g_designer = g_designer# Register signal handlerssignal.signal(signal.SIGINT, signal_handler)6 unmodified linesprint(f"Cached: {stats['cached']:.2f} MB")print(f"Peak: {stats['max_allocated']:.2f} MB")# Launch Gradio interface if memory is sufficientif memory_manager.check_memory(required_memory_mb=1000): # Adjust value as neededdemo = create_gradio_interface()demo.queue()demo.launch(1 unmodified lineshare=True,debug=True)else:print("Error: Insufficient GPU memory for launch")sys.exit(1)except Exception as e:print(f"Error during initialization: {str(e)}")18 unmodified lines1920212223247 unmodified lines323334353637680 unmodified lines718719720721722723724725726727728729730731732218 unmodified lines95195295395495595695795895996096196296396496596696735 unmodified lines10031004100510061007100845 unmodified lines1054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117874 unmodified lines1253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325551 unmodified lines18771878187918801881188218831884188518866 unmodified lines18931894189518961897189818991 unmodified line19011902190319041905190618 unmodified linesfrom dataclasses import dataclass# Initialize optimizer - Fixed by importing torch.optim and using torch's Adam optimizerfrom torch.optim import Adamfrom transformers import AutoModelForCausalLM, AutoTokenizerimport torch7 unmodified lines# Threshold for confidence level to stop querying LLMCONFIDENCE_THRESHOLD = 3class ARCDataLoader:"""Handles loading and processing of ARC task data."""JSON_directory='./evaluation'680 unmodified linesagents: 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_features218 unmodified linessuggested_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"""35 unmodified linesROUNDS: [number 1-8]"""@dataclass45 unmodified linesself.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 = role74 unmodified linesself.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], rounds551 unmodified linesprint("Initializing GPU memory management...")memory_manager.optimize_memory()# Initialize components with single DynamicLLM instanceprint("Initializing LLM...")g_designer = GDesigner()llm = DynamicLLM(g_designer) # This will be our only LLM instance# Register signal handlerssignal.signal(signal.SIGINT, signal_handler)6 unmodified linesprint(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(1 unmodified lineshare=True,debug=True)except Exception as e:print(f"Error during initialization: {str(e)}")
app.py+168-201