Faizal2805 commited on
Commit
ad8a314
·
verified ·
1 Parent(s): f9c13d8

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +104 -28
app.py CHANGED
@@ -1,44 +1,121 @@
1
  import gradio as gr
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
3
- from datasets import load_dataset, Dataset
4
  from peft import LoraConfig, get_peft_model
5
  import torch
6
 
 
 
 
 
7
  # Load GPT-2 model and tokenizer
8
  model_name = "gpt2"
9
  tokenizer = AutoTokenizer.from_pretrained(model_name)
10
  model = AutoModelForCausalLM.from_pretrained(model_name)
11
 
12
- # Custom Dataset (Improved format)
 
 
13
  custom_data = [
14
- {"text": "Prompt: Who are you?\nResponse: I am Eva, a virtual voice assistant."},
15
- {"text": "Prompt: What is your name?\nResponse: I am Eva, how can I help you?"},
16
- {"text": "Prompt: What can you do?\nResponse: I can assist with answering questions, searching the web, and much more!"},
17
- {"text": "Prompt: Who invented the computer?\nResponse: Charles Babbage is known as the father of the computer."},
18
- {"text": "Prompt: Tell me a joke.\nResponse: Why don’t scientists trust atoms? Because they make up everything!"},
19
- {"text": "Prompt: Who is the Prime Minister of India?\nResponse: The current Prime Minister of India is Narendra Modi."},
20
- {"text": "Prompt: Who created you?\nResponse: I was created by an expert team specializing in AI fine-tuning and web development."},
21
- {"text": "Prompt: Can you introduce yourself?\nResponse: I am Eva, your AI assistant, designed to assist and provide information."}
22
  ]
23
 
24
- # Convert custom data to a Dataset
25
- dataset_custom = Dataset.from_list(custom_data)
 
 
 
26
 
 
27
  def tokenize_function(examples):
28
  return tokenizer(examples["text"], truncation=True, padding="max_length", max_length=512)
29
 
30
- tokenized_datasets = dataset_custom.map(tokenize_function, batched=True)
31
 
32
  # Apply LoRA for efficient fine-tuning
33
  lora_config = LoraConfig(
34
- r=4, # Reduced r for stability
35
- lora_alpha=16,
36
- lora_dropout=0.1,
37
- bias="none",
38
- target_modules=["c_attn", "c_proj"] # LoRA targets attention layers
39
  )
40
 
41
  model = get_peft_model(model, lora_config)
 
 
42
  model.gradient_checkpointing_enable()
43
 
44
  # Training arguments
