Spaces:
Running
on
Zero
Running
on
Zero
File size: 9,239 Bytes
f852c4e 9267136 e507147 e6a16df 9267136 e507147 11034e2 e507147 a97aa70 9267136 e507147 11034e2 e507147 9267136 e507147 9267136 e507147 b3fa588 9267136 e507147 f852c4e e507147 f0d0d46 e507147 f0d0d46 e507147 f852c4e e507147 f852c4e e507147 |
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 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 |
import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer
import gc
import os
import datetime
import time
import spaces
# --- μ€μ ---
MODEL_ID = "HyperCLOVAX-SEED-Vision-Instruct-3B"
MAX_NEW_TOKENS = 512
CPU_THREAD_COUNT = 4 # νμμ μ‘°μ
# --- μ ν μ¬ν: CPU μ€λ λ μ€μ ---
# torch.set_num_threads(CPU_THREAD_COUNT)
# os.environ["OMP_NUM_THREADS"] = str(CPU_THREAD_COUNT)
# os.environ["MKL_NUM_THREADS"] = str(CPU_THREAD_COUNT)
print("--- νκ²½ μ€μ ---")
print(f"PyTorch λ²μ : {torch.__version__}")
print(f"μ€ν μ₯μΉ: {torch.device('cuda' if torch.cuda.is_available() else 'cpu')}")
print(f"Torch μ€λ λ: {torch.get_num_threads()}")
# --- λͺ¨λΈ λ° ν ν¬λμ΄μ λ‘λ© ---
print(f"--- λͺ¨λΈ λ‘λ© μ€: {MODEL_ID} ---")
print("첫 μ€ν μ λͺ λΆ μ λ μμλ μ μμ΅λλ€...")
model = None
tokenizer = None
load_successful = False
stop_token_ids_list = [] # stop_token_ids_list μ΄κΈ°ν
try:
start_load_time = time.time()
# μμμ λ°λΌ device_map μ€μ
device_map = "auto" if torch.cuda.is_available() else "cpu"
dtype = torch.float16 if torch.cuda.is_available() else torch.float32
tokenizer = AutoTokenizer.from_pretrained(
MODEL_ID,
trust_remote_code=True
)
model = AutoModelForCausalLM.from_pretrained(
MODEL_ID,
torch_dtype=dtype,
device_map=device_map,
trust_remote_code=True
)
model.eval()
load_time = time.time() - start_load_time
print(f"--- λͺ¨λΈ λ° ν ν¬λμ΄μ λ‘λ© μλ£: {load_time:.2f}μ΄ μμ ---")
load_successful = True
# --- μ€μ§ ν ν° μ€μ ---
stop_token_strings = ["</s>", "<|endoftext|>"]
temp_stop_ids = [tokenizer.convert_tokens_to_ids(token) for token in stop_token_strings]
if tokenizer.eos_token_id is not None and tokenizer.eos_token_id not in temp_stop_ids:
temp_stop_ids.append(tokenizer.eos_token_id)
elif tokenizer.eos_token_id is None:
print("κ²½κ³ : tokenizer.eos_token_idκ° Noneμ
λλ€. μ€μ§ ν ν°μ μΆκ°ν μ μμ΅λλ€.")
stop_token_ids_list = [tid for tid in temp_stop_ids if tid is not None]
if not stop_token_ids_list:
print("κ²½κ³ : μ€μ§ ν ν° IDλ₯Ό μ°Ύμ μ μμ΅λλ€. κ°λ₯νλ©΄ κΈ°λ³Έ EOSλ₯Ό μ¬μ©νκ³ , κ·Έλ μ§ μμΌλ©΄ μμ±μ΄ μ¬λ°λ₯΄κ² μ€μ§λμ§ μμ μ μμ΅λλ€.")
if tokenizer.eos_token_id is not None:
stop_token_ids_list = [tokenizer.eos_token_id]
else:
print("μ€λ₯: κΈ°λ³Έ EOSλ₯Ό ν¬ν¨νμ¬ μ€μ§ ν ν°μ μ°Ύμ μ μμ΅λλ€. μμ±μ΄ 무νμ μ€νλ μ μμ΅λλ€.")
print(f"μ¬μ©ν μ€μ§ ν ν° ID: {stop_token_ids_list}")
except Exception as e:
print(f"!!! λͺ¨λΈ λ‘λ© μ€λ₯: {e}")
if 'model' in locals() and model is not None: del model
if 'tokenizer' in locals() and tokenizer is not None: del tokenizer
gc.collect()
raise gr.Error(f"λͺ¨λΈ {MODEL_ID} λ‘λ©μ μ€ν¨νμ΅λλ€. μ ν리μΌμ΄μ
μ μμν μ μμ΅λλ€. μ€λ₯: {e}")
# --- μμ€ν
ν둬ννΈ μ μ ---
def get_system_prompt():
current_date = datetime.datetime.now().strftime("%Y-%m-%d (%A)")
return (
f"- μ€λμ {current_date}μ
λλ€.\n"
f"- μ¬μ©μμ μ§λ¬Έμ λν΄ μΉμ νκ³ μμΈνκ² νκ΅μ΄λ‘ λ΅λ³ν΄μΌ ν©λλ€."
)
# --- μμ
ν¨μ ---
def warmup_model():
if not load_successful or model is None or tokenizer is None:
print("μμ
건λλ°κΈ°: λͺ¨λΈμ΄ μ±κ³΅μ μΌλ‘ λ‘λλμ§ μμμ΅λλ€.")
return
print("--- λͺ¨λΈ μμ
μμ ---")
try:
start_warmup_time = time.time()
warmup_message = "μλ
νμΈμ"
# λͺ¨λΈμ λ§λ νμμΌλ‘ μ
λ ₯ ꡬμ±
system_prompt = get_system_prompt()
# MiMo λͺ¨λΈμ ν둬ννΈ νμμ λ§κ² μ‘°μ
prompt = f"Human: {warmup_message}\nAssistant:"
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
# μ€μ§ ν ν°μ΄ λΉμ΄ μλμ§ νμΈνκ³ μ μ ν μ²λ¦¬
gen_kwargs = {
"max_new_tokens": 10,
"pad_token_id": tokenizer.eos_token_id if tokenizer.eos_token_id is not None else tokenizer.pad_token_id,
"do_sample": False
}
if stop_token_ids_list:
gen_kwargs["eos_token_id"] = stop_token_ids_list
else:
print("μμ
κ²½κ³ : μμ±μ μ μλ μ€μ§ ν ν°μ΄ μμ΅λλ€.")
with torch.no_grad():
output_ids = model.generate(**inputs, **gen_kwargs)
del inputs
del output_ids
gc.collect()
warmup_time = time.time() - start_warmup_time
print(f"--- λͺ¨λΈ μμ
μλ£: {warmup_time:.2f}μ΄ μμ ---")
except Exception as e:
print(f"!!! λͺ¨λΈ μμ
μ€ μ€λ₯ λ°μ: {e}")
finally:
gc.collect()
# --- μΆλ‘ ν¨μ ---
@spaces.GPU()
def predict(message, history):
"""
HyperCLOVAX-SEED-Vision-Instruct-3B λͺ¨λΈμ μ¬μ©νμ¬ μλ΅μ μμ±ν©λλ€.
'history'λ Gradio 'messages' νμμ κ°μ ν©λλ€: List[Dict].
"""
if model is None or tokenizer is None:
return "μ€λ₯: λͺ¨λΈμ΄ λ‘λλμ§ μμμ΅λλ€."
# λν κΈ°λ‘ μ²λ¦¬
history_text = ""
if isinstance(history, list):
for turn in history:
if isinstance(turn, tuple) and len(turn) == 2:
history_text += f"Human: {turn[0]}\nAssistant: {turn[1]}\n"
# MiMo λͺ¨λΈ μ
λ ₯ νμμ λ§κ² ν둬ννΈ κ΅¬μ±
prompt = f"{history_text}Human: {message}\nAssistant:"
inputs = None
output_ids = None
try:
# μ
λ ₯ μ€λΉ
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
input_length = inputs.input_ids.shape[1]
print(f"\nμ
λ ₯ ν ν° μ: {input_length}")
except Exception as e:
print(f"!!! μ
λ ₯ μ²λ¦¬ μ€ μ€λ₯ λ°μ: {e}")
return f"μ€λ₯: μ
λ ₯ νμμ μ²λ¦¬νλ μ€ λ¬Έμ κ° λ°μνμ΅λλ€. ({e})"
try:
print("μλ΅ μμ± μ€...")
generation_start_time = time.time()
# μμ± μΈμ μ€λΉ, λΉμ΄ μλ stop_token_ids_list μ²λ¦¬
gen_kwargs = {
"max_new_tokens": MAX_NEW_TOKENS,
"pad_token_id": tokenizer.eos_token_id if tokenizer.eos_token_id is not None else tokenizer.pad_token_id,
"do_sample": True,
"temperature": 0.7,
"top_p": 0.9,
"repetition_penalty": 1.1
}
if stop_token_ids_list:
gen_kwargs["eos_token_id"] = stop_token_ids_list
else:
print("μμ± κ²½κ³ : μ μλ μ€μ§ ν ν°μ΄ μμ΅λλ€.")
with torch.no_grad():
output_ids = model.generate(**inputs, **gen_kwargs)
generation_time = time.time() - generation_start_time
print(f"μμ± μλ£: {generation_time:.2f}μ΄ μμ.")
except Exception as e:
print(f"!!! λͺ¨λΈ μμ± μ€ μ€λ₯ λ°μ: {e}")
if inputs is not None: del inputs
if output_ids is not None: del output_ids
gc.collect()
return f"μ€λ₯: μλ΅μ μμ±νλ μ€ λ¬Έμ κ° λ°μνμ΅λλ€. ({e})"
# μλ΅ λμ½λ©
response = "μ€λ₯: μλ΅ μμ±μ μ€ν¨νμ΅λλ€."
if output_ids is not None:
try:
new_tokens = output_ids[0, input_length:]
response = tokenizer.decode(new_tokens, skip_special_tokens=True)
print(f"μΆλ ₯ ν ν° μ: {len(new_tokens)}")
del new_tokens
except Exception as e:
print(f"!!! μλ΅ λμ½λ© μ€ μ€λ₯ λ°μ: {e}")
response = "μ€λ₯: μλ΅μ λμ½λ©νλ μ€ λ¬Έμ κ° λ°μνμ΅λλ€."
# λ©λͺ¨λ¦¬ μ 리
if inputs is not None: del inputs
if output_ids is not None: del output_ids
gc.collect()
print("λ©λͺ¨λ¦¬ μ 리 μλ£.")
return response.strip()
# --- Gradio μΈν°νμ΄μ€ μ€μ ---
print("--- Gradio μΈν°νμ΄μ€ μ€μ μ€ ---")
examples = [
["μλ
νμΈμ! μκΈ°μκ° μ’ ν΄μ£ΌμΈμ."],
["μΈκ³΅μ§λ₯κ³Ό λ¨Έμ λ¬λμ μ°¨μ΄μ μ 무μμΈκ°μ?"],
["λ₯λ¬λ λͺ¨λΈ νμ΅ κ³Όμ μ λ¨κ³λ³λ‘ μλ €μ£ΌμΈμ."],
["μ μ£Όλ μ¬ν κ³νμ μΈμ°κ³ μλλ°, 3λ° 4μΌ μΆμ² μ½μ€ μ’ μλ €μ£ΌμΈμ."],
]
# ChatInterfaceλ₯Ό μ¬μ©νμ¬ μ체 Chatbot μ»΄ν¬λνΈ κ΄λ¦¬
demo = gr.ChatInterface(
fn=predict,
title="π€ HyperCLOVAX-SEED-Text-Instruct-0.5B",
description=(
f"**λͺ¨λΈ:** {MODEL_ID}\n"
),
examples=examples,
cache_examples=False,
theme=gr.themes.Soft(),
)
# --- μ ν리μΌμ΄μ
μ€ν ---
if __name__ == "__main__":
if load_successful:
warmup_model()
else:
print("λͺ¨λΈ λ‘λ©μ μ€ν¨νμ¬ μμ
μ 건λλλλ€.")
print("--- Gradio μ± μ€ν μ€ ---")
demo.queue().launch(
# share=True # κ³΅κ° λ§ν¬λ₯Ό μνλ©΄ μ£Όμ ν΄μ
# server_name="0.0.0.0" # λ‘컬 λ€νΈμν¬ μ κ·Όμ μνλ©΄ μ£Όμ ν΄μ
) |