Spaces:
Sleeping
Sleeping
Auto commit at 20-2025-08 18:09:40
Browse files
lily_llm_api/app_v2_250820_1805.py
DELETED
|
The diff for this file is too large to render.
See raw diff
|
|
|
lily_llm_api/models/polyglot_ko_1_3b_chat_250820_1805.py
DELETED
|
@@ -1,150 +0,0 @@
|
|
| 1 |
-
#!/usr/bin/env python3
|
| 2 |
-
"""
|
| 3 |
-
Polyglot-ko-1.3b-chat 모델 프로필
|
| 4 |
-
heegyu/polyglot-ko-1.3b-chat 모델용
|
| 5 |
-
"""
|
| 6 |
-
|
| 7 |
-
from typing import Dict, Any, Tuple
|
| 8 |
-
import torch
|
| 9 |
-
from transformers import AutoTokenizer, AutoModelForCausalLM
|
| 10 |
-
import logging
|
| 11 |
-
import os
|
| 12 |
-
from pathlib import Path
|
| 13 |
-
|
| 14 |
-
logger = logging.getLogger(__name__)
|
| 15 |
-
|
| 16 |
-
class PolyglotKo13bChatProfile:
|
| 17 |
-
"""Polyglot-ko-1.3b-chat 모델 프로필"""
|
| 18 |
-
|
| 19 |
-
def __init__(self):
|
| 20 |
-
self.model_name = "heegyu/polyglot-ko-1.3b-chat"
|
| 21 |
-
self.local_path = "./lily_llm_core/models/polyglot_ko_1_3b_chat"
|
| 22 |
-
self.display_name = "Polyglot-ko-1.3b-chat"
|
| 23 |
-
self.description = "한국어 채팅 전용 경량 모델 (1.3B)"
|
| 24 |
-
self.language = "ko"
|
| 25 |
-
self.model_size = "1.3B"
|
| 26 |
-
|
| 27 |
-
def load_model(self) -> Tuple[AutoModelForCausalLM, AutoTokenizer]:
|
| 28 |
-
"""모델 로드 (로컬 우선, 없으면 Hub)"""
|
| 29 |
-
logger.info(f"📥 {self.display_name} 모델 로드 중...")
|
| 30 |
-
try:
|
| 31 |
-
use_local = Path(self.local_path).exists() and any(Path(self.local_path).iterdir())
|
| 32 |
-
model_path = self.local_path if use_local else self.model_name
|
| 33 |
-
|
| 34 |
-
logger.info(f"🔍 모델 경로: {model_path} (local={'yes' if use_local else 'no'})")
|
| 35 |
-
|
| 36 |
-
tokenizer = AutoTokenizer.from_pretrained(
|
| 37 |
-
model_path,
|
| 38 |
-
use_fast=True,
|
| 39 |
-
trust_remote_code=True,
|
| 40 |
-
local_files_only=use_local,
|
| 41 |
-
)
|
| 42 |
-
if tokenizer.pad_token is None:
|
| 43 |
-
tokenizer.pad_token = tokenizer.eos_token
|
| 44 |
-
|
| 45 |
-
# CPU에서는 float32가 더 안정적, CUDA에서는 float16 사용
|
| 46 |
-
device = 'cuda' if torch.cuda.is_available() else 'cpu'
|
| 47 |
-
selected_dtype = torch.float16 if device == 'cuda' else torch.float32
|
| 48 |
-
|
| 49 |
-
model = AutoModelForCausalLM.from_pretrained(
|
| 50 |
-
model_path,
|
| 51 |
-
trust_remote_code=True,
|
| 52 |
-
torch_dtype=selected_dtype,
|
| 53 |
-
local_files_only=use_local,
|
| 54 |
-
).to(device)
|
| 55 |
-
|
| 56 |
-
logger.info(f"✅ {self.display_name} 모델 로드 성공! (device={device}, dtype={selected_dtype})")
|
| 57 |
-
return model, tokenizer
|
| 58 |
-
except Exception as e:
|
| 59 |
-
logger.error(f"❌ {self.display_name} 모델 로드 실패: {e}")
|
| 60 |
-
raise
|
| 61 |
-
|
| 62 |
-
def format_prompt(self, user_input: str) -> str:
|
| 63 |
-
"""프롬프트 포맷팅 - 채팅 형식 (최적화)"""
|
| 64 |
-
# 더 간결한 프롬프트로 토큰 수 줄임
|
| 65 |
-
prompt = f"""AI 챗봇입니다. 도움이 되고 유익한 내용을 제공하세요.
|
| 66 |
-
|
| 67 |
-
### 사용자:
|
| 68 |
-
{user_input}
|
| 69 |
-
|
| 70 |
-
### 챗봇:
|
| 71 |
-
"""
|
| 72 |
-
return prompt
|
| 73 |
-
|
| 74 |
-
def extract_response(self, full_text: str, formatted_prompt: str = None) -> str:
|
| 75 |
-
"""응답 추출 - 더 강력한 로직으로 개선"""
|
| 76 |
-
logger.info(f"--- Polyglot 응답 추출 시작 ---")
|
| 77 |
-
logger.info(f"전체 생성 텍스트 (Raw): \n---\n{full_text}\n---")
|
| 78 |
-
logger.info(f"사용된 프롬프트: {formatted_prompt}")
|
| 79 |
-
|
| 80 |
-
# 1순위: "### 챗봇:" 태그로 추출 시도
|
| 81 |
-
if "### 챗봇:" in full_text:
|
| 82 |
-
response = full_text.split("### 챗봇:")[-1].strip()
|
| 83 |
-
logger.info(f"✅ 성공: '### 챗봇:' 태그로 응답 추출")
|
| 84 |
-
logger.info(f"추출된 응답: {response}")
|
| 85 |
-
if response: # 빈 문자열이 아닌 경우에만 반환
|
| 86 |
-
return response
|
| 87 |
-
|
| 88 |
-
# 2순위: 프롬프트 제거로 추출 시도
|
| 89 |
-
if formatted_prompt and formatted_prompt in full_text:
|
| 90 |
-
response = full_text.replace(formatted_prompt, "").strip()
|
| 91 |
-
logger.info(f"✅ 성공: 프롬프트 제거로 응답 추출")
|
| 92 |
-
logger.info(f"추출된 응답: {response}")
|
| 93 |
-
if response: # 빈 문자열이 아닌 경우에만 반환
|
| 94 |
-
return response
|
| 95 |
-
|
| 96 |
-
# 3순위: 일반적인 프롬프트 패턴 제거 시도
|
| 97 |
-
clean_text = full_text.strip()
|
| 98 |
-
patterns_to_remove = [
|
| 99 |
-
"당신은 AI 챗봇입니다. 사용자에게 도움이 되고 유익한 내용을 제공해야합니다. 답변은 길고 자세하며 친절한 설명을 덧붙여서 작성하세요.",
|
| 100 |
-
"### 사용자:",
|
| 101 |
-
"### 챗봇:",
|
| 102 |
-
"사용자:",
|
| 103 |
-
"챗봇:",
|
| 104 |
-
"assistant:",
|
| 105 |
-
"user:"
|
| 106 |
-
]
|
| 107 |
-
|
| 108 |
-
for pattern in patterns_to_remove:
|
| 109 |
-
clean_text = clean_text.replace(pattern, "")
|
| 110 |
-
|
| 111 |
-
clean_text = clean_text.strip()
|
| 112 |
-
|
| 113 |
-
if clean_text and clean_text != full_text:
|
| 114 |
-
logger.info("✅ 성공: 패턴 제거로 응답 정리")
|
| 115 |
-
logger.info(f"정리된 응답: {clean_text}")
|
| 116 |
-
return clean_text
|
| 117 |
-
|
| 118 |
-
# 4순위: 전체 텍스트에서 불필요한 부분만 제거
|
| 119 |
-
final_response = full_text.strip()
|
| 120 |
-
logger.warning("⚠️ 경고: 특별한 응답 추출 패턴을 찾지 못했습니다. 전체 텍스트를 ��리하여 반환합니다.")
|
| 121 |
-
logger.info(f"최종 반환 텍스트: {final_response}")
|
| 122 |
-
return final_response
|
| 123 |
-
|
| 124 |
-
def get_generation_config(self) -> Dict[str, Any]:
|
| 125 |
-
"""생성 설정 - 속도 최적화"""
|
| 126 |
-
return {
|
| 127 |
-
"max_new_tokens": 64, # 128에서 64로 줄여서 속도 향상
|
| 128 |
-
"temperature": 0.7, # 적당한 창의성 유지
|
| 129 |
-
"do_sample": True, # 샘플링 활성화
|
| 130 |
-
"top_k": 40, # 50에서 40으로 줄여서 속도 향상
|
| 131 |
-
"top_p": 0.9, # nucleus sampling 유지
|
| 132 |
-
"repetition_penalty": 1.1, # 반복 방지
|
| 133 |
-
"no_repeat_ngram_size": 3, # n-gram 반복 방지
|
| 134 |
-
"pad_token_id": None, # 모델 기본값 사용
|
| 135 |
-
"eos_token_id": None, # 모델 기본값 사용
|
| 136 |
-
"use_cache": True, # 캐시 사용으로 속도 향상
|
| 137 |
-
"max_time": 60.0, # 60초 타임아웃
|
| 138 |
-
}
|
| 139 |
-
|
| 140 |
-
def get_model_info(self) -> Dict[str, Any]:
|
| 141 |
-
"""모델 정보"""
|
| 142 |
-
return {
|
| 143 |
-
"model_name": self.model_name,
|
| 144 |
-
"display_name": self.display_name,
|
| 145 |
-
"description": self.description,
|
| 146 |
-
"language": self.language,
|
| 147 |
-
"model_size": self.model_size,
|
| 148 |
-
"local_path": self.local_path,
|
| 149 |
-
"multimodal": False,
|
| 150 |
-
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|