FAQ-Finetuning / app.py
sparta02's picture
Update app.py
b63691e verified
Raw History Blame Contribute Delete
7.83 kB
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from transformers import AutoTokenizer, AutoModelForCausalLM
import torch
from typing import Optional
import uvicorn
# ===============================
# FastAPI ์•ฑ ์ดˆ๊ธฐํ™”
# ===============================
app = FastAPI(
title="Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API",
description="ํŒŒ์ธํŠœ๋‹๋œ Gemma ๋ชจ๋ธ์„ ํ†ตํ•ด ์งˆ๋ฌธ์— ๋‹ต๋ณ€ํ•˜๋Š” API",
version="1.0.0"
)
# ===============================
# ์ „์—ญ ๋ณ€์ˆ˜ (๋ชจ๋ธ ๋กœ๋“œ)
# ===============================
MODEL_PATH = "./gemma2-finetuned"
tokenizer = None
model = None
device = "cpu" # Hugging Face Spaces๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ CPU
# ===============================
# ์š”์ฒญ/์‘๋‹ต ๋ชจ๋ธ ์ •์˜
# ===============================
class QuestionRequest(BaseModel):
question: str
max_tokens: Optional[int] = 120
temperature: Optional[float] = 0.3
top_k: Optional[int] = 40
top_p: Optional[float] = 0.8
repetition_penalty: Optional[float] = 1.8
class Config:
json_schema_extra = {
"example": {
"question": "์˜ค๋‹ต๋…ธํŠธ๋Š” ์–ด๋–ป๊ฒŒ ์ •๋ฆฌํ• ๊นŒ์š”?",
"max_tokens": 120,
"temperature": 0.3
}
}
class AnswerResponse(BaseModel):
question: str
answer: str
full_output: str
model_path: str
device: str
class HealthResponse(BaseModel):
status: str
model_loaded: bool
device: str
# ===============================
# ์‹œ์ž‘ ์‹œ ๋ชจ๋ธ ๋กœ๋“œ
# ===============================
@app.on_event("startup")
async def load_model():
"""์„œ๋ฒ„ ์‹œ์ž‘ ์‹œ ๋ชจ๋ธ์„ ๋ฉ”๋ชจ๋ฆฌ์— ๋กœ๋“œ"""
global tokenizer, model
print("๐Ÿš€ ๋ชจ๋ธ ๋กœ๋“œ ์ค‘...")
try:
# ํ•„์š”ํ•œ ๋ชจ๋“ˆ๋“ค import
from peft import PeftModel
import os
# Hugging Face ํ† ํฐ ๊ฐ€์ ธ์˜ค๊ธฐ (Space Secret์—์„œ)
hf_token = os.environ.get("HF_TOKEN", None)
if hf_token:
print("โœ… Hugging Face ํ† ํฐ ํ™•์ธ๋จ")
else:
print("โš ๏ธ HF_TOKEN์ด ์„ค์ •๋˜์ง€ ์•Š์Œ (๊ณต๊ฐœ ๋ชจ๋ธ๋งŒ ์‚ฌ์šฉ ๊ฐ€๋Šฅ)")
# ๋ฒ ์ด์Šค ๋ชจ๋ธ๊ณผ LoRA adapter๋ฅผ ๋ถ„๋ฆฌํ•ด์„œ ๋กœ๋“œ
# ์บ์‹œ ๋””๋ ‰ํ† ๋ฆฌ ์„ค์ • (Docker ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์‚ฌ์šฉ)
cache_dir = os.environ.get("HF_HOME", "/tmp/hf_cache")
print(f" ๐Ÿ“ ์บ์‹œ ๋””๋ ‰ํ† ๋ฆฌ: {cache_dir}")
# 1. ๋ฒ ์ด์Šค ๋ชจ๋ธ ๋กœ๋“œ (google/gemma-2b) - CPU ์ตœ์ ํ™”
print(" ๐Ÿ“ฅ ๋ฒ ์ด์Šค ๋ชจ๋ธ ๋กœ๋“œ ์ค‘...")
base_model = AutoModelForCausalLM.from_pretrained(
"google/gemma-2b",
torch_dtype=torch.float32, # CPU์—์„œ๋Š” float32 ์‚ฌ์šฉ
device_map="cpu", # CPU๋กœ ๊ฐ•์ œ ์„ค์ •
token=hf_token,
cache_dir=cache_dir,
low_cpu_mem_usage=True, # ๋ฉ”๋ชจ๋ฆฌ ์‚ฌ์šฉ๋Ÿ‰ ์ตœ์ ํ™”
trust_remote_code=True # Gemma ๋ชจ๋ธ ํ˜ธํ™˜์„ฑ
)
# 2. LoRA adapter ๋กœ๋“œ
print(" ๐Ÿ“ฅ LoRA adapter ๋กœ๋“œ ์ค‘...")
model = PeftModel.from_pretrained(
base_model,
MODEL_PATH,
device_map="cpu" # CPU๋กœ ๊ฐ•์ œ ์„ค์ •
)
# 3. ํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ (๋ฒ ์ด์Šค ๋ชจ๋ธ๊ณผ ๋™์ผ)
tokenizer = AutoTokenizer.from_pretrained(
"google/gemma-2b",
token=hf_token,
cache_dir=cache_dir,
trust_remote_code=True
)
model = model.to(device)
model.eval() # ํ‰๊ฐ€ ๋ชจ๋“œ๋กœ ์„ค์ •
print(f"โœ… ๋ชจ๋ธ ๋กœ๋“œ ์™„๋ฃŒ! (Device: {device})")
except Exception as e:
print(f"โŒ ๋ชจ๋ธ ๋กœ๋“œ ์‹คํŒจ: {e}")
raise
# ===============================
# API ์—”๋“œํฌ์ธํŠธ
# ===============================
@app.get("/", response_model=dict)
async def root():
"""๋ฃจํŠธ ์—”๋“œํฌ์ธํŠธ - API ์ •๋ณด"""
return {
"message": "Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API ์„œ๋ฒ„",
"version": "1.0.0",
"description": "์ˆ˜ํ—˜์ƒ Q&A ๋‹ต๋ณ€ ๋ชจ๋ธ",
"endpoints": {
"health": "GET /health - ์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ",
"predict": "POST /predict - ์งˆ๋ฌธ์— ๋‹ต๋ณ€",
"docs": "GET /docs - API ๋ฌธ์„œ"
},
"usage": {
"example": {
"method": "POST",
"url": "/predict",
"body": {
"question": "์˜ค๋‹ต๋…ธํŠธ๋Š” ์–ด๋–ป๊ฒŒ ์ •๋ฆฌํ• ๊นŒ์š”?"
}
}
}
}
@app.get("/health", response_model=HealthResponse)
async def health_check():
"""์„œ๋ฒ„ ์ƒํƒœ ํ™•์ธ"""
return HealthResponse(
status="healthy" if model is not None else "model_not_loaded",
model_loaded=model is not None,
device=device
)
@app.post("/predict", response_model=AnswerResponse)
async def predict(request: QuestionRequest):
"""
์งˆ๋ฌธ์— ๋Œ€ํ•œ ๋‹ต๋ณ€ ์ƒ์„ฑ
- **question**: ๋‹ต๋ณ€์„ ์›ํ•˜๋Š” ์งˆ๋ฌธ
- **max_tokens**: ์ƒ์„ฑํ•  ์ตœ๋Œ€ ํ† ํฐ ์ˆ˜ (๊ธฐ๋ณธ๊ฐ’: 120)
- **temperature**: ์ƒ์„ฑ ๋‹ค์–‘์„ฑ ์กฐ์ ˆ (๊ธฐ๋ณธ๊ฐ’: 0.3, ๋‚ฎ์„์ˆ˜๋ก ๋ณด์ˆ˜์ )
- **top_k**: ์ƒ์œ„ k๊ฐœ ํ† ํฐ๋งŒ ๊ณ ๋ ค (๊ธฐ๋ณธ๊ฐ’: 40)
- **top_p**: nucleus sampling ํ™•๋ฅ  (๊ธฐ๋ณธ๊ฐ’: 0.8)
- **repetition_penalty**: ๋ฐ˜๋ณต ๋ฐฉ์ง€ ๊ฐ•๋„ (๊ธฐ๋ณธ๊ฐ’: 1.8)
"""
if model is None or tokenizer is None:
raise HTTPException(status_code=503, detail="๋ชจ๋ธ์ด ๋กœ๋“œ๋˜์ง€ ์•Š์•˜์Šต๋‹ˆ๋‹ค")
try:
# ํ”„๋กฌํ”„ํŠธ ์ƒ์„ฑ
prompt = f"์งˆ๋ฌธ: {request.question}\n๋‹ต๋ณ€:"
# ํ† ํฌ๋‚˜์ด์ง•
inputs = tokenizer(prompt, return_tensors="pt")
inputs = inputs.to(device)
# ๋‹ต๋ณ€ ์ƒ์„ฑ
with torch.no_grad():
outputs = model.generate(
**inputs,
max_new_tokens=request.max_tokens,
temperature=request.temperature,
top_k=request.top_k,
top_p=request.top_p,
do_sample=True,
repetition_penalty=request.repetition_penalty,
no_repeat_ngram_size=4,
eos_token_id=tokenizer.eos_token_id,
pad_token_id=tokenizer.pad_token_id,
)
# ๊ฒฐ๊ณผ ๋””์ฝ”๋”ฉ
full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)
# ๋‹ต๋ณ€ ๋ถ€๋ถ„๋งŒ ์ถ”์ถœ
answer_only = full_output
if "๋‹ต๋ณ€:" in full_output:
answer_only = full_output.split("๋‹ต๋ณ€:", 1)[1].strip()
# ๋‹ค์Œ ์งˆ๋ฌธ์ด ๋‚˜์˜ค๋ฉด ๊ทธ ์ „๊นŒ์ง€๋งŒ ์ถ”์ถœ
if "์งˆ๋ฌธ:" in answer_only:
answer_only = answer_only.split("์งˆ๋ฌธ:", 1)[0].strip()
# HTML ํƒœ๊ทธ๋‚˜ ์ด์ƒํ•œ ๋ฌธ์ž ์ œ๊ฑฐ
if "<" in answer_only:
answer_only = answer_only.split("<", 1)[0].strip()
return AnswerResponse(
question=request.question,
answer=answer_only,
full_output=full_output,
model_path=MODEL_PATH,
device=device
)
except Exception as e:
raise HTTPException(status_code=500, detail=f"๋‹ต๋ณ€ ์ƒ์„ฑ ์ค‘ ์˜ค๋ฅ˜ ๋ฐœ์ƒ: {str(e)}")
# ===============================
# ์„œ๋ฒ„ ์‹คํ–‰
# ===============================
if __name__ == "__main__":
print("="*70)
print("๐Ÿš€ Gemma ํŒŒ์ธํŠœ๋‹ ๋ชจ๋ธ API ์„œ๋ฒ„ ์‹œ์ž‘")
print("="*70)
print(f"๐Ÿ“ ์„œ๋ฒ„ ์ฃผ์†Œ: http://0.0.0.0:7860")
print(f"๐Ÿ“š API ๋ฌธ์„œ: http://0.0.0.0:7860/docs")
print(f"๐Ÿ”ง Device: {device}")
print("="*70)
uvicorn.run(
app,
host="0.0.0.0",
port=7860, # Hugging Face Spaces๋Š” 7860 ํฌํŠธ ์‚ฌ์šฉ
log_level="info"
)