alex4cip Claude commited on
Commit
bfd0656
·
1 Parent(s): 0155077

feat: Add 3 Korean LLM models and update dependencies

Browse files

Major Features:
- Add EXAONE 3.5 7.8B Instruct (파라미터 대비 최고 효율)
- Add EXAONE 3.5 2.4B Instruct (초경량, 빠른 응답)
- Add Llama-3 Open-Ko 8B (Llama 3 생태계)
- Expand model selection from 10 to 13 models (10 Public + 3 Gated)

Model Management Improvements:
- Implement lazy loading: models load on first use, not startup
- Add cache detection with check_model_cached() function
- Display cache status in UI (cached vs. downloading)
- Add .env file loading with python-dotenv
- Support gated models with HF_TOKEN authentication
- Add detailed logging for model loading process

Dependency Updates:
- gradio: 5.9.1 → 5.49.1
- transformers: 4.46.0 → 4.57.1
- torch: 2.1.0 → 2.9.0
- safetensors: 0.4.5 → 0.6.2
- Add python-dotenv==1.0.0 for .env file support
- Remove unused dependencies (accelerate, spaces)

Technical Changes:
- Implement loaded_model_name tracking for lazy loading
- Add huggingface_hub.scan_cache_dir() for cache detection
- Update UI messages to clarify cache vs download status
- Change deprecated torch_dtype to dtype parameter
- All 13 models verified on Hugging Face

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <[email protected]>

Files changed (2) hide show
  1. app.py +239 -44
  2. requirements.txt +7 -6
app.py CHANGED
@@ -15,33 +15,180 @@ except ImportError:
15
  import os
16
  import gradio as gr
17
  from transformers import AutoModelForCausalLM, AutoTokenizer
 
18
  import torch
19
 
 
 
 
 
 
 
 
 
20
  # Get HF token from environment
21
  HF_TOKEN = os.getenv("HF_TOKEN", None)
22
-
23
- # Model configuration
24
- MODEL_NAME = "beomi/llama-2-ko-7b"
25
- MODEL_CONFIG = {
26
- "name": "Llama-2-Ko 7B (한글 대화형)",
27
- "max_length": 150,
28
- }
29
-
30
- # Global model cache (loaded once)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31
  model = None
32
  tokenizer = None
33
 
34
 