@@ -46,8 +123,8 @@ training_args = TrainingArguments(
46
  output_dir="gpt2_finetuned",
47
  auto_find_batch_size=True,
48
  gradient_accumulation_steps=4,
49
- learning_rate=3e-5, # Lowered learning rate for improved stability
50
- num_train_epochs=5, # Increased epochs for better training
51
  save_strategy="epoch",
52
  logging_dir="logs",
53
  bf16=True,
@@ -61,20 +138,19 @@ trainer = Trainer(
61
  train_dataset=tokenized_datasets
62
  )
63
 
 
64
  trainer.train()
65
 
66
- # Save and push the model
67
  trainer.save_model("gpt2_finetuned")
68
  tokenizer.save_pretrained("gpt2_finetuned")
69
  trainer.push_to_hub()
70
 
71
- # Gradio Interface for Responses
72
  def generate_response(prompt):
73
- inputs = tokenizer(f"Prompt: {prompt}\nResponse:", return_tensors="pt")
74
- outputs = model.generate(**inputs, max_length=150, num_return_sequences=1, temperature=0.7, top_p=0.9)
75
- return tokenizer.decode(outputs[0], skip_special_tokens=True).split("Response:")[-1].strip()
76
 
77
  demo = gr.Interface(fn=generate_response, inputs="text", outputs="text")
78
-
79
- if __name__ == "__main__":
80
- 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
+ if __name__ == "__main__":
63
+ demo.launch()
64
+
65
+ # Fine-Tuning GPT-2 on Hugging Face Spaces (Streaming 40GB Dataset, No Storage Issues)
66
+
67
+ # Install required libraries
68
+ # Install required libraries (Run this separately in a terminal or notebook cell)
69
+ # !pip install transformers datasets peft accelerate bitsandbytes torch torchvision torchaudio gradio -q
70
+
71
  from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
72
+ from datasets import load_dataset
73
  from peft import LoraConfig, get_peft_model
74
  import torch
75
 
76
+ # Authenticate Hugging Face
77
+ from huggingface_hub import notebook_login
78
+ notebook_login()
79
+
80
  # Load GPT-2 model and tokenizer
81
  model_name = "gpt2"
82
  tokenizer = AutoTokenizer.from_pretrained(model_name)
83
  model = AutoModelForCausalLM.from_pretrained(model_name)
84
 
85
+ # Load the OpenWebText dataset using streaming (No download required)
86
+
87
+ # Custom Dataset (Predefined Q&A Pairs for Project Expo)
88
  custom_data = [
89
+ {"prompt": "Who are you?", "response": "I am Eva, a virtual voice assistant."},
90
+ {"prompt": "What is your name?", "response": "I am Eva, how can I help you?"},
91
+ {"prompt": "What can you do?", "response": "I can assist with answering questions, searching the web, and much more!"},
92
+ {"prompt": "Who invented the computer?", "response": "Charles Babbage is known as the father of the computer."},
93
+ {"prompt": "Tell me a joke.", "response": "Why don’t scientists trust atoms? Because they make up everything!"},
94
+ {"prompt": "Who is the Prime Minister of India?", "response": "The current Prime Minister of India is Narendra Modi."},
95
+ {"prompt": "Who created you?", "response": "I was created by an expert team specializing in AI fine-tuning and web development."}
 
96
  ]
97
 
98
+ # Convert custom dataset to Hugging Face Dataset
99
+ dataset_custom = load_dataset("json", data_files={"train": custom_data})
100
+
101
+ # Merge with OpenWebText dataset
102
+ dataset = load_dataset("Skylion007/openwebtext", split="train[:20%]") # Load 5% to avoid streaming issues
103
 
104
+ # Tokenization function
105
  def tokenize_function(examples):
106
  return tokenizer(examples["text"], truncation=True, padding="max_length", max_length=512)
107
 
108
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
109
 
110
  # Apply LoRA for efficient fine-tuning
111
  lora_config = LoraConfig(
112
+ r=8, lora_alpha=32, lora_dropout=0.05, bias="none",
113
+ target_modules=["c_attn", "c_proj"] # Apply LoRA to attention layers
 
 
 
114
  )
115
 
116
  model = get_peft_model(model, lora_config)
117
+
118
+ # Enable gradient checkpointing to reduce memory usage
119
  model.gradient_checkpointing_enable()
120
 
121
  # Training arguments
 
123
  output_dir="gpt2_finetuned",
124
  auto_find_batch_size=True,
125
  gradient_accumulation_steps=4,
126
+ learning_rate=5e-5,
127
+ num_train_epochs=3,
128
  save_strategy="epoch",
129
  logging_dir="logs",
130
  bf16=True,
 
138
  train_dataset=tokenized_datasets
139
  )
140
 
141
+ # Start fine-tuning
142
  trainer.train()
143
 
144
+ # Save and push the model to Hugging Face Hub
145
  trainer.save_model("gpt2_finetuned")
146
  tokenizer.save_pretrained("gpt2_finetuned")
147
  trainer.push_to_hub()
148
 
149
+ # Deploy as Gradio Interface
150
  def generate_response(prompt):
151
+ inputs = tokenizer(prompt, return_tensors="pt")
152
+ outputs = model.generate(**inputs, max_length=100)
153
+ return tokenizer.decode(outputs[0], skip_special_tokens=True)
154
 
155
  demo = gr.Interface(fn=generate_response, inputs="text", outputs="text")
156
+ demo.launch()