File size: 6,505 Bytes
bfe5d0e
2eb6820
bfe5d0e
 
 
 
 
 
 
 
 
 
2eb6820
 
bfe5d0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eb6820
bfe5d0e
14f2b83
 
 
 
 
 
 
 
 
 
 
bfe5d0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eb6820
bfe5d0e
2eb6820
bfe5d0e
 
 
 
 
 
2eb6820
bfe5d0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eb6820
 
bfe5d0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2eb6820
bfe5d0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
import gradio as gr
from transformers import AutoModelForCausalLM, AutoTokenizer
import torch
import random
import time
import os

# Load the model and tokenizer
model_path = "./phi2-qlora-final"
tokenizer = AutoTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
    model_path,
    device_map="cpu",  # Force CPU usage
    torch_dtype=torch.float32,  # Use float32 for CPU
    trust_remote_code=True
)

# Custom CSS for better styling
custom_css = """

.gradio-container {

    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;

}

.container {

    max-width: 800px;

    margin: auto;

    padding: 20px;

}

.title {

    text-align: center;

    color: #2c3e50;

    margin-bottom: 20px;

}

.description {

    text-align: center;

    color: #7f8c8d;

    margin-bottom: 30px;

}

.loading {

    display: flex;

    justify-content: center;

    align-items: center;

    height: 100px;

}

.error {

    color: #e74c3c;

    padding: 10px;

    border-radius: 5px;

    background-color: #fde8e8;

    margin: 10px 0;

}

"""

def generate_response(prompt, max_length=512, temperature=0.7, top_p=0.9, top_k=50):
    """Generate response with progress indicator"""
    try:
        if not prompt.strip():
            return "Please enter a prompt."
            
        inputs = tokenizer(prompt, return_tensors="pt")
        
        with torch.no_grad():  # Disable gradient computation for inference
            outputs = model.generate(
                **inputs,
                max_length=max_length,
                temperature=temperature,
                num_return_sequences=1,
                pad_token_id=tokenizer.eos_token_id,
                do_sample=True,
                top_p=top_p,
                top_k=top_k,
            )
        
        response = tokenizer.decode(outputs[0], skip_special_tokens=True)
        return response
    except Exception as e:
        return f"Error generating response: {str(e)}"

def clear_all():
    """Clear all inputs and outputs"""
    return "", "", 512, 0.7, 0.9, 50

# Example prompts
example_prompts = [
    "What is the capital of France?",
    "Explain quantum computing in simple terms.",
    "Write a short story about a robot learning to paint.",
    "What are the benefits of meditation?",
    "How does photosynthesis work?",
]

# Create the Gradio interface
with gr.Blocks(css=custom_css, theme=gr.themes.Soft()) as iface:
    gr.Markdown(
        """

        # πŸ€– Phi-2 QLoRA Chat Interface (CPU Version)

        

        Chat with the fine-tuned Phi-2 model using QLoRA. This version runs on CPU for better compatibility.

        """,
        elem_classes="title"
    )
    
    gr.Markdown(
        """

        This interface allows you to interact with a fine-tuned Phi-2 model. Note that responses may be slower due to CPU-only inference.

        """,
        elem_classes="description"
    )
    
    with gr.Row():
        with gr.Column(scale=2):
            # Input section
            with gr.Group():
                gr.Markdown("### πŸ’­ Input")
                prompt = gr.Textbox(
                    label="Enter your prompt:",
                    placeholder="Type your message here...",
                    lines=3,
                    show_label=True,
                    container=True
                )
                
                with gr.Row():
                    max_length = gr.Slider(
                        minimum=64,
                        maximum=512,  # Reduced max length for CPU
                        value=256,    # Reduced default length
                        step=64,
                        label="Max Length",
                        info="Maximum length of generated response"
                    )
                    temperature = gr.Slider(
                        minimum=0.1,
                        maximum=1.0,
                        value=0.7,
                        step=0.1,
                        label="Temperature",
                        info="Higher values make output more random"
                    )
                
                with gr.Row():
                    top_p = gr.Slider(
                        minimum=0.1,
                        maximum=1.0,
                        value=0.9,
                        step=0.1,
                        label="Top P",
                        info="Nucleus sampling parameter"
                    )
                    top_k = gr.Slider(
                        minimum=1,
                        maximum=100,
                        value=50,
                        step=1,
                        label="Top K",
                        info="Top-k sampling parameter"
                    )
            
            # Buttons
            with gr.Row():
                submit_btn = gr.Button("Generate Response", variant="primary")
                clear_btn = gr.Button("Clear All", variant="secondary")
        
        with gr.Column(scale=2):
            # Output section
            with gr.Group():
                gr.Markdown("### πŸ€– Response")
                output = gr.Textbox(
                    label="Model Response:",
                    lines=5,
                    show_label=True,
                    container=True
                )
    
    # Examples section
    with gr.Group():
        gr.Markdown("### πŸ“ Example Prompts")
        gr.Examples(
            examples=example_prompts,
            inputs=prompt,
            outputs=output,
            fn=generate_response,
            cache_examples=True
        )
    
    # Footer
    gr.Markdown(
        """

        ---

        Made with ❀️ using Phi-2 and QLoRA (CPU Version)

        """,
        elem_classes="footer"
    )
    
    # Event handlers
    submit_btn.click(
        fn=generate_response,
        inputs=[prompt, max_length, temperature, top_p, top_k],
        outputs=output
    )
    
    clear_btn.click(
        fn=clear_all,
        inputs=[],
        outputs=[prompt, output, max_length, temperature, top_p, top_k]
    )

if __name__ == "__main__":
    iface.launch(
        share=True,  # Enable sharing
        server_name="0.0.0.0",  # Allow external access
        server_port=7860,  # Default Gradio port
        show_error=True  # Show detailed error messages
    )