Spaces:
Running
Running
Update app.py
Browse files
app.py
CHANGED
@@ -1,64 +1,137 @@
|
|
1 |
import gradio as gr
|
2 |
-
|
|
|
|
|
3 |
|
4 |
-
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
|
11 |
-
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
top_p,
|
17 |
-
):
|
18 |
-
messages = [{"role": "system", "content": system_message}]
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
|
24 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
25 |
|
26 |
-
|
|
|
27 |
|
28 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
29 |
|
30 |
-
|
31 |
-
messages,
|
32 |
-
max_tokens=max_tokens,
|
33 |
-
stream=True,
|
34 |
-
temperature=temperature,
|
35 |
-
top_p=top_p,
|
36 |
-
):
|
37 |
-
token = message.choices[0].delta.content
|
38 |
|
39 |
-
|
40 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
41 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
42 |
|
43 |
-
"""
|
44 |
-
For information on how to customize the ChatInterface, peruse the gradio docs: https://www.gradio.app/docs/chatinterface
|
45 |
-
"""
|
46 |
demo = gr.ChatInterface(
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
|
|
|
|
59 |
],
|
|
|
|
|
|
|
|
|
|
|
60 |
)
|
61 |
|
62 |
-
|
63 |
if __name__ == "__main__":
|
64 |
-
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import torch
|
3 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
4 |
+
import gc # Garbage collector
|
5 |
|
6 |
+
# --- Configuration ---
|
7 |
+
MODEL_ID = "naver-hyperclovax/HyperCLOVAX-SEED-Text-Instruct-0.5B"
|
8 |
+
MAX_NEW_TOKENS = 512 # Limit output length for faster response on CPU
|
9 |
+
SYSTEM_PROMPT = "- AI μΈμ΄λͺ¨λΈμ μ΄λ¦μ \"CLOVA X\" μ΄λ©° λ€μ΄λ²μμ λ§λ€μλ€.\n- μ¬μ©μμ μ§λ¬Έμ λν΄ μΉμ νκ³ μμΈνκ² λ΅λ³ν΄μΌ νλ€." # Simplified system prompt
|
10 |
|
11 |
+
# --- Model Loading ---
|
12 |
+
# Load model and tokenizer explicitly on CPU
|
13 |
+
# Using device_map='cpu' and torch_dtype=torch.float32 ensures it targets the CPU
|
14 |
+
print(f"Loading model: {MODEL_ID}...")
|
15 |
+
try:
|
16 |
+
model = AutoModelForCausalLM.from_pretrained(
|
17 |
+
MODEL_ID,
|
18 |
+
torch_dtype=torch.float32, # Use float32 for CPU compatibility
|
19 |
+
device_map="cpu" # Explicitly load on CPU
|
20 |
+
)
|
21 |
+
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
22 |
+
print("Model and tokenizer loaded successfully on CPU.")
|
23 |
+
# Ensure model is in evaluation mode
|
24 |
+
model.eval()
|
25 |
+
except Exception as e:
|
26 |
+
print(f"Error loading model: {e}")
|
27 |
+
# If loading fails, exit or handle gracefully
|
28 |
+
raise gr.Error(f"Failed to load the model {MODEL_ID}. Check logs. Error: {e}")
|
29 |
|
30 |
+
# Define stop tokens based on the example, get their IDs
|
31 |
+
stop_token_strings = ["<|endofturn|>", "<|stop|>"]
|
32 |
+
stop_token_ids = [tokenizer.convert_tokens_to_ids(token) for token in stop_token_strings]
|
33 |
+
# Also include the standard EOS token if it's different
|
34 |
+
if tokenizer.eos_token_id not in stop_token_ids:
|
35 |
+
stop_token_ids.append(tokenizer.eos_token_id)
|
|
|
|
|
|
|
36 |
|
37 |
+
# --- Inference Function ---
|
38 |
+
def predict(message, history):
|
39 |
+
"""
|
40 |
+
Generates a response using the HyperCLOVAX model based on user message and chat history.
|
41 |
+
"""
|
42 |
+
# Reconstruct chat history in the required format
|
43 |
+
chat_history_formatted = [
|
44 |
+
{"role": "tool_list", "content": ""}, # As per model card example structure
|
45 |
+
{"role": "system", "content": SYSTEM_PROMPT}
|
46 |
+
]
|
47 |
+
for user_msg, ai_msg in history:
|
48 |
+
chat_history_formatted.append({"role": "user", "content": user_msg})
|
49 |
+
# Add the endofturn token manually if needed, or rely on template
|
50 |
+
chat_history_formatted.append({"role": "assistant", "content": ai_msg }) # Ensure assistant response is captured correctly
|
51 |
|
52 |
+
# Add the current user message
|
53 |
+
chat_history_formatted.append({"role": "user", "content": message})
|
54 |
|
55 |
+
# Apply the chat template
|
56 |
+
try:
|
57 |
+
inputs = tokenizer.apply_chat_template(
|
58 |
+
chat_history_formatted,
|
59 |
+
add_generation_prompt=True, # Crucial for instruct models
|
60 |
+
return_dict=True,
|
61 |
+
return_tensors="pt"
|
62 |
+
).to(model.device) # Ensure inputs are on the CPU device
|
63 |
+
except Exception as e:
|
64 |
+
print(f"Error applying chat template: {e}")
|
65 |
+
return f"Error formatting input: {e}"
|
66 |
|
67 |
+
print(f"Input tokens: {inputs['input_ids'].shape[1]}") # Log input length
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
68 |
|
69 |
+
# Generate response - Use torch.no_grad() to save memory
|
70 |
+
try:
|
71 |
+
with torch.no_grad():
|
72 |
+
output_ids = model.generate(
|
73 |
+
**inputs,
|
74 |
+
max_new_tokens=MAX_NEW_TOKENS,
|
75 |
+
eos_token_id=stop_token_ids, # Use the identified stop token IDs
|
76 |
+
pad_token_id=tokenizer.eos_token_id, # Often set pad = eos
|
77 |
+
do_sample=True, # Sample for more diverse outputs
|
78 |
+
temperature=0.7,
|
79 |
+
top_p=0.9,
|
80 |
+
# Note: The original example used 'stop_strings' and passed the tokenizer,
|
81 |
+
# which isn't standard in `generate`. Using eos_token_id is preferred.
|
82 |
+
# If specific stopping behavior is needed beyond EOS, StoppingCriteria can be used.
|
83 |
+
)
|
84 |
+
except Exception as e:
|
85 |
+
print(f"Error during model generation: {e}")
|
86 |
+
# Clean up GPU memory if an error occurs (though we are on CPU, good practice)
|
87 |
+
gc.collect()
|
88 |
+
# Consider torch.cuda.empty_cache() if GPU was accidentally involved
|
89 |
+
return f"Error during generation: {e}"
|
90 |
|
91 |
+
# Decode only the newly generated tokens
|
92 |
+
input_length = inputs['input_ids'].shape[1]
|
93 |
+
new_tokens = output_ids[0, input_length:]
|
94 |
+
response = tokenizer.decode(new_tokens, skip_special_tokens=True)
|
95 |
+
|
96 |
+
print(f"Output tokens: {len(new_tokens)}") # Log output length
|
97 |
+
print(f"Raw response: {response}")
|
98 |
+
|
99 |
+
# Clean up memory (especially important in constrained environments)
|
100 |
+
del inputs
|
101 |
+
del output_ids
|
102 |
+
gc.collect()
|
103 |
+
# Consider torch.cuda.empty_cache() if GPU was involved
|
104 |
+
|
105 |
+
return response
|
106 |
+
|
107 |
+
# --- Gradio Interface ---
|
108 |
+
# Use ChatInterface for a conversational experience
|
109 |
+
chatbot = gr.Chatbot(label="HyperCLOVA X SEED (0.5B)", height=600)
|
110 |
|
|
|
|
|
|
|
111 |
demo = gr.ChatInterface(
|
112 |
+
fn=predict,
|
113 |
+
chatbot=chatbot,
|
114 |
+
title="π°π· HyperCLOVA X SEED (0.5B) - CPU Demo",
|
115 |
+
description=(
|
116 |
+
f"Chat with the `naver-hyperclovax/HyperCLOVAX-SEED-Text-Instruct-0.5B` model. "
|
117 |
+
f"This model excels in Korean language understanding. \n"
|
118 |
+
f"**Note:** Running on a free CPU Hugging Face Space. Responses will be **slow**. "
|
119 |
+
f"Max new tokens set to {MAX_NEW_TOKENS}."
|
120 |
+
),
|
121 |
+
examples=[
|
122 |
+
["μλ’°λ©κ±° λ°©μ μκ³Ό μμμνμ κ΄κ³λ₯Ό μ΅λν μμΈν μλ €μ€."],
|
123 |
+
["λ€μ΄λ² νμ΄νΌν΄λ‘λ°Xμ λν΄ μ€λͺ
ν΄μ€."],
|
124 |
+
["μ€λ λ μ¨ μ΄λ?"], # Example showing it might not know real-time data
|
125 |
+
["κ°λ¨ν νμ΄μ¬ μ½λ μμ λ₯Ό 보μ¬μ€."],
|
126 |
],
|
127 |
+
cache_examples=False, # Caching might consume too much memory/disk on free tier
|
128 |
+
theme="soft",
|
129 |
+
retry_btn=None,
|
130 |
+
undo_btn="Delete Previous Turn",
|
131 |
+
clear_btn="Clear Conversation",
|
132 |
)
|
133 |
|
134 |
+
# --- Launch the App ---
|
135 |
if __name__ == "__main__":
|
136 |
+
# queue() is important for handling multiple users, especially with slow inference
|
137 |
+
demo.queue().launch()
|