Kevin Fink commited on
Commit
915a0f9
·
1 Parent(s): 1e083b4
Files changed (2) hide show
  1. app (copy).py +179 -0
  2. app.py +39 -83
app (copy).py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces
2
+ import gradio as gr
3
+ from transformers import Trainer, TrainingArguments, AutoTokenizer, AutoModelForSeq2SeqLM
4
+ from transformers import DataCollatorForSeq2Seq
5
+ from datasets import load_dataset, concatenate_datasets, load_from_disk
6
+ import traceback
7
+ from sklearn.metrics import accuracy_score
8
+ import numpy as np
9
+ import torch
10
+
11
+ import os
12
+ from huggingface_hub import login
13
+ from peft import get_peft_model, LoraConfig
14
+
15
+ #os.environ['HF_HOME'] = '/data/.huggingface'
16
+
17
+ @spaces.GPU(duration=120)
18
+ def fine_tune_model(model_name, dataset_name, hub_id, api_key, num_epochs, batch_size, lr, grad):
19
+ try:
20
+ torch.cuda.empty_cache()
21
+ def compute_metrics(eval_pred):
22
+ logits, labels = eval_pred
23
+ predictions = np.argmax(logits, axis=1)
24
+ accuracy = accuracy_score(labels, predictions)
25
+ return {
26
+ 'eval_accuracy': accuracy,
27
+ 'eval_loss': eval_pred.loss, # If you want to include loss as well
28
+ }
29
+ login(api_key.strip())
30
+ lora_config = LoraConfig(
31
+ r=16, # Rank of the low-rank adaptation
32
+ lora_alpha=32, # Scaling factor
33
+ lora_dropout=0.1, # Dropout for LoRA layers
34
+ bias="none" # Bias handling
35
+ )
36
+
37
+ # Load the model and tokenizer
38
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name.strip(), num_labels=2, force_download=True)
39
+ model.gradient_checkpointing_enable()
40
+ #model = get_peft_model(model, lora_config)
41
+
42
+
43
+ # Set training arguments
44
+ training_args = TrainingArguments(
45
+ output_dir='/data/results',
46
+ eval_strategy="steps", # Change this to steps
47
+ save_strategy='steps',
48
+ learning_rate=lr*0.00001,
49
+ per_device_train_batch_size=int(batch_size),
50
+ per_device_eval_batch_size=int(batch_size),
51
+ num_train_epochs=int(num_epochs),
52
+ weight_decay=0.01,
53
+ gradient_accumulation_steps=int(grad),
54
+ max_grad_norm = 1.0,
55
+ load_best_model_at_end=True,
56
+ metric_for_best_model="accuracy",
57
+ greater_is_better=True,
58
+ logging_dir='/data/logs',
59
+ logging_steps=10,
60
+ #push_to_hub=True,
61
+ hub_model_id=hub_id.strip(),
62
+ fp16=True,
63
+ #lr_scheduler_type='cosine',
64
+ save_steps=100, # Save checkpoint every 500 steps
65
+ save_total_limit=3,
66
+ )
67
+ # Check if a checkpoint exists and load it
68
+ if os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir):
69
+ print("Loading model from checkpoint...")
70
+ model = AutoModelForSeq2SeqLM.from_pretrained(training_args.output_dir)
71
+
72
+ max_length = 128
73
+ try:
74
+ tokenized_train_dataset = load_from_disk(f'/data/{hub_id.strip()}_train_dataset')
75
+ tokenized_test_dataset = load_from_disk(f'/data/{hub_id.strip()}_test_dataset')
76
+
77
+ # Create Trainer
78
+ trainer = Trainer(
79
+ model=model,
80
+ args=training_args,
81
+ train_dataset=tokenized_train_dataset,
82
+ eval_dataset=tokenized_test_dataset,
83
+ compute_metrics=compute_metrics,
84
+ #callbacks=[LoggingCallback()],
85
+ )
86
+ except:
87
+ # Load the dataset
88
+ dataset = load_dataset(dataset_name.strip())
89
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
90
+ # Tokenize the dataset
91
+ def tokenize_function(examples):
92
+
93
+ # Assuming 'text' is the input and 'target' is the expected output
94
+ model_inputs = tokenizer(
95
+ examples['text'],
96
+ max_length=max_length, # Set to None for dynamic padding
97
+ padding=True, # Disable padding here, we will handle it later
98
+ truncation=True,
99
+ )
100
+
101
+ # Setup the decoder input IDs (shifted right)
102
+ labels = tokenizer(
103
+ examples['target'],
104
+ max_length=max_length, # Set to None for dynamic padding
105
+ padding=True, # Disable padding here, we will handle it later
106
+ truncation=True,
107
+ text_target=examples['target'] # Use text_target for target text
108
+ )
109
+
110
+ # Add labels to the model inputs
111
+ model_inputs["labels"] = labels["input_ids"]
112
+ return model_inputs
113
+
114
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
115
+
116
+ tokenized_datasets['train'].save_to_disk(f'/data/{hub_id.strip()}_train_dataset')
117
+ tokenized_datasets['test'].save_to_disk(f'/data/{hub_id.strip()}_test_dataset')
118
+
119
+ # Create Trainer
120
+ trainer = Trainer(
121
+ model=model,
122
+ args=training_args,
123
+ train_dataset=tokenized_datasets['train'],
124
+ eval_dataset=tokenized_datasets['test'],
125
+ compute_metrics=compute_metrics,
126
+ #callbacks=[LoggingCallback()],
127
+ )
128
+
129
+ # Fine-tune the model
130
+ trainer.train()
131
+ trainer.push_to_hub(commit_message="Training complete!")
132
+ except Exception as e:
133
+ return f"An error occurred: {str(e)}, TB: {traceback.format_exc()}"
134
+ return 'DONE!'#model
135
+ '''
136
+ # Define Gradio interface
137
+ def predict(text):
138
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name.strip(), num_labels=2)
139
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
140
+ inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
141
+ outputs = model(inputs)
142
+ predictions = outputs.logits.argmax(dim=-1)
143
+ return predictions.item()
144
+ '''
145
+ # Create Gradio interface
146
+ try:
147
+ model = AutoModelForSeq2SeqLM.from_pretrained('google/t5-efficient-tiny-nh8'.strip(), num_labels=2, force_download=True)
148
+ iface = gr.Interface(
149
+ fn=fine_tune_model,
150
+ inputs=[
151
+ gr.Textbox(label="Model Name (e.g., 'google/t5-efficient-tiny-nh8')"),
152
+ gr.Textbox(label="Dataset Name (e.g., 'imdb')"),
153
+ gr.Textbox(label="HF hub to push to after training"),
154
+ gr.Textbox(label="HF API token"),
155
+ gr.Slider(minimum=1, maximum=10, value=3, label="Number of Epochs", step=1),
156
+ gr.Slider(minimum=1, maximum=2000, value=1, label="Batch Size", step=1),
157
+ gr.Slider(minimum=1, maximum=1000, value=1, label="Learning Rate (e-5)", step=1),
158
+ gr.Slider(minimum=1, maximum=100, value=1, label="Gradient accumulation", step=1),
159
+ ],
160
+ outputs="text",
161
+ title="Fine-Tune Hugging Face Model",
162
+ description="This interface allows you to fine-tune a Hugging Face model on a specified dataset."
163
+ )
164
+ '''
165
+ iface = gr.Interface(
166
+ fn=predict,
167
+ inputs=[
168
+ gr.Textbox(label="Query"),
169
+ ],
170
+ outputs="text",
171
+ title="Fine-Tune Hugging Face Model",
172
+ description="This interface allows you to test a fine-tune Hugging Face model."
173
+ )
174
+ '''
175
+ # Launch the interface
176
+ iface.launch()
177
+ except Exception as e:
178
+ print(f"An error occurred: {str(e)}, TB: {traceback.format_exc()}")
179
+
app.py CHANGED
@@ -4,40 +4,15 @@ from transformers import Trainer, TrainingArguments, AutoTokenizer, AutoModelFor
4
  from transformers import DataCollatorForSeq2Seq
