Spaces:
Build error
Build error
Update app.py
Browse files1072 unmodified lines107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671528 unmodified lines269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827391072 unmodified linesclass 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):self.memory_manager = GPUMemoryManager()self.g_designer = GDesigner() # Initialize with default parametersself.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 = GDesigner()self._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:1528 unmodified linesllm = DynamicLLM()boss_agent = BossAgent(llm)system = DynamicMultiAgentSystem()with gr.Blocks() as interface:gr.Markdown("# Dynamic Agent System")with gr.Row():query = gr.Textbox(label="Enter your query",placeholder="What would you like the agents to help you with?",lines=3)with gr.Row():submit_btn = gr.Button("Process Query")with gr.Row():output = gr.Textbox(label="System Response",lines=10)def process_query(query):if not query.strip():return "Please enter a query"try:agent_specs, _ = boss_agent.process_query(query)system.initialize_roles(agent_specs)result = system.process_task({"query": query})return result.get('response', 'No response generated')except Exception as e:return f"Error processing query: {str(e)}"submit_btn.click(fn=process_query,inputs=query,outputs=output)interface.launch()1072 unmodified lines1073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081528 unmodified lines263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826591072 unmodified linesclass DynamicLLM:def __init__(self):self.model_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised"self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)self.model = self._initialize_model()def _initialize_model(self):config = AutoConfig.from_pretrained(self.model_name)model = AutoModelForCausalLM.from_pretrained(self.model_name,config=config,device_map='auto',torch_dtype=torch.float16)return modeldef generate_response(self, prompt: str, role: str = None) -> str:try:inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)outputs = self.model.generate(**inputs,max_length=512,temperature=0.7,do_sample=True)return self.tokenizer.decode(outputs[0], skip_special_tokens=True)except Exception as e:print(f"Error generating response: {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."""try:1528 unmodified linesllm = DynamicLLM()boss_agent = BossAgent(llm)system = DynamicMultiAgentSystem()def process_query(query: str) -> str:if not query.strip():return "Please enter a query"try:response = llm.generate_response(query)return response if response else "No response generated"except Exception as e:return f"Error processing query: {str(e)}"# Create Gradio interfaceinterface = gr.Interface(fn=process_query,inputs=gr.Textbox(lines=3, placeholder="Enter your query..."),outputs=gr.Textbox(),title="Dynamic LLM Query System")interface.launch()
app.py+38-118