35
- def load_model_once():
36
- """Load model and tokenizer once at startup"""
37
- global model, tokenizer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- if model is None:
40
- print(f"🔄 Loading model: {MODEL_NAME}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
42
  # Load tokenizer
 
43
  tokenizer = AutoTokenizer.from_pretrained(
44
- MODEL_NAME,
45
  token=HF_TOKEN,
46
  trust_remote_code=True,
47
  )
@@ -54,12 +201,16 @@ def load_model_once():
54
  print(f"📍 Using device: {device}")
55
 
56
  # Load model with appropriate settings
 
 
 
 
57
  if device == "cuda":
58
  # GPU available (CPU Upgrade with GPU or ZeroGPU)
59
  model = AutoModelForCausalLM.from_pretrained(
60
- MODEL_NAME,
61
  token=HF_TOKEN,
62
- torch_dtype=torch.float16, # Use float16 for GPU
63
  low_cpu_mem_usage=True,
64
  trust_remote_code=True,
65
  device_map="auto",
@@ -67,16 +218,20 @@ def load_model_once():
67
  else:
68
  # CPU only
69
  model = AutoModelForCausalLM.from_pretrained(
70
- MODEL_NAME,
71
  token=HF_TOKEN,
72
- torch_dtype=torch.float32, # Use float32 for CPU
73
  low_cpu_mem_usage=True,
74
  trust_remote_code=True,
75
  )
76
  model.to(device)
77
 
78
  model.eval()
79
- print(f"✅ Model {MODEL_NAME} loaded successfully")
 
 
 
 
80
 
81
  return model, tokenizer
82
 
@@ -117,12 +272,15 @@ def generate_response_impl(message, history):
117
  inputs = encoded['input_ids'].to(device)
118
  attention_mask = encoded['attention_mask'].to(device)
119
 
 
 
 
120
  # Generate response
121
  with torch.no_grad():
122
  outputs = current_model.generate(
123
  inputs,
124
  attention_mask=attention_mask,
125
- max_new_tokens=MODEL_CONFIG["max_length"],
126
  temperature=0.7,
127
  top_p=0.9,
128
  do_sample=True,
@@ -180,37 +338,44 @@ hardware_info = "NVIDIA H200 (ZeroGPU)" if ZEROGPU_AVAILABLE else "CPU Upgrade (
180
  print(f"✅ App initialized - Hardware: {hardware_info}")
181
 
182
  # Create Gradio interface
183
- with gr.Blocks(title="🤖 Llama-2-Ko Chatbot") as demo:
184
  # Dynamic header based on hardware
185
  if ZEROGPU_AVAILABLE:
186
  header = """
187
- # 🤖 Llama-2-Ko 7B Chatbot (ZeroGPU)
188
 
189
- **모델**: Llama-2-Ko 7B (한글 대화형 모델)
190
  **하드웨어**: NVIDIA H200 (ZeroGPU - 자동 할당)
191
 
192
  **특징**:
193
  - ⚡ GPU 가속으로 빠른 응답 (3-5초)
194
- - 🇰🇷 한글 대화에 최적화
195
- - 🔄 첫 응답은 모델 로딩으로 조금 소요될 수 있습니다
196
  - 💰 PRO 구독 시 하루 25분 무료 사용
197
  """
198
  else:
199
  header = """
200
- # 🤖 Llama-2-Ko 7B Chatbot (CPU Upgrade)
201
 
202
- **모델**: Llama-2-Ko 7B (한글 대화형 모델)
203
  **하드웨어**: CPU Upgrade (8 vCPU / 32 GB RAM)
204
 
205
  **특징**:
206
- - 🇰🇷 한글 대화에 최적화
207
- - 🔄 응답은 모델 로딩으로 조금 더 소요될 수 있습니다 (10-15초)
208
  - ⏳ CPU 환경이므로 응답이 다소 느립니다 (30초~1분)
209
  - 💰 시간당 $0.03 (월 약 $22)
210
  """
211
 
212
  gr.Markdown(header)
213
 
 
 
 
 
 
 
 
 
 
214
  chatbot = gr.Chatbot(height=400, type="messages", show_label=False)
215
 
216
  with gr.Row():
@@ -223,19 +388,47 @@ with gr.Blocks(title="🤖 Llama-2-Ko Chatbot") as demo:
223
 
224
  clear = gr.Button("🗑️ 대화 초기화", size="sm")
225
 
 
 
 
 
 
 
 
 
 
 
 
226
  def submit(message, history):
 
 
227
  # Immediately show user message
228
  updated_history = history + [{"role": "user", "content": message}]
229
  yield updated_history, ""
230
 
231
- # Show "thinking" indicator
232
- thinking_history = updated_history + [{"role": "assistant", "content": "🤔 응답 생성 중..."}]
233
- yield thinking_history, ""
 
 
 
 
 
 
 
 
 
 
 
 
 
234
 
235
- # Generate and add bot response
236
  final_history = chat_wrapper(message, history)
237
  yield final_history, ""
238
 
 
 
239
  btn.click(submit, [msg, chatbot], [chatbot, msg])
240
  msg.submit(submit, [msg, chatbot], [chatbot, msg])
241
  clear.click(lambda: [], outputs=chatbot)
@@ -245,29 +438,31 @@ with gr.Blocks(title="🤖 Llama-2-Ko Chatbot") as demo:
245
  footer = """
246
  ---
247
  **참고사항 (ZeroGPU 모드)**:
248
- - ZeroGPU는 요청 자동으로 GPU를 할당합니다
249
- - PRO 구독자는 하루 25분 무료 사용 가능
250
- - 응답은 모델 로딩 시간 포함 (~10-15초)
251
- - 이후 응답은 빠르게 생성됩니다 (~3-5초)
 
252
 
253
  **테스트 예시**:
254
  - "안녕하세요"
255
  - "인공지능에 대해 설명해주세요"
256
- - "오늘 날씨가 어때요?"
257
  """
258
  else:
259
  footer = """
260
  ---
261
  **참고사항 (CPU Upgrade 모드)**:
262
- - CPU 환경에서 실행되므로 응답이 느립니다 (30초~1분)
263
- - 응답은 모델 로딩 시간 포함 (~1-2분)
264
- - 24시간 무제한 사용 가능 (시간당 $0.03)
265
- - GPU 환경(ZeroGPU)으로 전환 빠른 응답 가능
 
266
 
267
  **테스트 예시**:
268
  - "안녕하세요"
269
  - "인공지능에 대해 설명해주세요"
270
- - "오늘 날씨가 어때요?"
271
  """
272
 
273
  gr.Markdown(footer)
 
15
  import os
16
  import gradio as gr
17
  from transformers import AutoModelForCausalLM, AutoTokenizer
18
+ from huggingface_hub import snapshot_download
19
  import torch
20
 
21
+ # Load environment variables from .env file
22
+ try:
23
+ from dotenv import load_dotenv
24
+ load_dotenv() # Load .env file into environment
25
+ print("✅ .env file loaded")
26
+ except ImportError:
27
+ print("⚠️ python-dotenv not installed, using system environment variables only")
28
+
29
  # Get HF token from environment
30
  HF_TOKEN = os.getenv("HF_TOKEN", None)
31
+ if HF_TOKEN:
32
+ print(f"✅ HF_TOKEN loaded (length: {len(HF_TOKEN)} chars)")
33
+ else:
34
+ print("⚠️ HF_TOKEN not found in environment - some models may not be accessible")
35
+
36
+ # Model configurations (10 Public + 3 Gated models = 13 total)
37
+ # Note: Gated models require HF access approval at https://huggingface.co/[model-name]
38
+ MODEL_CONFIGS = [
39
+ {
40
+ "MODEL_NAME": "LGAI-EXAONE/EXAONE-3.5-7.8B-Instruct",
41
+ "MODEL_CONFIG": {
42
+ "name": "EXAONE 3.5 7.8B Instruct ⭐ (파라미터 대비 최고 효율)",
43
+ "max_length": 150,
44
+ },
45
+ },
46
+ {
47
+ "MODEL_NAME": "LGAI-EXAONE/EXAONE-3.5-2.4B-Instruct",
48
+ "MODEL_CONFIG": {
49
+ "name": "EXAONE 3.5 2.4B Instruct ⚡ (초경량, 빠른 응답)",
50
+ "max_length": 150,
51
+ },
52
+ },
53
+ {
54
+ "MODEL_NAME": "beomi/Llama-3-Open-Ko-8B",
55
+ "MODEL_CONFIG": {
56
+ "name": "Llama-3 Open-Ko 8B 🔥 (Llama 3 생태계)",
57
+ "max_length": 150,
58
+ },
59
+ },
60
+ {
61
+ "MODEL_NAME": "Qwen/Qwen2.5-7B-Instruct",
62
+ "MODEL_CONFIG": {
63
+ "name": "Qwen2.5 7B Instruct (한글 지시응답 우수)",
64
+ "max_length": 150,
65
+ },
66
+ },
67
+ {
68
+ "MODEL_NAME": "Qwen/Qwen2.5-14B-Instruct",
69
+ "MODEL_CONFIG": {
70
+ "name": "Qwen2.5 14B Instruct (다국어·한글 강점, 여유 GPU 권장)",
71
+ "max_length": 150,
72
+ },
73
+ },
74
+ {
75
+ "MODEL_NAME": "meta-llama/Llama-3.1-8B-Instruct",
76
+ "MODEL_CONFIG": {
77
+ "name": "Llama 3.1 8B Instruct 🔒 (커뮤니티 Ko 튜닝 활발, 승인 필요)",
78
+ "max_length": 150,
79
+ },
80
+ },
81
+ {
82
+ "MODEL_NAME": "meta-llama/Llama-3.1-70B-Instruct",
83
+ "MODEL_CONFIG": {
84
+ "name": "Llama 3.1 70B Instruct 🔒 (대규모·한글 품질 우수, 승인 필요)",
85
+ "max_length": 150,
86
+ },
87
+ },
88
+ {
89
+ "MODEL_NAME": "01-ai/Yi-1.5-9B-Chat",
90
+ "MODEL_CONFIG": {
91
+ "name": "Yi 1.5 9B Chat (다국어/한글 안정적 대화)",
92
+ "max_length": 150,
93
+ },
94
+ },
95
+ {
96
+ "MODEL_NAME": "01-ai/Yi-1.5-34B-Chat",
97
+ "MODEL_CONFIG": {
98
+ "name": "Yi 1.5 34B Chat (긴 문맥·한글 생성 강점)",
99
+ "max_length": 150,
100
+ },
101
+ },
102
+ {
103
+ "MODEL_NAME": "mistralai/Mistral-7B-Instruct-v0.3",
104
+ "MODEL_CONFIG": {
105
+ "name": "Mistral 7B Instruct v0.3 (경량·한글 커뮤니티 튜닝 多)",
106
+ "max_length": 150,
107
+ },
108
+ },
109
+ {
110
+ "MODEL_NAME": "upstage/SOLAR-10.7B-Instruct-v1.0",
111
+ "MODEL_CONFIG": {
112
+ "name": "Solar 10.7B Instruct v1.0 (한국어 강점, 실전 지시응답)",
113
+ "max_length": 150,
114
+ },
115
+ },
116
+ {
117
+ "MODEL_NAME": "EleutherAI/polyglot-ko-5.8b",
118
+ "MODEL_CONFIG": {
119
+ "name": "Polyglot-Ko 5.8B (한국어 중심 베이스)",
120
+ "max_length": 150,
121
+ },
122
+ },
123
+ {
124
+ "MODEL_NAME": "CohereForAI/aya-23-8B",
125
+ "MODEL_CONFIG": {
126
+ "name": "Aya-23 8B 🔒 (다국어·한국어 지원 양호, 승인 필요)",
127
+ "max_length": 150,
128
+ },
129
+ },
130
+ ]
131
+
132
+ # Default model
133
+ current_model_index = 0
134
+ loaded_model_name = None # Track which model is currently loaded
135
+
136
+ # Global model cache
137
  model = None
138
  tokenizer = None
139
 
140
 
141
+ def check_model_cached(model_name):
142
+ """Check if model is already downloaded in HF cache"""
143
+ try:
144
+ from huggingface_hub import scan_cache_dir
145
+ cache_info = scan_cache_dir()
146
+
147
+ # Check if model exists in cache
148
+ for repo in cache_info.repos:
149
+ if repo.repo_id == model_name:
150
+ return True
151
+ return False
152
+ except Exception as e:
153
+ # If unable to check cache, assume not cached
154
+ print(f" ⚠️ Unable to check cache: {e}")
155
+ return False
156
+
157
+
158
+ def load_model_once(model_index=None):
159
+ """Load model and tokenizer based on selected index (lazy loading)"""
160
+ global model, tokenizer, current_model_index, loaded_model_name
161
+
162
+ if model_index is None:
163
+ model_index = current_model_index
164
 
165
+ # Get model config
166
+ model_name = MODEL_CONFIGS[model_index]["MODEL_NAME"]
167
+
168
+ # Check if we need to reload (different model or not loaded yet)
169
+ if loaded_model_name != model_name:
170
+ print(f"🔄 Loading model: {model_name}")
171
+ print(f" Previous model: {loaded_model_name or 'None'}")
172
+
173
+ # Check if model is already cached
174
+ is_cached = check_model_cached(model_name)
175
+ if is_cached:
176
+ print(f" ✅ Model found in cache, loading from disk...")
177
+ else:
178
+ print(f" 📥 Model not in cache, will download (~4-14GB depending on model)...")
179
+
180
+ # Clear previous model
181
+ if model is not None:
182
+ print(f" 🗑️ Unloading previous model from memory...")
183
+ del model
184
+ del tokenizer
185
+ if torch.cuda.is_available():
186
+ torch.cuda.empty_cache()
187
 
188
  # Load tokenizer
189
+ print(f" 📝 Loading tokenizer...")
190
  tokenizer = AutoTokenizer.from_pretrained(
191
+ model_name,
192
  token=HF_TOKEN,
193
  trust_remote_code=True,
194
  )
 
201
  print(f"📍 Using device: {device}")
202
 
203
  # Load model with appropriate settings
204
+ if is_cached:
205
+ print(f" 📀 Loading model from disk cache (15-30 seconds)...")
206
+ else:
207
+ print(f" 🌐 Downloading model from network (5-20 minutes, first time only)...")
208
  if device == "cuda":
209
  # GPU available (CPU Upgrade with GPU or ZeroGPU)
210
  model = AutoModelForCausalLM.from_pretrained(
211
+ model_name,
212
  token=HF_TOKEN,
213
+ dtype=torch.float16, # Use float16 for GPU
214
  low_cpu_mem_usage=True,
215
  trust_remote_code=True,
216
  device_map="auto",
 
218
  else:
219
  # CPU only
220
  model = AutoModelForCausalLM.from_pretrained(
221
+ model_name,
222
  token=HF_TOKEN,
223
+ dtype=torch.float32, # Use float32 for CPU
224
  low_cpu_mem_usage=True,
225
  trust_remote_code=True,
226
  )
227
  model.to(device)
228
 
229
  model.eval()
230
+ current_model_index = model_index
231
+ loaded_model_name = model_name
232
+ print(f"✅ Model {model_name} loaded successfully")
233
+ else:
234
+ print(f"ℹ️ Model {model_name} already loaded, reusing...")
235
 
236
  return model, tokenizer
237
 
 
272
  inputs = encoded['input_ids'].to(device)
273
  attention_mask = encoded['attention_mask'].to(device)
274
 
275
+ # Get current model config
276
+ model_config = MODEL_CONFIGS[current_model_index]["MODEL_CONFIG"]
277
+
278
  # Generate response
279
  with torch.no_grad():
280
  outputs = current_model.generate(
281
  inputs,
282
  attention_mask=attention_mask,
283
+ max_new_tokens=model_config["max_length"],
284
  temperature=0.7,
285
  top_p=0.9,
286
  do_sample=True,
 
338
  print(f"✅ App initialized - Hardware: {hardware_info}")
339
 
340
  # Create Gradio interface
341
+ with gr.Blocks(title="🤖 Multi-Model Chatbot") as demo:
342
  # Dynamic header based on hardware
343
  if ZEROGPU_AVAILABLE:
344
  header = """
345
+ # 🤖 다중 모델 챗봇 (ZeroGPU)
346
 
 
347
  **하드웨어**: NVIDIA H200 (ZeroGPU - 자동 할당)
348
 
349
  **특징**:
350
  - ⚡ GPU 가속으로 빠른 응답 (3-5초)
351
+ - 🎯 10가지 한글 최적화 모델 선택 가능
352
+ - 🔄 모델 전환 자동 재로딩
353
  - 💰 PRO 구독 시 하루 25분 무료 사용
354
  """
355
  else:
356
  header = """
357
+ # 🤖 다중 모델 챗봇 (CPU Upgrade)
358
 
 
359
  **하드웨어**: CPU Upgrade (8 vCPU / 32 GB RAM)
360
 
361
  **특징**:
362
+ - 🎯 10가지 한글 최적화 모델 선택 가능
363
+ - 🔄 ��델 전환 자동 재로딩
364
  - ⏳ CPU 환경이므로 응답이 다소 느립니다 (30초~1분)
365
  - 💰 시간당 $0.03 (월 약 $22)
366
  """
367
 
368
  gr.Markdown(header)
369
 
370
+ # Model selector
371
+ model_choices = [f"{cfg['MODEL_CONFIG']['name']}" for cfg in MODEL_CONFIGS]
372
+ model_dropdown = gr.Dropdown(
373
+ choices=model_choices,
374
+ value=model_choices[0],
375
+ label="🤖 모델 선택",
376
+ interactive=True,
377
+ )
378
+
379
  chatbot = gr.Chatbot(height=400, type="messages", show_label=False)
380
 
381
  with gr.Row():
 
388
 
389
  clear = gr.Button("🗑️ 대화 초기화", size="sm")
390
 
391
+ def change_model(selected_model):
392
+ """Handle model change"""
393
+ global current_model_index
394
+ # Find index of selected model
395
+ for idx, cfg in enumerate(MODEL_CONFIGS):
396
+ if cfg['MODEL_CONFIG']['name'] == selected_model:
397
+ current_model_index = idx
398
+ break
399
+ # Clear chat history when changing model
400
+ return []
401
+
402
  def submit(message, history):
403
+ global loaded_model_name, current_model_index
404
+
405
  # Immediately show user message
406
  updated_history = history + [{"role": "user", "content": message}]
407
  yield updated_history, ""
408
 
409
+ # Check if model needs to be loaded
410
+ selected_model_name = MODEL_CONFIGS[current_model_index]["MODEL_NAME"]
411
+ if loaded_model_name != selected_model_name:
412
+ # Check if model is cached
413
+ is_cached = check_model_cached(selected_model_name)
414
+ if is_cached:
415
+ # Model is cached, just loading from disk
416
+ loading_history = updated_history + [{"role": "assistant", "content": "💾 캐시된 모델 디스크에서 로딩 중... (15-30초, 다운로드 안 함)"}]
417
+ else:
418
+ # Model needs to be downloaded
419
+ loading_history = updated_history + [{"role": "assistant", "content": "📥 모델 다운로드 시작... (4-14GB, 첫 사용 시 5-20분 소요)"}]
420
+ yield loading_history, ""
421
+ else:
422
+ # Show "thinking" indicator
423
+ thinking_history = updated_history + [{"role": "assistant", "content": "🤔 응답 생성 중..."}]
424
+ yield thinking_history, ""
425
 
426
+ # Generate and add bot response (this will load model if needed)
427
  final_history = chat_wrapper(message, history)
428
  yield final_history, ""
429
 
430
+ # Event handlers
431
+ model_dropdown.change(change_model, inputs=[model_dropdown], outputs=[chatbot])
432
  btn.click(submit, [msg, chatbot], [chatbot, msg])
433
  msg.submit(submit, [msg, chatbot], [chatbot, msg])
434
  clear.click(lambda: [], outputs=chatbot)
 
438
  footer = """
439
  ---
440
  **참고사항 (ZeroGPU 모드)**:
441
+ - 🤖 10가지 모델 선택 가능 (드롭다운에서 선택)
442
+ - ZeroGPU는 요청 자동으로 GPU를 할당합니다
443
+ - 💰 PRO 구독자는 하루 25분 무료 사용
444
+ - 🔄 모델 변경 대화 내역이 초기화됩니다
445
+ - ⏱️ 첫 응답은 모델 로딩 시간 포함 (~10-15초)
446
 
447
  **테스트 예시**:
448
  - "안녕하세요"
449
  - "인공지능에 대해 설명해주세요"
450
+ - "한국의 수도는 어디인가요?"
451
  """
452
  else:
453
  footer = """
454
  ---
455
  **참고사항 (CPU Upgrade 모드)**:
456
+ - 🤖 10가지 모델 선택 가능 (드롭다운에서 선택)
457
+ - 🔄 모델 변경 대화 내역이 초기화됩니다
458
+ - CPU 환경이므로 응답이 느립니다 (30초~1분)
459
+ - ⏱️ 응답은 모델 로딩 시간 포함 (~1-2분)
460
+ - 💰 24시간 무제한 사용 (시간당 $0.03)
461
 
462
  **테스트 예시**:
463
  - "안녕하세요"
464
  - "인공지능에 대해 설명해주세요"
465
+ - "한국의 수도는 어디인가요?"
466
  """
467
 
468
  gr.Markdown(footer)
requirements.txt CHANGED
@@ -1,6 +1,7 @@
1
- gradio==5.9.1
2
- transformers==4.46.0
3
- torch==2.1.0
4
- safetensors==0.4.5
5
- accelerate==0.26.1
6
- spaces
 
 
1
+ gradio==5.49.1
2
+ transformers==4.57.1
3
+ torch==2.9.0
4
+ safetensors==0.6.2
5
+ sentencepiece==0.2.0
6
+ protobuf==4.25.1
7
+ python-dotenv==1.0.0