shorecode commited on
Commit
eb4c2ff
·
verified ·
1 Parent(s): d098f6f

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +91 -42
  2. requirements.txt +8 -0
app.py CHANGED
@@ -1,88 +1,137 @@
 
1
  import gradio as gr
2
  from transformers import Trainer, TrainingArguments, AutoTokenizer, AutoModelForSeq2SeqLM
3
- from datasets import load_dataset
 
4
  import traceback
5
 
6
- def fine_tune_model(model_name, dataset_name, hub_id, num_epochs, batch_size, lr, grad):
7
- '''
 
 
 
 
8
  try:
9
-
10
- # Load the dataset
11
- dataset = load_dataset(dataset_name)
12
-
13
  # Load the model and tokenizer
14
- model = AutoModelForSeq2SeqLM.from_pretrained(model_name, num_labels=2)
15
- tokenizer = AutoTokenizer.from_pretrained(model_name)
16
-
17
- # Tokenize the dataset
18
- def tokenize_function(examples):
19
- return tokenizer(examples['text'], padding="max_length", truncation=True)
20
-
21
- tokenized_datasets = dataset.map(tokenize_function, batched=True)
22
 
23
  # Set training arguments
24
  training_args = TrainingArguments(
25
- output_dir='./results',
26
- evaluation_strategy="epoch",
27
- learning_rate=lr,
28
- per_device_train_batch_size=batch_size,
29
- per_device_eval_batch_size=batch_size,
30
- num_train_epochs=num_epochs,
 
31
  weight_decay=0.01,
32
- evaluation_strategy='epoch',
33
- gradient_accumulation_steps=grad,
34
  load_best_model_at_end=True,
35
  metric_for_best_model="accuracy",
36
  greater_is_better=True,
37
- logging_dir='./logs',
38
  logging_steps=10,
39
- push_to_hub=True,
40
- hub_model_id=hub_id,
 
 
 
 
41
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
 
43
  # Create Trainer
44
  trainer = Trainer(
45
  model=model,
46
  args=training_args,
47
  train_dataset=tokenized_datasets['train'],
48
- eval_dataset=tokenized_datasets['validation'],
49
- )
50
-
 
 
51
  # Fine-tune the model
52
  trainer.train()
53
  trainer.push_to_hub(commit_message="Training complete!")
54
  except Exception as e:
55
  return f"An error occurred: {str(e)}, TB: {traceback.format_exc()}"
56
- '''
57
  return 'DONE!'#model
58
  '''
59
  # Define Gradio interface
60
  def predict(text):
 
 
61
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
62
  outputs = model(inputs)
63
  predictions = outputs.logits.argmax(dim=-1)
64
- return "Positive" if predictions.item() == 1 else "Negative"
65
  '''
66
  # Create Gradio interface
67
  try:
68
-
69
  iface = gr.Interface(
70
- fine_tune_model,
71
  inputs=[
72
- gr.inputs.Textbox(label="Model Name (e.g., 'google/t5-efficient-tiny-nh8')"),
73
- gr.inputs.Textbox(label="Dataset Name (e.g., 'imdb')"),
74
- gr.inputs.Textbox(label="HF hub to push to after training"),
75
- gr.inputs.Slider(minimum=1, maximum=10, default=3, label="Number of Epochs"),
76
- gr.inputs.Slider(minimum=1, maximum=16, default=4, label="Batch Size"),
77
- gr.inputs.Slider(minimum=1, maximum=100, default=50, label="Learning Rate (e-5)"),
78
- gr.inputs.Slider(minimum=1, maximum=100, default=1, label="Gradient accumulation (e-1)"),
 
79
  ],
80
  outputs="text",
81
  title="Fine-Tune Hugging Face Model",
82
  description="This interface allows you to fine-tune a Hugging Face model on a specified dataset."
83
  )
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  except Exception as e:
85
  print(f"An error occurred: {str(e)}, TB: {traceback.format_exc()}")
86
 
87
- # Launch the interface
88
- iface.launch()
 
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
 
8
+
9
+ import os
10
+ from huggingface_hub import login
11
+
12
+ @spaces.GPU
13
+ def fine_tune_model(model_name, dataset_name, hub_id, api_key, num_epochs, batch_size, lr, grad):
14
  try:
15
+ #login(api_key.strip())
 
 
 
16
  # Load the model and tokenizer
17
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name.strip(), num_labels=2)
18
+
 
 
 
 
 
 
19
 
20
  # Set training arguments
