Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,22 +1,91 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from huggingface_hub import InferenceClient
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 4 |
from datasets import load_dataset
|
| 5 |
from peft import LoraConfig, get_peft_model
|
| 6 |
import torch
|
| 7 |
|
| 8 |
-
#
|
| 9 |
-
|
|
|
|
| 10 |
|
| 11 |
-
# GPT-2
|
| 12 |
model_name = "gpt2"
|
| 13 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 14 |
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 15 |
|
| 16 |
-
#
|
| 17 |
-
tokenizer.pad_token = tokenizer.eos_token
|
| 18 |
|
| 19 |
-
# Custom Dataset
|
| 20 |
custom_data = [
|
| 21 |
{"prompt": "Who are you?", "response": "I am Eva, a virtual voice assistant."},
|
| 22 |
{"prompt": "What is your name?", "response": "I am Eva, how can I help you?"},
|
|
@@ -30,8 +99,8 @@ custom_data = [
|
|
| 30 |
# Convert custom dataset to Hugging Face Dataset
|
| 31 |
dataset_custom = load_dataset("json", data_files={"train": custom_data})
|
| 32 |
|
| 33 |
-
#
|
| 34 |
-
dataset = load_dataset("Skylion007/openwebtext", split="train[:20%]"
|
| 35 |
|
| 36 |
# Tokenization function
|
| 37 |
def tokenize_function(examples):
|
|
@@ -39,16 +108,18 @@ def tokenize_function(examples):
|
|
| 39 |
|
| 40 |
tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
| 41 |
|
| 42 |
-
# LoRA
|
| 43 |
lora_config = LoraConfig(
|
| 44 |
r=8, lora_alpha=32, lora_dropout=0.05, bias="none",
|
| 45 |
-
target_modules=["c_attn", "c_proj"]
|
| 46 |
)
|
| 47 |
|
| 48 |
model = get_peft_model(model, lora_config)
|
|
|
|
|
|
|
| 49 |
model.gradient_checkpointing_enable()
|
| 50 |
|
| 51 |
-
# Training
|
| 52 |
training_args = TrainingArguments(
|
| 53 |
output_dir="gpt2_finetuned",
|
| 54 |
auto_find_batch_size=True,
|
|
@@ -61,14 +132,14 @@ training_args = TrainingArguments(
|
|
| 61 |
push_to_hub=True
|
| 62 |
)
|
| 63 |
|
| 64 |
-
# Trainer
|
| 65 |
trainer = Trainer(
|
| 66 |
model=model,
|
| 67 |
args=training_args,
|
| 68 |
train_dataset=tokenized_datasets
|
| 69 |
)
|
| 70 |
|
| 71 |
-
#
|
| 72 |
trainer.train()
|
| 73 |
|
| 74 |
# Save and push the model to Hugging Face Hub
|
|
@@ -76,44 +147,11 @@ trainer.save_model("gpt2_finetuned")
|
|
| 76 |
tokenizer.save_pretrained("gpt2_finetuned")
|
| 77 |
trainer.push_to_hub()
|
| 78 |
|
| 79 |
-
#
|
| 80 |
-
def
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
for entry in history:
|
| 85 |
-
if isinstance(entry, dict):
|
| 86 |
-
messages.append(entry)
|
| 87 |
-
elif isinstance(entry, tuple) and len(entry) == 2:
|
| 88 |
-
messages.append({"role": "user", "content": entry[0]})
|
| 89 |
-
messages.append({"role": "assistant", "content": entry[1]})
|
| 90 |
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
response = ""
|
| 94 |
-
for message in client.chat_completion(
|
| 95 |
-
messages,
|
| 96 |
-
max_tokens=max_tokens,
|
| 97 |
-
stream=True,
|
| 98 |
-
temperature=temperature,
|
| 99 |
-
top_p=top_p,
|
| 100 |
-
):
|
| 101 |
-
token = message.choices[0].delta.content
|
| 102 |
-
response += token
|
| 103 |
-
yield response
|
| 104 |
-
|
| 105 |
-
# Gradio Chatbot Interface
|
| 106 |
-
demo = gr.ChatInterface(
|
| 107 |
-
respond,
|
| 108 |
-
chatbot=gr.Chatbot(type="messages"),
|
| 109 |
-
additional_inputs=[
|
| 110 |
-
gr.Textbox(value="You are a friendly Chatbot.", label="System message"),
|
| 111 |
-
gr.Slider(minimum=1, maximum=2048, value=512, step=1, label="Max new tokens"),
|
| 112 |
-
gr.Slider(minimum=0.1, maximum=4.0, value=0.7, step=0.1, label="Temperature"),
|
| 113 |
-
gr.Slider(minimum=0.1, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
|
| 114 |
-
],
|
| 115 |
-
)
|
| 116 |
-
|
| 117 |
-
# Launch the App
|
| 118 |
-
if __name__ == "__main__":
|
| 119 |
-
demo.launch()
|
|
|
|
| 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()
|
| 65 |
+
|
| 66 |
+
# Fine-Tuning GPT-2 on Hugging Face Spaces (Streaming 40GB Dataset, No Storage Issues)
|
| 67 |
+
|
| 68 |
+
# Install required libraries
|
| 69 |
+
# Install required libraries (Run this separately in a terminal or notebook cell)
|
| 70 |
+
# !pip install transformers datasets peft accelerate bitsandbytes torch torchvision torchaudio gradio -q
|
| 71 |
+
|
| 72 |
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 73 |
from datasets import load_dataset
|
| 74 |
from peft import LoraConfig, get_peft_model
|
| 75 |
import torch
|
| 76 |
|
| 77 |
+
# Authenticate Hugging Face
|
| 78 |
+
from huggingface_hub import notebook_login
|
| 79 |
+
notebook_login()
|
| 80 |
|
| 81 |
+
# Load GPT-2 model and tokenizer
|
| 82 |
model_name = "gpt2"
|
| 83 |
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
| 84 |
model = AutoModelForCausalLM.from_pretrained(model_name)
|
| 85 |
|
| 86 |
+
# Load the OpenWebText dataset using streaming (No download required)
|
|
|
|
| 87 |
|
| 88 |
+
# Custom Dataset (Predefined Q&A Pairs for Project Expo)
|
| 89 |
custom_data = [
|
| 90 |
{"prompt": "Who are you?", "response": "I am Eva, a virtual voice assistant."},
|
| 91 |
{"prompt": "What is your name?", "response": "I am Eva, how can I help you?"},
|
|
|
|
| 99 |
# Convert custom dataset to Hugging Face Dataset
|
| 100 |
dataset_custom = load_dataset("json", data_files={"train": custom_data})
|
| 101 |
|
| 102 |
+
# Merge with OpenWebText dataset
|
| 103 |
+
dataset = load_dataset("Skylion007/openwebtext", split="train[:20%]") # Load 5% to avoid streaming issues
|
| 104 |
|
| 105 |
# Tokenization function
|
| 106 |
def tokenize_function(examples):
|
|
|
|
| 108 |
|
| 109 |
tokenized_datasets = dataset.map(tokenize_function, batched=True)
|
| 110 |
|
| 111 |
+
# Apply LoRA for efficient fine-tuning
|
| 112 |
lora_config = LoraConfig(
|
| 113 |
r=8, lora_alpha=32, lora_dropout=0.05, bias="none",
|
| 114 |
+
target_modules=["c_attn", "c_proj"] # Apply LoRA to attention layers
|
| 115 |
)
|
| 116 |
|
| 117 |
model = get_peft_model(model, lora_config)
|
| 118 |
+
|
| 119 |
+
# Enable gradient checkpointing to reduce memory usage
|
| 120 |
model.gradient_checkpointing_enable()
|
| 121 |
|
| 122 |
+
# Training arguments
|
| 123 |
training_args = TrainingArguments(
|
| 124 |
output_dir="gpt2_finetuned",
|
| 125 |
auto_find_batch_size=True,
|
|
|
|
| 132 |
push_to_hub=True
|
| 133 |
)
|
| 134 |
|
| 135 |
+
# Trainer setup
|
| 136 |
trainer = Trainer(
|
| 137 |
model=model,
|
| 138 |
args=training_args,
|
| 139 |
train_dataset=tokenized_datasets
|
| 140 |
)
|
| 141 |
|
| 142 |
+
# Start fine-tuning
|
| 143 |
trainer.train()
|
| 144 |
|
| 145 |
# Save and push the model to Hugging Face Hub
|
|
|
|
| 147 |
tokenizer.save_pretrained("gpt2_finetuned")
|
| 148 |
trainer.push_to_hub()
|
| 149 |
|
| 150 |
+
# Deploy as Gradio Interface
|
| 151 |
+
def generate_response(prompt):
|
| 152 |
+
inputs = tokenizer(prompt, return_tensors="pt")
|
| 153 |
+
outputs = model.generate(**inputs, max_length=100)
|
| 154 |
+
return tokenizer.decode(outputs[0], skip_special_tokens=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 155 |
|
| 156 |
+
demo = gr.Interface(fn=generate_response, inputs="text", outputs="text")
|
| 157 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|