Spaces:
Runtime error
Runtime error
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182import gradio as grfrom huggingface_hub import InferenceClientfrom transformers import AutoModelForCausalLMfrom peft import PeftModel# This automatically loads the base model mentioned in adapter_config.jsonmodel = AutoModelForCausalLM.from_pretrained("rishu834763/java-explainer-lora",device_map="auto",torch_dtype="auto",trust_remote_code=True # only needed for some gated/gated models)model = PeftModel.from_pretrained(model, "rishu834763/java-explainer-lora")def respond(message,history: list[dict[str, str]],system_message,max_tokens,temperature,top_p,hf_token: gr.OAuthToken,):"""For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference"""client = InferenceClient(token=hf_token.token, model="openai/gpt-oss-20b")messages = [{"role": "system", "content": system_message}]messages.extend(history)messages.append({"role": "user", "content": message})response = ""for message in client.chat_completion(messages,max_tokens=max_tokens,stream=True,temperature=temperature,top_p=top_p,):choices = message.choicestoken = ""if len(choices) and choices[0].delta.content:token = choices[0].delta.contentresponse += tokenyield response"""For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface"""chatbot = gr.ChatInterface(respond,type="messages",additional_inputs=[gr.Textbox(value="You are a friendly Chatbot.", label="System message"),gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),gr.Slider(minimum=0.1,maximum=1.0,value=0.95,step=0.05,label="Top-p (nucleus sampling)",),],)with gr.Blocks() as demo:with gr.Sidebar():gr.LoginButton()chatbot.render()if __name__ == "__main__":demo.launch()12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576import torchfrom transformers import AutoTokenizer, AutoModelForCausalLM, pipelinefrom peft import PeftModel, PeftConfigimport gradio as gr# === Load your LoRA correctly ===peft_model_id = "rishu834763/java-explainer-lora"config = PeftConfig.from_pretrained(peft_model_id)base_model_name = config.base_model_name_or_path # this will be mistralai/Mistral-7B-Instruct-v0.2# Load base model (with quantization if you want to fit in free tier)model = AutoModelForCausalLM.from_pretrained(base_model_name,torch_dtype=torch.bfloat16,device_map="auto",# Remove the two lines below if you have enough VRAM or a paid Space# load_in_4bit=True,# quantization_config=BitsAndBytesConfig(# load_in_4bit=True,# bnb_4bit_compute_dtype=torch.bfloat16,# bnb_4bit_use_double_quant=True,# bnb_4bit_quant_type="nf4"# ),)model = PeftModel.from_pretrained(model, peft_model_id)# Optional but recommended: merge so inference is faster and uses less VRAMmodel = model.merge_and_unload()tokenizer = AutoTokenizer.from_pretrained(base_model_name)if tokenizer.pad_token is None:tokenizer.pad_token = tokenizer.eos_token# Create the pipeline using YOUR model and tokenizerpipe = pipeline("text-generation",model=model,tokenizer=tokenizer,torch_dtype=torch.bfloat16,device_map="auto",)# === This is the most important part ===def chat(message, history):messages = []for user_msg, assistant_msg in history:messages.append({"role": "user", "content": user_msg})if assistant_msg:messages.append({"role": "assistant", "content": assistant_msg})messages.append({"role": "user", "content": message})outputs = pipe(messages,max_new_tokens=512,do_sample=True,temperature=0.7,top_p=0.9,pad_token_id=tokenizer.eos_token_id)response = outputs[0]["generated_text"][-1]["content"]return response# === Build the Gradio interface ===demo = gr.ChatInterface(fn=chat,title="Java Explainer (Mistral-7B + your LoRA)",description="Ask anything about Java code → I will explain it using your fine-tuned model",examples=["Explain this Java code: public class HelloWorld { public static void main(String[] args) { System.out.println(\"Hello, World!\"); } }","What does synchronized keyword do in Java?"],cache_examples=False,)demo.launch()
app.py+58-64