random2222 commited on
Commit
75342d8
·
verified ·
1 Parent(s): b8d5861

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +157 -55
app.py CHANGED
@@ -1,64 +1,166 @@
 
 
 
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
+ # app.py
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
  import gradio as gr
 
5
 
6
+ # Initialize variables
7
+ model = None
8
+ tokenizer = None
9
+ device = None
10
 
11
+ # Define function to load model
12
+ def load_model():
13
+ global model, tokenizer, device
14
+
15
+ # Use GPU if available
16
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
17
+ print(f"Using device: {device}")
18
+
19
+ # Load the Phi-2 model
20
+ model_id = "microsoft/phi-2"
21
+
22
+ print("Loading Phi-2 model and tokenizer...")
23
+ tokenizer = AutoTokenizer.from_pretrained(model_id)
24
+ model = AutoModelForCausalLM.from_pretrained(
25
+ model_id,
26
+ torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
27
+ device_map="auto" # Better device management for Spaces
28
+ )
29
+ print("Model loaded successfully!")
30
 
31
+ # Define inference function
32
+ def generate_text(prompt, task_type, max_length=300):
33
+ global model, tokenizer, device
34
+
35
+ # If model hasn't been loaded yet, load it
36
+ if model is None:
37
+ load_model()
38
+
39
+ # Set temperature based on task type
40
+ temperature_map = {
41
+ "Math Problem": 0.2,
42
+ "Science Theory": 0.4,
43
+ "Coding Question": 0.3,
44
+ "Reasoning": 0.5,
45
+ "Creative Writing": 0.8
46
+ }
47
+ temperature = temperature_map.get(task_type, 0.5)
48
+
49
+ # Enhance the prompt to request step-by-step solutions
50
+ enhanced_prompt = f"{prompt}\n\nPlease provide a detailed step-by-step solution with clear reasoning."
51
+
52
+ # Progress update for UI
53
+ yield "Generating solution..."
54
+
55
+ # Tokenize input
56
+ inputs = tokenizer(enhanced_prompt, return_tensors="pt").to(device)
57
+
58
+ # Generate output
59
+ with torch.no_grad():
60
+ outputs = model.generate(
61
+ **inputs,
62
+ max_new_tokens=max_length,
63
+ temperature=temperature,
64
+ do_sample=True
65
+ )
66
+
67
+ # Decode response
68
+ response = tokenizer.decode(outputs[0], skip_special_tokens=True)
69
+
70
+ # If the response doesn't seem to include steps, add formatting for clarity
71
+ if "step" not in response.lower() and len(response) > 100:
72
+ # Split into paragraphs and format as steps
73
+ paragraphs = [p for p in response.split('\n') if p.strip()]
74
+ formatted_response = ""
75
+
76
+ for i, para in enumerate(paragraphs):
77
+ if i == 0 and para == enhanced_prompt:
78
+ continue
79
+ formatted_response += f"Step {i+1}: {para}\n\n"
80
+
81
+ yield formatted_response
82
+ else:
83
  yield response
84
 
85
+ # Create Gradio interface
86
+ with gr.Blocks(title="Phi-2 Step-by-Step Solution Generator", theme=gr.themes.Soft()) as demo:
87
+ gr.Markdown("# 🧠 Phi-2 Step-by-Step Solution Generator")
88
+ gr.Markdown("""
89
+ Enter a prompt below and get detailed step-by-step solutions using Microsoft's Phi-2 model.
90
+ Select the appropriate task type to optimize the model's response.
91
+ """)
92
+
93
+ with gr.Row():
94
+ with gr.Column(scale=2):
95
+ prompt_input = gr.Textbox(
96
+ label="Prompt",
97
+ placeholder="Enter your question or problem here...",
98
+ lines=5
99
+ )
100
+
101
+ with gr.Row():
102
+ task_type = gr.Radio(
103
+ ["Math Problem", "Science Theory", "Coding Question", "Reasoning", "Creative Writing"],
104
+ label="Task Type (sets optimal temperature)",
105
+ value="Reasoning"
106
+ )
107
+
108
+ max_length_slider = gr.Slider(
109
+ minimum=100,
110
+ maximum=1000,
111
+ value=300,
112
+ step=50,
113
+ label="Maximum Output Length"
114
+ )
115
+
116
+ with gr.Row():
117
+ generate_button = gr.Button(
118
+ "✨ Generate Step-by-Step Solution",
119
+ variant="primary",
120
+ size="lg"
121
+ )
122
+ clear_button = gr.Button("Clear", variant="secondary")
123
+
124
+ with gr.Column(scale=3):
125
+ output_text = gr.Textbox(
126
+ label="Step-by-Step Solution",
127
+ lines=15,
128
+ show_copy_button=True
129
+ )
130
+
131
+ # Examples with different task types
132
+ with gr.Accordion("Example Prompts", open=False):
133
+ gr.Examples(
134
+ examples=[
135
+ ["Solve the quadratic equation: 2x² + 5x - 3 = 0", "Math Problem"],
136
+ ["Explain how photosynthesis works in plants", "Science Theory"],
137
+ ["Write a function in Python to find the Fibonacci sequence up to n terms", "Coding Question"],
138
+ ["Why might increasing minimum wage have both positive and negative economic impacts?", "Reasoning"],
139
+ ["Write a short story about a robot discovering emotions", "Creative Writing"]
140
+ ],
141
+ inputs=[prompt_input, task_type]
142
+ )
143
+
144
+ # Add functionality to buttons
145
+ generate_button.click(
146
+ fn=generate_text,
147
+ inputs=[prompt_input, task_type, max_length_slider],
148
+ outputs=output_text
149
+ )
150
+
151
+ # Clear functionality
152
+ clear_button.click(
153
+ fn=lambda: ("", "Reasoning"),
154
+ inputs=[],
155
+ outputs=[prompt_input, task_type]
156
+ )
157
 
158
+ # Adding a note about load times
159
+ gr.Markdown("""
160
+ > **Note**: The model loads when you submit your first prompt, which may take 1-2 minutes.
161
+ > Subsequent generations will be much faster.
162
+ """)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
163
 
164
+ # Launch the app
165
  if __name__ == "__main__":
166
+ demo.queue().launch()