Spaces:
Sleeping
Sleeping
Update app.py
Browse files11 unmodified lines121314151617181920212215161718192021222324252627282930253233343526272829303132333435364041424337454647484950515238394054414243444560464748493 unmodified lines53545570565758735911 unmodified linesadapter_model_id = f"{hf_username}/{repo_name}"
# --- LOAD MODEL & TOKENIZER ---# Load the tokenizertokenizer = AutoTokenizer.from_pretrained(base_model_id)
# Quantization config for memory efficiencybnb_config = BitsAndBytesConfig( load_in_4bit=True, bnb_4bit_quant_type="nf4", bnb_4bit_compute_dtype=torch.bfloat16# This is now a simple, standard loading process.# No quantization, no PEFT, no bitsandbytes needed!tokenizer = AutoTokenizer.from_pretrained(model_id)model = AutoModelForCausalLM.from_pretrained( model_id, torch_dtype=torch.bfloat16, # Use bfloat16 for performance device_map="auto",)print("Merged model and tokenizer loaded successfully!")
# Load the base modelbase_model = AutoModelForCausalLM.from_pretrained( base_model_id, quantization_config=bnb_config, device_map="auto")
# Load the PEFT model (adapter) and merge it with the base modelmodel = PeftModel.from_pretrained(base_model, adapter_model_id)model = model.merge_and_unload()print("Model loaded and merged successfully!")# --- CREATE THE INFERENCE PIPELINE ---pipe = pipeline( "text-generation", model=model, tokenizer=tokenizer, max_new_tokens=150)
# --- DEFINE THE INFERENCE FUNCTION ---def generate_answer(question): """ Generates an answer to a given question using the fine-tuned model. """ # Format the prompt exactly as we did in training prompt = f"### Question:\n{question}\n\n### Answer:\n"
# Tokenize the input and generate the output inputs = tokenizer(prompt, return_tensors="pt").to("cuda") outputs = model.generate(**inputs, max_new_tokens=150)
# Decode the response and clean it up response_text = tokenizer.decode(outputs[0], skip_special_tokens=True) # Extract only the answer part result = pipe(prompt) response_text = result[0]['generated_text'] answer_part = response_text.split("### Answer:\n")[-1]
return answer_part.strip()
# --- CREATE THE GRADIO INTERFACE ---with gr.Blocks() as demo: gr.Markdown("# FAQ Chatbot\nWhat questions can I answer for you?") gr.Markdown("# FAQ Chatbot\nEnter your question below to get an answer from the fine-tuned AI.") with gr.Row(): question_box = gr.Textbox(label="Your Question") answer_box = gr.Textbox(label="AI Answer", interactive=False)3 unmodified lines fn=generate_answer, inputs=question_box, outputs=answer_box, api_name="ask_faq" # This makes the API endpoint name predictable api_name="ask_faq" )
# Launch the Gradio appdemo.launch()app.py+19-34