Spaces:
Build error
Build error
Update app.py
Browse files18 unmodified lines192021222324252223247 unmodified lines32333439404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384353637680 unmodified lines718719720771772773774775776777778779721722723724725726727728729730731732218 unmodified lines95195295310041005100610071008100910109549551012101310141015101695695795895996096196296396496596696735 unmodified lines1003100410051058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110710061007100845 unmodified lines1054105510561159105710581059116311641060106110621063106410651066116611671168106710681069107010711072107311711074117310751076107711761177117810781079108010811180118111821183118411851186118711881189119010821083108410851192119311941195119610861087108810891090109110921093109410951096109710981099110011011203110211031104110512071208110611071108110911101111111211131210111411151116111711181213121411191120112112161122112311241125122112221126112711281224122511291130113112291230123112321233113211331134113511361137113811391140114111421235123612371238114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175124411761177117874 unmodified lines12531254125513251256125713271328132913301331133213331334125812591260126112621263126412651266126712681269127012711272127312741275127612771278133713381339134013411342134312791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325551 unmodified lines1877187818791901190219031904190519061907190819091910188018811882191218831884188518866 unmodified lines1893189418951925192618961897189818991 unmodified line19011902190319341935193619041905190618 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 os from transformers import AutoModelForCausalLM, AutoTokenizerimport torch7 unmodified lines# Threshold for confidence level to stop querying LLMCONFIDENCE_THRESHOLD = 3
class SharedLLM: """Singleton class to manage a single LLM instance""" _instance = None _model = None _tokenizer = None
@classmethod def get_instance(cls): if cls._instance is None: cls._instance = cls() return cls._instance
def __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
@property def model(self): return self._model
@property def tokenizer(self): return self._tokenizer
def 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 lines 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 instance text = f"Base: {agent.base}, Role: {agent.role}, Plugins: {', '.join(agent.plugins)}" agent_features.append(self.node_encoder(text)) """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 instance text = 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 lines suggested_rounds: int # Track suggested rounds from LLM or system
def 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()} """Use DynamicLLM instance directly""" # Generate response outputs = model.generate(**inputs, max_length=max_length) response = tokenizer.decode(outputs[0], skip_special_tokens=True) return response # Return is inside the function now 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 lines ROUNDS: [number 1-8]""" response = generate_llm_response(boss_prompt)
# Parse the response to extract agents and rounds try: agents_section, rounds_section = response.split("ROUNDS:") # Parse agents agent_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 agents lines = 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 3 while 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-8
except Exception as e: print(f"Error parsing LLM response: {e}") # Fallback default configuration with exactly 3 agents return [ {"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 returned rounds = min(max(1, int(rounds_section.strip())), 8) # Ensure rounds is between 1-8
return agent_specs[:3], rounds
@dataclass45 unmodified lines self.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 variables os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:512,expandable_segments:True' # More aggressive memory settings os.environ['PYTORCH_CUDA_ALLOC_CONF'] = ( 'max_split_size_mb:128,' 'expandable_segments:True,' 'garbage_collection_threshold:0.6' ) # Initialize memory tracking self.peak_memory = 0 self.current_memory = 0 # Enable cuda memory stats if torch.cuda.is_available(): torch.cuda.memory.set_per_process_memory_fraction(0.9) # Use 90% of available VRAM torch.cuda.empty_cache() gc.collect()
def optimize_memory(self): """Optimize GPU memory usage""" gc.collect() empty_cache() torch.cuda.empty_cache() if torch.cuda.is_available(): torch.cuda.synchronize()
def get_memory_stats(self): """Get current GPU memory statistics""" def force_memory_release(self): """Force release of CUDA memory""" 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 True torch.cuda.empty_cache() gc.collect() torch.cuda.synchronize() stats = self.get_memory_stats() available = torch.cuda.get_device_properties(0).total_memory / 1024**2 currently_available = available - stats['allocated'] return currently_available >= required_memory_mb # Reset peak memory stats torch.cuda.reset_peak_memory_stats() # Clear any remaining tensors for obj in gc.get_objects(): try: if torch.is_tensor(obj): del obj except Exception: pass class 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 optimization # More conservative model configuration self.model_config = { 'torch_dtype': torch.float16, 'low_cpu_mem_usage': True, 'device_map': 'auto', 'max_memory': {0: '40GB'}, # Adjust based on your GPU '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' 'revision': 'main', 'load_in_8bit': True, # Use 8-bit quantization 'use_cache': False # Disable KV cache to save memory } # Initialize tokenizer and model with memory management self._initialize_model() # Initialize in chunks self._initialize_model_in_chunks() # Other initializations... self.g_designer = g_designer self.current_role = None self.learning_manager = RoleLearningManager()
def _initialize_model(self): """Initialize model with memory management""" def _initialize_model_in_chunks(self): """Initialize model in chunks to manage memory better""" 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 ) print("Preparing for model load...") self.memory_manager.force_memory_release() print("Loading model in chunks...") # Load model configuration first config = AutoConfig.from_pretrained(self.model_name) # Load model in chunks self.model = None chunk_size = 1000000 # Adjust based on your GPU # Move model to GPU with memory optimization if torch.cuda.is_available(): self.model = self.model.half() # Use half precision self.model = self.model.to(self.memory_manager.device) for param_chunk in range(0, config.num_parameters, chunk_size): self.memory_manager.optimize_memory() if self.model is None: # First chunk - initialize model self.model = AutoModelForCausalLM.from_pretrained( self.model_name, config=config, **self.model_config ) else: # Load subsequent chunks chunk = AutoModelForCausalLM.from_pretrained( self.model_name, config=config, state_dict_chunk=slice(param_chunk, param_chunk + chunk_size), **self.model_config ) # Merge chunks self.model.load_state_dict( {**self.model.state_dict(), **chunk.state_dict()}, strict=False ) del chunk self.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() raise
def switch_role(self, role: str, context: Dict = None): """Switch LLM to a different role and load relevant experience""" self.current_role = role74 unmodified lines self.learning_manager.save_experience(role, experience)
class MultiAgentSystem: def __init__(self, g_designer: GDesigner): def __init__(self, g_designer: GDesigner, temperature: float = 1.0): self.g_designer = g_designer self.llm = DynamicLLM() self.current_task = None # Use shared LLM instance instead of creating new one self.llm = SharedLLM.get_instance()
#Add checkpoint interval self.checkpoint_interval = 10 # Save every 10 tasks self.temperature = temperature self.feedback_data = {} self.saved_tasks = {} self.current_agents = [] self.checkpoint_interval = 10 self.tasks_since_checkpoint = 0 self.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} ) # Fixed summarizer agent self.summarizer_agent = { "base": self.model_name, "role": "Summarizer", "specialty": "Information synthesis and consolidation", "plugins": ["text_analysis", "summary_generation"] } # Parse the response to extract agents and rounds try: agents_section, rounds_section = response.split("ROUNDS:") # Parse agents agent_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 agents lines = 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 3 while 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-8 except Exception as e: print(f"Error parsing LLM response: {e}") # Fallback default configuration return [ {"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"]} ], 3
return agent_specs[:3], rounds
551 unmodified lines print("Initializing GPU memory management...") memory_manager.optimize_memory() # Print initial memory stats stats = 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 management # Initialize components with single DynamicLLM instance print("Initializing LLM...") g_designer = GDesigner() shared_llm.g_designer = g_designer llm = DynamicLLM(g_designer) # This will be our only LLM instance # Register signal handlers signal.signal(signal.SIGINT, signal_handler)6 unmodified lines print(f"Cached: {stats['cached']:.2f} MB") print(f"Peak: {stats['max_allocated']:.2f} MB") # Launch Gradio interface if memory is sufficient if memory_manager.check_memory(required_memory_mb=1000): # Adjust value as needed if memory_manager.check_memory(required_memory_mb=1000): demo = create_gradio_interface() demo.queue() demo.launch(1 unmodified line share=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)}")app.py+168-201