kimhyunwoo commited on
Commit
662b714
·
verified ·
1 Parent(s): aeb4465

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +117 -60
app.py CHANGED
@@ -1,64 +1,121 @@
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, pipeline
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
+ # Model and tokenizer loading (with error handling)
6
+ try:
7
+ model_name = "google/gemma-3-1b-it" # Correct model name
8
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
9
+ model = AutoModelForCausalLM.from_pretrained(
10
+ model_name,
11
+ torch_dtype=torch.bfloat16, # Use bfloat16 for efficiency, if supported
12
+ device_map="auto", # Automatically use GPU if available, otherwise CPU
13
+ )
14
+ # Create the pipeline
15
+ pipe = pipeline(
16
+ "text-generation",
17
+ model=model,
18
+ tokenizer=tokenizer,
19
+ torch_dtype=torch.bfloat16, # Make sure pipeline also uses correct dtype
20
+ device_map="auto", # and device mapping
21
+ model_kwargs={"attn_implementation": "flash_attention_2"} # Enable Flash Attention 2 if supported by your hardware and transformers version
22
+ )
23
 
24
+ except Exception as e:
25
+ error_message = f"Error loading model or tokenizer: {e}"
26
+ print(error_message) # Log the error to the console
27
+ # Provide a fallback, even if it's just displaying the error.
28
+ def error_response(message, history):
29
+ return f"Model loading failed. Error: {error_message}"
30
+
31
+ # Minimal Gradio interface to show the error
32
+ with gr.Blocks() as demo:
33
+ gr.ChatInterface(error_response)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
34
  demo.launch()
35
+ exit() # Important: exit to prevent running the rest of the (broken) code
36
+
37
+
38
+ # Chat template handling (important for correct prompting)
39
+ def apply_chat_template(messages, chat_template=None):
40
+ """Applies the chat template to the message history.
41
+
42
+ Args:
43
+ messages: A list of dictionaries, where each dictionary has a "role"
44
+ ("user" or "assistant") and "content" key.
45
+ chat_template: The chat template string (optional). If None,
46
+ try to get from tokenizer.
47
+
48
+ Returns:
49
+ A single string representing the formatted conversation.
50
+ """
51
+ if chat_template is None:
52
+ if hasattr(tokenizer, "chat_template") and tokenizer.chat_template:
53
+ chat_template = tokenizer.chat_template
54
+ else:
55
+ # Fallback to a simple template if no chat template is found. This is
56
+ # *critical* to prevent the model from generating nonsensical output.
57
+ chat_template = "{% for message in messages %}" \
58
+ "{{ '<start_of_turn>' + message['role'] + '\n' + message['content'] + '<end_of_turn>\n' }}" \
59
+ "{% endfor %}" \
60
+ "{% if add_generation_prompt %}{{ '<start_of_turn>model\n' }}{% endif %}"
61
+
62
+ return tokenizer.apply_chat_template(
63
+ messages, tokenize=False, add_generation_prompt=True, chat_template=chat_template
64
+ )
65
+
66
+ # Prediction function (modified for chat)
67
+ def predict(message, history):
68
+ """Generates a response to the user's message.
69
+
70
+ Args:
71
+ message: The user's input message (string).
72
+ history: A list of (user_message, bot_response) tuples representing
73
+ the conversation history.
74
+
75
+ Returns:
76
+ The generated bot response (string).
77
+ """
78
+ # Build the conversation history in the required format.
79
+ messages = []
80
+ for user_msg, bot_response in history:
81
+ messages.append({"role": "user", "content": user_msg})
82
+ messages.append({"role": "model", "content": bot_response})
83
+ messages.append({"role": "user", "content": message})
84
+
85
+ # Apply the chat template.
86
+ prompt = apply_chat_template(messages)
87
+
88
+ # Generate the response using the pipeline (much cleaner).
89
+ try:
90
+ sequences = pipe(
91
+ prompt,
92
+ max_new_tokens=512, # Limit response length
93
+ do_sample=True, # Use sampling for more diverse responses
94
+ temperature=0.7, # Control randomness (higher = more random)
95
+ top_k=50, # Top-k sampling
96
+ top_p=0.95, # Nucleus sampling
97
+ repetition_penalty=1.2, # Reduce repetition
98
+ pad_token_id=tokenizer.eos_token_id, # Ensure padding is correct.
99
+
100
+ )
101
+ response = sequences[0]['generated_text'][len(prompt):].strip() # Extract *only* generated text
102
+ return response
103
+
104
+ except Exception as e:
105
+ return f"An error occurred during generation: {e}"
106
+
107
+
108
+ # Gradio interface (using gr.ChatInterface for a chatbot UI)
109
+ with gr.Blocks() as demo:
110
+ gr.ChatInterface(
111
+ predict,
112
+ chatbot=gr.Chatbot(height=500), # Set a reasonable height
113
+ textbox=gr.Textbox(placeholder="Ask me anything!", container=False, scale=7),
114
+ title="Gemma-3-1b-it Chatbot",
115
+ description="Chat with the Gemma-3-1b-it model.",
116
+ retry_btn=None, # Remove redundant buttons
117
+ undo_btn=None,
118
+ clear_btn=None,
119
+ )
120
+
121
+ demo.launch(share=False) # Set share=True to create a publicly shareable link