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"
    )