Spaces:
Runtime error
Runtime error
File size: 7,825 Bytes
d7f0c69 66c8c43 5a2c966 14d9f28 18fb2e5 47d23e4 14d9f28 b63691e 14d9f28 b63691e 18fb2e5 b63691e 5a2c966 14d9f28 b63691e 14d9f28 18fb2e5 b63691e 5a2c966 d7f0c69 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 | 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"
)
|