Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891016 unmodified lines2728293031323334354 unmodified lines404142434445464748495051525354555657585960616210 unmodified lines737475767778798081828384858638 unmodified lines12512612712812913013113213313413513613713813914014114214345 unmodified lines1891901911921931941951961971981992002012022032042052062072082092102112122132142152167 unmodified lines22422522622722822923023123223341 unmodified lines27527627727827928028128228328428528628728828929029129229329429529629739 unmodified lines33733833934034134234334434534634734834935035135235335435535635735835936036136236336436518 unmodified lines3843853863873883893904 unmodified linesimport osfrom typing import List, Dict, Anyimport time# ConfigurationMODEL_ID = "facebook/MobileLLM-Pro"16 unmodified linesself.tokenizer = Noneself.device = Noneself.model_loaded = Falsedef load_model(self, version="instruct"):"""Load the MobileLLM-Pro model and tokenizer"""try:print(f"Loading MobileLLM-Pro ({version})...")4 unmodified linessubfolder=version)# Load modelself.model = AutoModelForCausalLM.from_pretrained(MODEL_ID,trust_remote_code=True,subfolder=version,torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,device_map="auto" if torch.cuda.is_available() else None)# Set deviceself.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")if not torch.cuda.is_available():self.model.to(self.device)self.model.eval()self.model_loaded = Trueprint(f"Model loaded successfully on {self.device}")return Trueexcept Exception as e:10 unmodified linesreturn messagesdef generate_response(self, user_input: str, history: List[Dict[str, str]],system_prompt: str, temperature: float = 0.7,max_new_tokens: int = MAX_NEW_TOKENS) -> str:"""Generate a response from the model"""if not self.model_loaded:return "Model not loaded. Please try loading the model first."try:# Add user message to historyhistory.append({"role": "user", "content": user_input})38 unmodified lines# Add assistant response to historyhistory.append({"role": "assistant", "content": response})return responseexcept Exception as e:return f"Error generating response: {str(e)}"def generate_stream(self, user_input: str, history: List[Dict[str, str]],system_prompt: str, temperature: float = 0.7):"""Generate a streaming response from the model"""if not self.model_loaded:yield "Model not loaded. Please try loading the model first."returntry:# Add user message to historyhistory.append({"role": "user", "content": user_input})45 unmodified lines# Add final response to historyhistory.append({"role": "assistant", "content": response})except Exception as e:yield f"Error generating response: {str(e)}"# Initialize chat modelchat_model = MobileLLMChat()def load_model_button(version):"""Load the model when button is clicked"""success = chat_model.load_model(version)if success:return gr.update(visible=False), gr.update(visible=True), gr.update(value="Model loaded successfully!")else:return gr.update(visible=True), gr.update(visible=False), gr.update(value="Failed to load model. Please check the logs.")def clear_chat():"""Clear the chat history"""return [], []def chat_fn(message, history, system_prompt, temperature, model_version):"""Main chat function"""if not chat_model.model_loaded:return "Please load the model first using the button above."# Convert history formatformatted_history = []7 unmodified linesreturn responsedef chat_stream_fn(message, history, system_prompt, temperature, model_version):"""Streaming chat function"""if not chat_model.model_loaded:yield "Please load the model first using the button above."return# Convert history format41 unmodified lines</div>""")# Model loading sectionwith gr.Row():with gr.Column(scale=1):model_version = gr.Dropdown(choices=["instruct", "base"],value="instruct",label="Model Version",info="Choose between instruct (chat) or base model")load_btn = gr.Button("🚀 Load Model", variant="primary", size="lg")with gr.Column(scale=2):model_status = gr.Textbox(label="Model Status",value="Model not loaded",interactive=False)# Configuration sectionwith gr.Accordion("⚙️ Configuration", open=False):39 unmodified linessubmit_btn = gr.Button("Send", variant="primary", scale=1)clear_btn = gr.Button("Clear", scale=0)# Event handlersload_btn.click(load_model_button,inputs=[model_version],outputs=[load_btn, model_status, model_status])# Handle chat submissiondef handle_chat(message, history, system_prompt, temperature, model_version, streaming):if streaming:return chat_stream_fn(message, history, system_prompt, temperature, model_version)else:return chat_fn(message, history, system_prompt, temperature, model_version)msg.submit(handle_chat,inputs=[msg, chatbot, system_prompt, temperature, model_version, streaming],outputs=[chatbot])submit_btn.click(handle_chat,inputs=[msg, chatbot, system_prompt, temperature, model_version, streaming],outputs=[chatbot])18 unmodified lines# Footergr.HTML("""<div style="text-align: center; margin-top: 20px; color: #666;"><p>⚠️ Note: This model requires significant computational resources. Loading may take a few minutes.</p><p>Model: <a href="https://huggingface.co/facebook/MobileLLM-Pro" target="_blank">facebook/MobileLLM-Pro</a></p></div>""")4 unmodified lines56789101116 unmodified lines28293031323334353637384 unmodified lines4344454647484950515253545556575859606110 unmodified lines7273747576777879808182838485868788899038 unmodified lines12913013113213313413513613713813914014114214314414514614714814915015115215315415515645 unmodified lines2022032042052062072082092102112122132142152162172182192202212222232242252267 unmodified lines23423523623723823924024124224341 unmodified lines28528628728828929029129229329429529629729839 unmodified lines33833934034134234334434534634734834935035135235335435535635735835918 unmodified lines3783793803813823833844 unmodified linesimport osfrom typing import List, Dict, Anyimport timeimport spaces# ConfigurationMODEL_ID = "facebook/MobileLLM-Pro"16 unmodified linesself.tokenizer = Noneself.device = Noneself.model_loaded = False# Load model on initialization for shared appself.load_model()def load_model(self, version="instruct"):"""Load the MobileLLM-Pro model and tokenizer - runs once on CPU/system memory"""try:print(f"Loading MobileLLM-Pro ({version})...")4 unmodified linessubfolder=version)# Load model to CPU first for shared appself.model = AutoModelForCausalLM.from_pretrained(MODEL_ID,trust_remote_code=True,subfolder=version,torch_dtype=torch.float16,low_cpu_mem_usage=True)# Model will be moved to GPU during inferenceself.model.eval()self.model_loaded = Trueprint(f"Model loaded successfully in system memory")return Trueexcept Exception as e:10 unmodified linesreturn messages@spaces.GPU(duration=120)def generate_response(self, user_input: str, history: List[Dict[str, str]],system_prompt: str, temperature: float = 0.7,max_new_tokens: int = MAX_NEW_TOKENS) -> str:"""Generate a response from the model - GPU allocated only during inference"""if not self.model_loaded:return "Model not loaded. Please try reloading the space."try:# Move model to GPU for inferenceself.device = torch.device("cuda")self.model.to(self.device)# Add user message to historyhistory.append({"role": "user", "content": user_input})38 unmodified lines# Add assistant response to historyhistory.append({"role": "assistant", "content": response})# Move model back to CPU after inference to free GPUself.model.to("cpu")torch.cuda.empty_cache()return responseexcept Exception as e:return f"Error generating response: {str(e)}"@spaces.GPU(duration=120)def generate_stream(self, user_input: str, history: List[Dict[str, str]],system_prompt: str, temperature: float = 0.7):"""Generate a streaming response from the model - GPU allocated only during inference"""if not self.model_loaded:yield "Model not loaded. Please try reloading the space."returntry:# Move model to GPU for inferenceself.device = torch.device("cuda")self.model.to(self.device)# Add user message to historyhistory.append({"role": "user", "content": user_input})45 unmodified lines# Add final response to historyhistory.append({"role": "assistant", "content": response})# Move model back to CPU after inference to free GPUself.model.to("cpu")torch.cuda.empty_cache()except Exception as e:yield f"Error generating response: {str(e)}"# Initialize chat model (loads model once on startup)print("Initializing MobileLLM-Pro model...")chat_model = MobileLLMChat()def clear_chat():"""Clear the chat history"""return [], []def chat_fn(message, history, system_prompt, temperature):"""Main chat function"""if not chat_model.model_loaded:return "Please wait for the model to load or reload the space."# Convert history formatformatted_history = []7 unmodified linesreturn responsedef chat_stream_fn(message, history, system_prompt, temperature):"""Streaming chat function"""if not chat_model.model_loaded:yield "Please wait for the model to load or reload the space."return# Convert history format41 unmodified lines</div>""")# Model status indicatorwith gr.Row():model_status = gr.Textbox(label="Model Status",value="Model loaded and ready!" if chat_model.model_loaded else "Model loading...",interactive=False,container=True)# Configuration sectionwith gr.Accordion("⚙️ Configuration", open=False):39 unmodified linessubmit_btn = gr.Button("Send", variant="primary", scale=1)clear_btn = gr.Button("Clear", scale=0)# Handle chat submissiondef handle_chat(message, history, system_prompt, temperature, streaming):if streaming:return chat_stream_fn(message, history, system_prompt, temperature)else:return chat_fn(message, history, system_prompt, temperature)msg.submit(handle_chat,inputs=[msg, chatbot, system_prompt, temperature, streaming],outputs=[chatbot])submit_btn.click(handle_chat,inputs=[msg, chatbot, system_prompt, temperature, streaming],outputs=[chatbot])18 unmodified lines# Footergr.HTML("""<div style="text-align: center; margin-top: 20px; color: #666;"><p>⚠️ Note: Model is pre-loaded for faster inference. GPU is allocated only during generation.</p><p>Model: <a href="https://huggingface.co/facebook/MobileLLM-Pro" target="_blank">facebook/MobileLLM-Pro</a></p></div>""")
app.py+50-56