Spaces:
Runtime error
Runtime error
| import torch | |
| from transformers import AutoModelForCausalLM, AutoTokenizer | |
| from peft import PeftModel | |
| import gradio as gr | |
| import os | |
| from huggingface_hub import login | |
| # Load Hugging Face token (ensure it's set in 'Secrets') | |
| hf_token = os.getenv("HUGGINGFACE_TOKEN") | |
| if hf_token: | |
| login(hf_token) | |
| print("β Successfully logged in to Hugging Face Hub") | |
| else: | |
| print("β Hugging Face token not found. Make sure it's set in 'Secrets'.") | |
| # Base model | |
| BASE_MODEL = "mistralai/Mistral-7B-Instruct-v0.1" | |
| FINETUNED_MODEL_DIR = "./finetuned_model" # Path to your adapter weights | |
| # Load tokenizer | |
| tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL) | |
| # Load base model (WITHOUT bitsandbytes) | |
| base_model = AutoModelForCausalLM.from_pretrained( | |
| BASE_MODEL, | |
| torch_dtype=torch.float32 # Ensure CPU compatibility | |
| ) | |
| # Move base model to CPU | |
| base_model.to("cpu") | |
| # Load LoRA adapter | |
| model = PeftModel.from_pretrained(base_model, FINETUNED_MODEL_DIR) | |
| # Merge adapter with base model | |
| model = model.merge_and_unload() | |
| # Move model to CPU (again, just to be sure) | |
| model.to("cpu") | |
| # Inference function | |
| def chat(message): | |
| inputs = tokenizer(message, return_tensors="pt").to("cpu") # Ensure inputs are on CPU | |
| output = model.generate(**inputs, max_new_tokens=100) | |
| response = tokenizer.decode(output[0], skip_special_tokens=True) | |
| return response | |
| # Gradio UI | |
| interface = gr.Interface( | |
| fn=chat, | |
| inputs="text", | |
| outputs="text", | |
| title="Chat with Mistral (Fine-Tuned)", | |
| description="Talk to a fine-tuned Mistral-7B model." | |
| ) | |
| if __name__ == "__main__": | |
| interface.launch() | |