5
  from datasets import load_dataset, concatenate_datasets, load_from_disk
6
  import traceback
7
- from sklearn.metrics import accuracy_score
8
- import numpy as np
9
- import torch
10
 
11
  import os
12
  from huggingface_hub import login
13
- from peft import get_peft_model, LoraConfig
14
-
15
- #os.environ['HF_HOME'] = '/data/.huggingface'
16
-
17
- @spaces.GPU(duration=120)
18
  def fine_tune_model(model_name, dataset_name, hub_id, api_key, num_epochs, batch_size, lr, grad):
19
  try:
20
- torch.cuda.empty_cache()
21
- def compute_metrics(eval_pred):
22
- logits, labels = eval_pred
23
- predictions = np.argmax(logits, axis=1)
24
- accuracy = accuracy_score(labels, predictions)
25
- return {
26
- 'eval_accuracy': accuracy,
27
- 'eval_loss': eval_pred.loss, # If you want to include loss as well
28
- }
29
  login(api_key.strip())
30
- lora_config = LoraConfig(
31
- r=16, # Rank of the low-rank adaptation
32
- lora_alpha=32, # Scaling factor
33
- lora_dropout=0.1, # Dropout for LoRA layers
34
- bias="none" # Bias handling
35
- )
36
-
37
  # Load the model and tokenizer
