kimhyunwoo commited on
Commit
73d76b4
Β·
verified Β·
1 Parent(s): 0e79c3c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -48
app.py CHANGED
@@ -1,64 +1,137 @@
1
  import gradio as gr
2
- from huggingface_hub import InferenceClient
 
 
3
 
4
- """
5
- For more information on `huggingface_hub` Inference API support, please check the docs: https://huggingface.co/docs/huggingface_hub/v0.22.2/en/guides/inference
6
- """
7
- client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
- def respond(
11
- message,
12
- history: list[tuple[str, str]],
13
- system_message,
14
- max_tokens,
15
- temperature,
16
- top_p,
17
- ):
18
- messages = [{"role": "system", "content": system_message}]
19
 
20
- for val in history:
21
- if val[0]:
22
- messages.append({"role": "user", "content": val[0]})
23
- if val[1]:
24
- messages.append({"role": "assistant", "content": val[1]})
 
 
 
 
 
 
 
 
 
25
 
26
- messages.append({"role": "user", "content": message})
 
27
 
28
- response = ""
 
 
 
 
 
 
 
 
 
 
29
 
30
- for message in client.chat_completion(
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
- response += token
40
- yield response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
- respond,
48
- additional_inputs=[
49
- gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
50
- gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
51
- gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
52
- gr.Slider(
53
- minimum=0.1,
54
- maximum=1.0,
55
- value=0.95,
56
- step=0.05,
57
- label="Top-p (nucleus sampling)",
58
- ),
 
 
59
  ],
 
 
 
 
 
60
  )
61
 
62
-
63
  if __name__ == "__main__":
64
- demo.launch()
 
 
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()