21
  training_args = TrainingArguments(
22
+ output_dir='/data/results',
23
+ eval_strategy="steps", # Change this to steps
24
+ save_strategy='steps',
25
+ learning_rate=lr*0.00001,
26
+ per_device_train_batch_size=int(batch_size),
27
+ per_device_eval_batch_size=int(batch_size),
28
+ num_train_epochs=int(num_epochs),
29
  weight_decay=0.01,
30
+ gradient_accumulation_steps=int(grad),
31
+ max_grad_norm = 1.0,
32
  load_best_model_at_end=True,
33
  metric_for_best_model="accuracy",
34
  greater_is_better=True,
35
+ logging_dir='/data/logs',
36
  logging_steps=10,
37
+ #push_to_hub=True,
38
+ hub_model_id=hub_id.strip(),
39
+ fp16=True,
40
+ #lr_scheduler_type='cosine',
41
+ save_steps=100, # Save checkpoint every 500 steps
42
+ save_total_limit=3,
43
  )
44
+ # Check if a checkpoint exists and load it
45
+ max_length = 128
46
+ # Load the dataset
47
+ dataset = load_dataset(dataset_name.strip())
48
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
49
+ # Tokenize the dataset
50
+ def tokenize_function(examples):
51
+
52
+ # Assuming 'text' is the input and 'target' is the expected output
53
+ model_inputs = tokenizer(
54
+ examples['text'],
55
+ max_length=max_length, # Set to None for dynamic padding
56
+ padding=True, # Disable padding here, we will handle it later
57
+ truncation=True,
58
+ )
59
+
60
+ # Setup the decoder input IDs (shifted right)
61
+ labels = tokenizer(
62
+ examples['target'],
63
+ max_length=max_length, # Set to None for dynamic padding
64
+ padding=True, # Disable padding here, we will handle it later
65
+ truncation=True,
66
+ text_target=examples['target'] # Use text_target for target text
67
+ )
68
+
69
+ # Add labels to the model inputs
70
+ model_inputs["labels"] = labels["input_ids"]
71
+
72
+
73
+ tokenized_datasets = dataset.map(tokenize_function, batched=True)
74
+
75
+ tokenized_datasets['train'].save_to_disk(f'/data/{hub_id.strip()}_train_dataset')
76
+ tokenized_datasets['test'].save_to_disk(f'/data/{hub_id.strip()}_test_dataset')
77
 
78
  # Create Trainer
79
  trainer = Trainer(
80
  model=model,
81
  args=training_args,
82
  train_dataset=tokenized_datasets['train'],
83
+ eval_dataset=tokenized_datasets['test'],
84
+ compute_metrics=compute_metrics,
85
+ #callbacks=[LoggingCallback()],
86
+ )
87
+
88
  # Fine-tune the model
89
  trainer.train()
90
  trainer.push_to_hub(commit_message="Training complete!")
91
  except Exception as e:
92
  return f"An error occurred: {str(e)}, TB: {traceback.format_exc()}"
 
93
  return 'DONE!'#model
94
  '''
95
  # Define Gradio interface
96
  def predict(text):
97
+ model = AutoModelForSeq2SeqLM.from_pretrained(model_name.strip(), num_labels=2)
98
+ tokenizer = AutoTokenizer.from_pretrained(model_name)
99
  inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True)
100
  outputs = model(inputs)
101
  predictions = outputs.logits.argmax(dim=-1)
102
+ return predictions.item()
103
  '''
104
  # Create Gradio interface
105
  try:
 
106
  iface = gr.Interface(
107
+ fn=fine_tune_model,
108
  inputs=[
109
+ gr.Textbox(label="Model Name (e.g., 'google/t5-efficient-tiny-nh8')"),
110
+ gr.Textbox(label="Dataset Name (e.g., 'imdb')"),
111
+ gr.Textbox(label="HF hub to push to after training"),
112
+ gr.Textbox(label="HF API token"),
113
+ gr.Slider(minimum=1, maximum=10, value=3, label="Number of Epochs", step=1),
114
+ gr.Slider(minimum=1, maximum=2000, value=1, label="Batch Size", step=1),
115
+ gr.Slider(minimum=1, maximum=1000, value=1, label="Learning Rate (e-5)", step=1),
116
+ gr.Slider(minimum=1, maximum=100, value=1, label="Gradient accumulation", step=1),
117
  ],
118
  outputs="text",
119
  title="Fine-Tune Hugging Face Model",
120
  description="This interface allows you to fine-tune a Hugging Face model on a specified dataset."
121
  )
122
+ '''
123
+ iface = gr.Interface(
124
+ fn=predict,
125
+ inputs=[
126
+ gr.Textbox(label="Query"),
127
+ ],
128
+ outputs="text",
129
+ title="Fine-Tune Hugging Face Model",
130
+ description="This interface allows you to test a fine-tune Hugging Face model."
131
+ )
132
+ '''
133
+ # Launch the interface
134
+ iface.launch()
135
  except Exception as e:
136
  print(f"An error occurred: {str(e)}, TB: {traceback.format_exc()}")
137
 
 
 
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ spaces
2
+ transformers
3
+ datasets
4
+ peft
5
+ huggingface_hub
6
+ scikit-learn
7
+ numpy
8
+ torch