38
  model = AutoModelForSeq2SeqLM.from_pretrained(model_name.strip(), num_labels=2, force_download=True)
39
- model.gradient_checkpointing_enable()
40
- #model = get_peft_model(model, lora_config)
41
 
42
 
43
  # Set training arguments
@@ -65,66 +40,48 @@ def fine_tune_model(model_name, dataset_name, hub_id, api_key, num_epochs, batch
65
  save_total_limit=3,
66
  )
67
  # Check if a checkpoint exists and load it
68
- if os.path.exists(training_args.output_dir) and os.listdir(training_args.output_dir):
69
- print("Loading model from checkpoint...")
70
- model = AutoModelForSeq2SeqLM.from_pretrained(training_args.output_dir)
71
-
72
  max_length = 128
73
- try:
74
- tokenized_train_dataset = load_from_disk(f'/data/{hub_id.strip()}_train_dataset')
75
- tokenized_test_dataset = load_from_disk(f'/data/{hub_id.strip()}_test_dataset')
76
-
77
- # Create Trainer
78
- trainer = Trainer(
79
- model=model,
80
- args=training_args,
81
- train_dataset=tokenized_train_dataset,
82
- eval_dataset=tokenized_test_dataset,
83
- compute_metrics=compute_metrics,
84
- #callbacks=[LoggingCallback()],
85
- )
86
- except:
87
- # Load the dataset
88
- dataset = load_dataset(dataset_name.strip())
89
- tokenizer = AutoTokenizer.from_pretrained(model_name)
90
- # Tokenize the dataset
91
- def tokenize_function(examples):
92
-
93
- # Assuming 'text' is the input and 'target' is the expected output
94
- model_inputs = tokenizer(
95
- examples['text'],
96
- max_length=max_length, # Set to None for dynamic padding
97
- padding=True, # Disable padding here, we will handle it later
98
- truncation=True,
99
- )
100
 
101
- # Setup the decoder input IDs (shifted right)
102
- labels = tokenizer(
103
- examples['target'],
104
- max_length=max_length, # Set to None for dynamic padding
105
- padding=True, # Disable padding here, we will handle it later
106
- truncation=True,
107
- text_target=examples['target'] # Use text_target for target text
108
- )
109
-
110
- # Add labels to the model inputs
111
- model_inputs["labels"] = labels["input_ids"]
112
- return model_inputs
113
 
