Spaces:
Sleeping
Sleeping
Create app.py
Browse files1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374import gradio as grimport torchfrom transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfigfrom peft import PeftModel
# --- CONFIGURATION ---# The base model we used for fine-tuningbase_model_id = "google/gemma-2-2b-it"# Your adapter model ID from the Hub (from Step 2)hf_username = "fortify"repo_name = "gtkt-faq-gemma-adapter"adapter_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)
# 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!")
# --- 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 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?") with gr.Row(): question_box = gr.Textbox(label="Your Question") answer_box = gr.Textbox(label="AI Answer", interactive=False) submit_btn = gr.Button("Ask")
submit_btn.click( fn=generate_answer, inputs=question_box, outputs=answer_box, api_name="ask_faq" # This makes the API endpoint name predictable )
# Launch the Gradio appdemo.launch()app.pyAdded+74