SQL_chatbot_API / app.py
saadkhi's picture
Update app.py
0fad5f5 verified
raw
history blame
3.25 kB
# app.py - ZeroGPU safe: no caching + CPU load + GPU only in inference
import torch
import gradio as gr
import spaces
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import PeftModel
# ────────────────────────────────────────────────────────────────
BASE_MODEL = "unsloth/Phi-3-mini-4k-instruct-bnb-4bit"
LORA_PATH = "saadkhi/SQL_Chat_finetuned_model"
MAX_NEW_TOKENS = 180
TEMPERATURE = 0.0
DO_SAMPLE = False
print("Loading quantized base model on CPU (GPU only during inference)...")
bnb_config = BitsAndBytesConfig(
load_in_4bit=True,
bnb_4bit_quant_type="nf4",
bnb_4bit_compute_dtype=torch.bfloat16
)
model = AutoModelForCausalLM.from_pretrained(
BASE_MODEL,
quantization_config=bnb_config,
device_map="cpu", # ← Force CPU load at startup
trust_remote_code=True
)
print("Loading & merging LoRA...")
model = PeftModel.from_pretrained(model, LORA_PATH)
model = model.merge_and_unload() # Merge once for speed
tokenizer = AutoTokenizer.from_pretrained(BASE_MODEL)
model.eval()
# ────────────────────────────────────────────────────────────────
@spaces.GPU(duration=60) # Requests GPU slice only here
def generate_sql(prompt: str):
messages = [{"role": "user", "content": prompt}]
# Tokenize on CPU
inputs = tokenizer.apply_chat_template(
messages,
tokenize=True,
add_generation_prompt=True,
return_tensors="pt"
)
# Move to GPU only now (GPU is allocated)
inputs = inputs.to("cuda")
with torch.inference_mode():
outputs = model.generate(
input_ids=inputs,
max_new_tokens=MAX_NEW_TOKENS,
temperature=TEMPERATURE,
do_sample=DO_SAMPLE,
use_cache=True,
pad_token_id=tokenizer.eos_token_id,
)
response = tokenizer.decode(outputs[0], skip_special_tokens=True)
# Clean up output
if "<|assistant|>" in response:
response = response.split("<|assistant|>", 1)[-1].strip()
if "<|end|>" in response:
response = response.split("<|end|>")[0].strip()
return response
# ────────────────────────────────────────────────────────────────
demo = gr.Interface(
fn=generate_sql,
inputs=gr.Textbox(
label="Ask an SQL question",
placeholder="Delete duplicate rows from users table based on email",
lines=3
),
outputs=gr.Textbox(label="Generated SQL"),
title="SQL Chatbot (ZeroGPU)",
description="Phi-3-mini 4bit + LoRA - GPU only during generation",
examples=[
["Find duplicate emails in users table"],
["Top 5 highest paid employees"],
["Count orders per customer last month"]
],
cache_examples=False # ← This is critical! Prevents startup crash
)
if __name__ == "__main__":
demo.launch()