114
- tokenized_datasets = dataset.map(tokenize_function, batched=True)
115
-
116
- tokenized_datasets['train'].save_to_disk(f'/data/{hub_id.strip()}_train_dataset')
117
- tokenized_datasets['test'].save_to_disk(f'/data/{hub_id.strip()}_test_dataset')
 
 
 
 
 
 
 
118
 
119
- # Create Trainer
120
- trainer = Trainer(
121
- model=model,
122
- args=training_args,
123
- train_dataset=tokenized_datasets['train'],
124
- eval_dataset=tokenized_datasets['test'],
125
- compute_metrics=compute_metrics,
126
- #callbacks=[LoggingCallback()],
127
- )
 
 
 
 
 
 
128
 
129
  # Fine-tune the model
130
  trainer.train()
@@ -144,7 +101,6 @@ def predict(text):
144
  '''
145
  # Create Gradio interface
146
  try:
147
- model = AutoModelForSeq2SeqLM.from_pretrained('google/t5-efficient-tiny-nh8'.strip(), num_labels=2, force_download=True)
148
  iface = gr.Interface(
149
  fn=fine_tune_model,
150
  inputs=[
 
4
  from transformers import DataCollatorForSeq2Seq
5
  from datasets import load_dataset, concatenate_datasets, load_from_disk
6
  import traceback
7
+
 
 
8
 
9
  import os
10
  from huggingface_hub import login
 
 
 
 
 
11
  def fine_tune_model(model_name, dataset_name, hub_id, api_key, num_epochs, batch_size, lr, grad):
12
  try:
 
 
 
 
 
 
 
 
 
13
  login(api_key.strip())
 
 
 
 
 
 
 
14
  # Load the model and tokenizer
15
  model = AutoModelForSeq2SeqLM.from_pretrained(model_name.strip(), num_labels=2, force_download=True)
 
 
16
 
17
 
18
  # Set training arguments
 
40
  save_total_limit=3,
41
  )
42
  # Check if a checkpoint exists and load it
 
 
 
 
43
  max_length = 128
44
+ # Load the dataset
45
+ dataset = load_dataset(dataset_name.strip())
46
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
47
+ # Tokenize the dataset
48
+ def tokenize_function(examples):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
 
50
+ # Assuming 'text' is the input and 'target' is the expected output
51
+ model_inputs = tokenizer(
52
+ examples['text'],
53
+ max_length=max_length, # Set to None for dynamic padding
54
+ padding=True, # Disable padding here, we will handle it later
55
+ truncation=True,
56
+ )
 
 
 
 
 
57
 
58
+ # Setup the decoder input IDs (shifted right)
59
+ labels = tokenizer(
60
+ examples['target'],
61
+ max_length=max_length, # Set to None for dynamic padding
62
+ padding=True, # Disable padding here, we will handle it later
63
+ truncation=True,
64
+ text_target=examples['target'] # Use text_target for target text
65
+ )
66
+
67
+ # Add labels to the model inputs
68
+ model_inputs["labels"] = labels["input_ids"]
69
 
70
+
71
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
72
+
73
+ tokenized_datasets['train'].save_to_disk(f'/data/{hub_id.strip()}_train_dataset')
74
+ tokenized_datasets['test'].save_to_disk(f'/data/{hub_id.strip()}_test_dataset')
75
+
76
+ # Create Trainer
77
+ trainer = Trainer(
78
+ model=model,
79
+ args=training_args,
80
+ train_dataset=tokenized_datasets['train'],
81
+ eval_dataset=tokenized_datasets['test'],
82
+ compute_metrics=compute_metrics,
83
+ #callbacks=[LoggingCallback()],
84
+ )
85
 
86
  # Fine-tune the model
87
  trainer.train()
 
101
  '''
102
  # Create Gradio interface
103
  try:
 
104
  iface = gr.Interface(
105
  fn=fine_tune_model,
106
  inputs=[