jakewatson commited on
Commit
d9af773
·
1 Parent(s): 6b58b65

pushing new occam

Browse files
Files changed (2) hide show
  1. app.py +65 -73
  2. app2.py +163 -0
app.py CHANGED
@@ -3,27 +3,30 @@ from huggingface_hub import InferenceClient
3
  import torch
4
  from transformers import pipeline
5
 
6
- # Inference client setup
 
 
 
7
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
- pipe = pipeline("text-generation", "microsoft/Phi-3-mini-4k-instruct", torch_dtype=torch.bfloat16, device_map="auto")
9
 
10
- # Global flag to handle cancellation
11
  stop_inference = False
12
 
13
- # Default system message
14
  DEFAULT_SYSTEM_MESSAGE = (
15
- "You are a helpful chatbot who answers questions according to Occam's razor, "
16
  "which suggests that the simplest explanation is usually the best one. Answer as concisely as possible. "
17
  "DO NOT explain everything in 3-5 paragraphs. Only provide the single simplest possible answer or solution. "
18
  "Ensure that the answer is still clearly explained to a user who does not understand, "
19
- "but avoid long and drawn out answers to simple questions. Prioritize speed of answering."
20
  )
21
 
 
22
  def respond(
23
  message,
24
- history: list[tuple[str, str]],
25
- system_message,
26
- max_tokens=512,
27
  temperature=0.7,
28
  top_p=0.95,
29
  use_local_model=False,
@@ -35,65 +38,51 @@ def respond(
35
  if history is None:
36
  history = []
37
 
38
- # Use `system_message` from the state
 
 
 
 
 
 
 
39
  if use_local_model:
40
- # Local inference
41
- messages = [{"role": "system", "content": system_message}]
42
- for val in history:
43
- if val[0]:
44
- messages.append({"role": "user", "content": val[0]})
45
- if val[1]:
46
- messages.append({"role": "assistant", "content": val[1]})
47
- messages.append({"role": "user", "content": message})
48
-
49
- response = ""
50
- for output in pipe(
51
- messages,
52
  max_new_tokens=max_tokens,
53
- temperature=temperature,
54
  do_sample=True,
55
- top_p=top_p,
56
- ):
57
- if stop_inference:
58
- response = "Inference cancelled."
59
- yield history + [(message, response)]
60
- return
61
- token = output['generated_text'][-1]['content']
62
- response += token
63
- yield history + [(message, response)] # Yield history + new response
64
-
65
- else:
66
- # API-based inference
67
- messages = [{"role": "system", "content": system_message}]
68
- for val in history:
69
- if val[0]:
70
- messages.append({"role": "user", "content": val[0]})
71
- if val[1]:
72
- messages.append({"role": "assistant", "content": val[1]})
73
- messages.append({"role": "user", "content": message})
74
-
75
- response = ""
76
- for message_chunk in client.chat_completion(
77
- messages,
78
- max_tokens=max_tokens,
79
- stream=True,
80
  temperature=temperature,
81
- top_p=top_p,
82
- ):
83
- if stop_inference:
84
- response = "Inference cancelled."
85
- yield history + [(message, response)]
86
- return
87
- token = message_chunk.choices[0].delta.content
88
- response += token
89
- yield history + [(message, response)] # Yield history + new response
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
  def cancel_inference():
93
  global stop_inference
94
  stop_inference = True
95
 
96
- # Custom CSS for a fancy look
97
  custom_css = """
98
  #main-container {
99
  background-color: #f0f0f0;
@@ -133,31 +122,34 @@ custom_css = """
133
  }
134
  """
135
 
136
- # Define the interface
137
  with gr.Blocks(css=custom_css) as demo:
138
- gr.Markdown("<h1 style='text-align: center;'>🪒 Occam's Chatbot 🪒</h1>")
139
- gr.Markdown("The simplest solution is often the best...")
140
 
141
- # Define a persistent state for the system message
142
  system_message_state = gr.State(value=DEFAULT_SYSTEM_MESSAGE)
143
 
144
- # Checkbox to toggle local model usage
145
- use_local_model = gr.Checkbox(label="Use Local Model", value=False)
146
-
147
- # Parameters for model control
148
- max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
149
- temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
150
- top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
151
 
152
- # Chat components
153
  chat_history = gr.Chatbot(label="Chat")
154
- user_input = gr.Textbox(show_label=False, placeholder="Type your message here...")
 
 
 
 
 
 
 
155
  cancel_button = gr.Button("Cancel Inference", variant="danger")
156
 
157
- # Pass the `system_message_state` to the `respond` function
158
  user_input.submit(respond, [user_input, chat_history, system_message_state, max_tokens, temperature, top_p, use_local_model], chat_history)
159
 
 
160
  cancel_button.click(cancel_inference)
161
 
162
  if __name__ == "__main__":
163
- demo.launch(share=False) # Remove share=True because it's not supported on HF Spaces
 
3
  import torch
4
  from transformers import pipeline
5
 
6
+ # Set up the local model (Phi-3-mini-4k-instruct) for text generation
7
+ local_pipe = pipeline("text-generation", model="microsoft/Phi-3-mini-4k-instruct", torch_dtype=torch.bfloat16, device_map="auto")
8
+
9
+ # Set up the Inference client for API-based inference (Zephyr 7B model)
10
  client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
 
11
 
12
+ # Global flag for stopping inference (if needed)
13
  stop_inference = False
14
 
15
+ # Occam's Razor-themed system message
16
  DEFAULT_SYSTEM_MESSAGE = (
17
+ "You are a helpful chatbot who answers questions according to Occam's Razor, "
18
  "which suggests that the simplest explanation is usually the best one. Answer as concisely as possible. "
19
  "DO NOT explain everything in 3-5 paragraphs. Only provide the single simplest possible answer or solution. "
20
  "Ensure that the answer is still clearly explained to a user who does not understand, "
21
+ "but avoid long and drawn-out answers to simple questions. Prioritize speed of answering."
22
  )
23
 
24
+ # Function to generate responses
25
  def respond(
26
  message,
27
+ history,
28
+ system_message=DEFAULT_SYSTEM_MESSAGE,
29
+ max_tokens=256,
30
  temperature=0.7,
31
  top_p=0.95,
32
  use_local_model=False,
 
38
  if history is None:
39
  history = []
40
 
41
+ # Prepare the chat messages with the system message and conversation history
42
+ messages = [{"role": "system", "content": system_message}]
43
+ for user_input, bot_response in history:
44
+ messages.append({"role": "user", "content": user_input})
45
+ messages.append({"role": "assistant", "content": bot_response})
46
+ messages.append({"role": "user", "content": message})
47
+
48
+ # Generate response based on the model selected
49
  if use_local_model:
50
+ # Use local model (Phi-3-mini-4k-instruct)
51
+ prompt = local_pipe.tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
52
+ output = local_pipe(
53
+ prompt,
 
 
 
 
 
 
 
 
54
  max_new_tokens=max_tokens,
 
55
  do_sample=True,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
56
  temperature=temperature,
57
+ top_p=top_p
58
+ )
59
+ response_text = output[0]["generated_text"].split("<|assistant|>")[-1].strip()
 
 
 
 
 
 
60
 
61
+ else:
62
+ # Use API-based model (Zephyr 7B)
63
+ response_text = ""
64
+ try:
65
+ response = client.chat_completion(
66
+ messages=messages,
67
+ max_tokens=max_tokens,
68
+ temperature=temperature,
69
+ top_p=top_p,
70
+ stream=False
71
+ )
72
+ response_text = response['choices'][0]['message']['content']
73
+ except Exception as e:
74
+ print(f"Error in API response: {e}")
75
+ response_text = "Error generating response"
76
+
77
+ # Append the user message and model response to history
78
+ history.append((message, response_text))
79
+ return history
80
 
81
  def cancel_inference():
82
  global stop_inference
83
  stop_inference = True
84
 
85
+ # Custom CSS for Gradio interface styling
86
  custom_css = """
87
  #main-container {
88
  background-color: #f0f0f0;
 
122
  }
