Spaces:
Runtime error
Runtime error
Download app.py from CSmart-AI/FAQ-Finetuning: direct link, hf CLI and curl.
- Browser
- Download file 7.83 kB
-
https://huggingface.co/spaces/CSmart-AI/FAQ-Finetuning/resolve/main/app.py
- Command line
-
hf download hf://spaces/CSmart-AI/FAQ-Finetuning/app.py
-
curl -L -o app.py https://huggingface.co/spaces/CSmart-AI/FAQ-Finetuning/resolve/main/app.py
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 | |
| # =============================== | |
| # ์์ ์ ๋ชจ๋ธ ๋ก๋ | |
| # =============================== | |
| 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 ์๋ํฌ์ธํธ | |
| # =============================== | |
| 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": "์ค๋ต๋ ธํธ๋ ์ด๋ป๊ฒ ์ ๋ฆฌํ ๊น์?" | |
| } | |
| } | |
| } | |
| } | |
| 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 | |
| ) | |
| 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" | |
| ) | |