Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,63 +1,31 @@
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
3 |
-
|
4 |
-
# Initialize Hugging Face Inference Client
|
5 |
-
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
6 |
-
|
7 |
-
# Response Function
|
8 |
-
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
9 |
-
messages = [{"role": "system", "content": system_message}]
|
10 |
-
|
11 |
-
if isinstance(history, list):
|
12 |
-
for entry in history:
|
13 |
-
if isinstance(entry, dict):
|
14 |
-
messages.append(entry)
|
15 |
-
elif isinstance(entry, tuple) and len(entry) == 2:
|
16 |
-
messages.append({"role": "user", "content": entry[0]})
|
17 |
-
messages.append({"role": "assistant", "content": entry[1]})
|
18 |
-
|
19 |
-
messages.append({"role": "user", "content": message})
|
20 |
-
|
21 |
-
response = ""
|
22 |
-
|
23 |
-
for message in client.chat_completion(
|
24 |
-
messages,
|
25 |
-
max_tokens=max_tokens,
|
26 |
-
stream=True,
|
27 |
-
temperature=temperature,
|
28 |
-
top_p=top_p,
|
29 |
-
):
|
30 |
-
token = message.choices[0].delta.content
|
31 |
-
response += token
|
32 |
-
yield response
|
33 |
-
|
34 |
-
# Gradio Chat Interface
|
35 |
-
demo = gr.ChatInterface(
|
36 |
-
respond,
|
37 |
-
additional_inputs=[
|
38 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
39 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
40 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
41 |
-
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p"),
|
42 |
-
],
|
43 |
-
)
|
44 |
-
|
45 |
-
# Fine-Tuning GPT-2 on Hugging Face Spaces
|
46 |
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
47 |
-
from datasets import Dataset
|
48 |
from peft import LoraConfig, get_peft_model
|
49 |
import torch
|
50 |
|
|
|
|
|
|
|
51 |
# Load GPT-2 model and tokenizer
|
52 |
model_name = "gpt2"
|
53 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
54 |
model = AutoModelForCausalLM.from_pretrained(model_name)
|
55 |
|
|
|
|
|
|
|
|
|
56 |
# Custom Dataset (Predefined Q&A Pairs for Project Expo)
|
57 |
custom_data = [
|
58 |
{"text": "Who are you?", "label": "I am Eva, a virtual voice assistant."},
|
59 |
{"text": "What is your name?", "label": "I am Eva, how can I help you?"},
|
60 |
{"text": "What can you do?", "label": "I can assist with answering questions, searching the web, and much more!"},
|
|
|
|
|
|
|
|
|
61 |
]
|
62 |
|
63 |
# Convert custom dataset to Hugging Face Dataset
|
@@ -66,20 +34,28 @@ dataset_custom = Dataset.from_dict({
|
|
66 |
"label": [d['label'] for d in custom_data]
|
67 |
})
|
68 |
|
|
|
|
|
|
|
69 |
# Tokenization function
|
70 |
def tokenize_function(examples):
|
71 |
-
return tokenizer(
|
|
|
|
|
|
|
|
|
|
|
72 |
|
73 |
tokenized_datasets = dataset_custom.map(tokenize_function, batched=True)
|
74 |
|
75 |
# Apply LoRA for efficient fine-tuning
|
76 |
lora_config = LoraConfig(
|
77 |
r=8, lora_alpha=32, lora_dropout=0.05, bias="none",
|
78 |
-
target_modules=["c_attn", "c_proj"]
|
79 |
)
|
80 |
|
81 |
model = get_peft_model(model, lora_config)
|
82 |
-
model.gradient_checkpointing_enable()
|
83 |
|
84 |
# Training arguments
|
85 |
training_args = TrainingArguments(
|
@@ -115,6 +91,50 @@ def generate_response(prompt):
|
|
115 |
outputs = model.generate(**inputs, max_length=100)
|
116 |
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|
117 |
|
118 |
-
#
|
119 |
-
|
120 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
3 |
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
4 |
+
from datasets import Dataset, load_dataset
|
5 |
from peft import LoraConfig, get_peft_model
|
6 |
import torch
|
7 |
|
8 |
+
# Initialize Hugging Face Inference Client
|
9 |
+
client = InferenceClient("HuggingFaceH4/zephyr-7b-beta")
|
10 |
+
|
11 |
# Load GPT-2 model and tokenizer
|
12 |
model_name = "gpt2"
|
13 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
14 |
model = AutoModelForCausalLM.from_pretrained(model_name)
|
15 |
|
16 |
+
# Add padding token (GPT-2 fix)
|
17 |
+
if tokenizer.pad_token is None:
|
18 |
+
tokenizer.pad_token = tokenizer.eos_token
|
19 |
+
|
20 |
# Custom Dataset (Predefined Q&A Pairs for Project Expo)
|
21 |
custom_data = [
|
22 |
{"text": "Who are you?", "label": "I am Eva, a virtual voice assistant."},
|
23 |
{"text": "What is your name?", "label": "I am Eva, how can I help you?"},
|
24 |
{"text": "What can you do?", "label": "I can assist with answering questions, searching the web, and much more!"},
|
25 |
+
{"text": "Who invented the computer?", "label": "Charles Babbage is known as the father of the computer."},
|
26 |
+
{"text": "Tell me a joke.", "label": "Why don’t scientists trust atoms? Because they make up everything!"},
|
27 |
+
{"text": "Who is the Prime Minister of India?", "label": "The current Prime Minister of India is Narendra Modi."},
|
28 |
+
{"text": "Who created you?", "label": "I was created by an expert team specializing in AI fine-tuning and web development."}
|
29 |
]
|
30 |
|
31 |
# Convert custom dataset to Hugging Face Dataset
|
|
|
34 |
"label": [d['label'] for d in custom_data]
|
35 |
})
|
36 |
|
37 |
+
# Load OpenWebText dataset (5% portion to avoid streaming issues)
|
38 |
+
dataset = load_dataset("Skylion007/openwebtext", split="train[:20%]")
|
39 |
+
|
40 |
# Tokenization function
|
41 |
def tokenize_function(examples):
|
42 |
+
return tokenizer(
|
43 |
+
examples["text"],
|
44 |
+
truncation=True,
|
45 |
+
padding="max_length",
|
46 |
+
max_length=512
|
47 |
+
)
|
48 |
|
49 |
tokenized_datasets = dataset_custom.map(tokenize_function, batched=True)
|
50 |
|
51 |
# Apply LoRA for efficient fine-tuning
|
52 |
lora_config = LoraConfig(
|
53 |
r=8, lora_alpha=32, lora_dropout=0.05, bias="none",
|
54 |
+
target_modules=["c_attn", "c_proj"] # Apply LoRA to attention layers
|
55 |
)
|
56 |
|
57 |
model = get_peft_model(model, lora_config)
|
58 |
+
model.gradient_checkpointing_enable() # Enable checkpointing for memory efficiency
|
59 |
|
60 |
# Training arguments
|
61 |
training_args = TrainingArguments(
|
|
|
91 |
outputs = model.generate(**inputs, max_length=100)
|
92 |
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|
93 |
|
94 |
+
# Gradio Chat Interface
|
95 |
+
def respond(message, history, system_message, max_tokens, temperature, top_p):
|
96 |
+
messages = [{"role": "system", "content": system_message}]
|
97 |
+
|
98 |
+
# Ensure 'history' is handled as a list of dicts
|
99 |
+
if isinstance(history, list):
|
100 |
+
for entry in history:
|
101 |
+
if isinstance(entry, dict):
|
102 |
+
messages.append(entry) # Correct format already
|
103 |
+
elif isinstance(entry, tuple) and len(entry) == 2:
|
104 |
+
messages.append({"role": "user", "content": entry[0]})
|
105 |
+
messages.append({"role": "assistant", "content": entry[1]})
|
106 |
+
|
107 |
+
messages.append({"role": "user", "content": message})
|
108 |
+
response = ""
|
109 |
+
|
110 |
+
for message in client.chat_completion(
|
111 |
+
messages,
|
112 |
+
max_tokens=max_tokens,
|
113 |
+
stream=True,
|
114 |
+
temperature=temperature,
|
115 |
+
top_p=top_p,
|
116 |
+
):
|
117 |
+
token = message.choices[0].delta.content
|
118 |
+
response += token
|
119 |
+
yield response
|
120 |
+
|
121 |
+
demo = gr.ChatInterface(
|
122 |
+
respond,
|
123 |
+
chatbot=gr.Chatbot(type="messages"),
|
124 |
+
additional_inputs=[
|
125 |
+
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
126 |
+
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
127 |
+
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
128 |
+
gr.Slider(
|
129 |
+
minimum=0.1,
|
130 |
+
maximum=1.0,
|
131 |
+
value=0.95,
|
132 |
+
step=0.05,
|
133 |
+
label="Top-p (nucleus sampling)",
|
134 |
+
),
|
135 |
+
],
|
136 |
+
)
|
137 |
+
|
138 |
+
# Launch the Gradio app
|
139 |
+
if __name__ == "__main__":
|
140 |
+
demo.launch()
|