123
  """
124
 
125
+ # Define the Gradio interface
126
  with gr.Blocks(css=custom_css) as demo:
127
+ gr.Markdown("<h1 style='text-align: center;'>🪒 Occam's Razor Chatbot 🪒</h1>")
128
+ gr.Markdown("Occam's Razor is the problem-solving principle that recommends searching for explanations constructed with the smallest possible set of elements.")
129
 
130
+ # System message state
131
  system_message_state = gr.State(value=DEFAULT_SYSTEM_MESSAGE)
132
 
133
+ # Toggle to use the local model or API
134
+ use_local_model = gr.Checkbox(label="Use Local Model (Phi-3-mini-4k-instruct)", value=False)
 
 
 
 
 
135
 
136
+ # Chat interface elements
137
  chat_history = gr.Chatbot(label="Chat")
138
+ user_input = gr.Textbox(show_label=False, placeholder="The simplest solution is usually the best...")
139
+
140
+ # Control sliders
141
+ max_tokens = gr.Slider(minimum=1, maximum=512, value=256, step=1, label="Max Tokens")
142
+ temperature = gr.Slider(minimum=0.1, maximum=2.0, value=0.7, step=0.1, label="Temperature")
143
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p")
144
+
145
+ # Cancel button
146
  cancel_button = gr.Button("Cancel Inference", variant="danger")
147
 
148
+ # Submit the input and generate response
149
  user_input.submit(respond, [user_input, chat_history, system_message_state, max_tokens, temperature, top_p, use_local_model], chat_history)
150
 
151
+ # Cancel inference button
152
  cancel_button.click(cancel_inference)
153
 
154
  if __name__ == "__main__":
155
+ demo.launch(share=False)
app2.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from huggingface_hub import InferenceClient
3
+ import torch
4
+ from transformers import pipeline
5
+
6
+ # Inference client setup
7
+ client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
8
+ pipe = pipeline("text-generation", "microsoft/Phi-3-mini-4k-instruct", torch_dtype=torch.bfloat16, device_map="auto")
9
+
10
+ # Global flag to handle cancellation
11
+ stop_inference = False
12
+
13
+ # Default system message
14
+ DEFAULT_SYSTEM_MESSAGE = (
15
+ "You are a helpful chatbot who answers questions according to Occam's razor, "
16
+ "which suggests that the simplest explanation is usually the best one. Answer as concisely as possible. "
17
+ "DO NOT explain everything in 3-5 paragraphs. Only provide the single simplest possible answer or solution. "
18
+ "Ensure that the answer is still clearly explained to a user who does not understand, "
19
+ "but avoid long and drawn out answers to simple questions. Prioritize speed of answering."
20
+ )
21
+
22
+ def respond(
23
+ message,
24
+ history: list[tuple[str, str]],
25
+ system_message,
26
+ max_tokens=512,
27
+ temperature=0.7,
28
+ top_p=0.95,
29
+ use_local_model=False,
30
+ ):
31
+ global stop_inference
32
+ stop_inference = False # Reset cancellation flag
33
+
34
+ # Initialize history if it's None
35
+ if history is None:
36
+ history = []
37
+
38
+ # Use `system_message` from the state
39
+ if use_local_model:
40
+ # Local inference
41
+ messages = [{"role": "system", "content": system_message}]
42
+ for val in history:
43
+ if val[0]:
44
+ messages.append({"role": "user", "content": val[0]})
45
+ if val[1]:
46
+ messages.append({"role": "assistant", "content": val[1]})
47
+ messages.append({"role": "user", "content": message})
48
+
49
+ response = ""
50
+ for output in pipe(
51
+ messages,
52
+ max_new_tokens=max_tokens,
53
+ temperature=temperature,
54
+ do_sample=True,
55
+ top_p=top_p,
56
+ ):
57
+ if stop_inference:
58
+ response = "Inference cancelled."
59
+ yield history + [(message, response)]
60
+ return
61
+ token = output['generated_text'][-1]['content']
62
+ response += token
63
+ yield history + [(message, response)] # Yield history + new response
64
+
65
+ else:
66
+ # API-based inference
67
+ messages = [{"role": "system", "content": system_message}]
68
+ for val in history:
69
+ if val[0]:
70
+ messages.append({"role": "user", "content": val[0]})
71
+ if val[1]:
72
+ messages.append({"role": "assistant", "content": val[1]})
73
+ messages.append({"role": "user", "content": message})
74
+
75
+ response = ""
76
+ for message_chunk in client.chat_completion(
77
+ messages,
78
+ max_tokens=max_tokens,
79
+ stream=True,
80
+ temperature=temperature,
81
+ top_p=top_p,
82
+ ):
83
+ if stop_inference:
84
+ response = "Inference cancelled."
85
+ yield history + [(message, response)]
86
+ return
87
+ token = message_chunk.choices[0].delta.content
88
+ response += token
89
+ yield history + [(message, response)] # Yield history + new response
90
+
91
+
92
+ def cancel_inference():
93
+ global stop_inference
94
+ stop_inference = True
95
+
96
+ # Custom CSS for a fancy look
97
+ custom_css = """
98
+ #main-container {
99
+ background-color: #f0f0f0;
100
+ font-family: 'Arial', sans-serif;
101
+ }
102
+ .gradio-container {
103
+ max-width: 700px;
104
+ margin: 0 auto;
105
+ padding: 20px;
106
+ background: white;
107
+ box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
108
+ border-radius: 10px;
109
+ }
110
+ .gr-button {
111
+ background-color: #4CAF50;
112
+ color: white;
113
+ border: none;
114
+ border-radius: 5px;
115
+ padding: 10px 20px;
116
+ cursor: pointer;
117
+ transition: background-color 0.3s ease;
118
+ }
119
+ .gr-button:hover {
120
+ background-color: #45a049;
121
+ }
122
+ .gr-slider input {
123
+ color: #4CAF50;
124
+ }
125
+ .gr-chat {
126
+ font-size: 16px;
127
+ }
128
+ #title {
129
+ text-align: center;
130
+ font-size: 2em;
131
+ margin-bottom: 20px;
132
+ color: #333;
133
+ }
134
+ """
135
+
136
+ # Define the interface
137
+ with gr.Blocks(css=custom_css) as demo:
138
+ gr.Markdown("<h1 style='text-align: center;'>🪒 Occam's Chatbot 🪒</h1>")
139
+ gr.Markdown("Occam's Razor is the problem-solving principle that recommends searching for explanations constructed with the smallest possible set of elements.")
140
+
141
+ # Define a persistent state for the system message
142
+ system_message_state = gr.State(value=DEFAULT_SYSTEM_MESSAGE)
143
+
144
+ # Checkbox to toggle local model usage
145
+ use_local_model = gr.Checkbox(label="Use Local Model", value=False)
146
+
147
+ # Parameters for model control
148
+ max_tokens = gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens")
149
+ temperature = gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature")
150
+ top_p = gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)")
151
+
152
+ # Chat components
153
+ chat_history = gr.Chatbot(label="Chat")
154
+ user_input = gr.Textbox(show_label=False, placeholder="The simplest solution is often the best...")
155
+ cancel_button = gr.Button("Cancel Inference", variant="danger")
156
+
157
+ # Pass the `system_message_state` to the `respond` function
158
+ user_input.submit(respond, [user_input, chat_history, system_message_state, max_tokens, temperature, top_p, use_local_model], chat_history)
159
+
160
+ cancel_button.click(cancel_inference)
161
+
162
+ if __name__ == "__main__":
163
+ demo.launch(share=False) # Remove share=True because it's not supported on HF Spaces