MRasheq commited on
Commit
57880bf
·
1 Parent(s): 9716d05

Second Commit

Browse files
Files changed (1) hide show
  1. app.py +13 -29
app.py CHANGED
@@ -20,10 +20,10 @@ from peft import (
20
  )
21
  from datetime import datetime
22
 
23
- # Constants - Modified for HF Spaces
24
- MODEL_NAME = "deepseek-ai/DeepSeek-R1"
25
- OUTPUT_DIR = "/tmp/finetuned_models" # Using /tmp for HF Spaces
26
- LOGS_DIR = "/tmp/training_logs" # Using /tmp for HF Spaces
27
 
28
  class TrainingInterface:
29
  def __init__(self):
@@ -32,14 +32,12 @@ class TrainingInterface:
32
  self.is_training = False
33
 
34
  def get_database_url(self):
35
- """Get database URL from HF Space secrets"""
36
  database_url = os.environ.get('DATABASE_URL')
37
  if not database_url:
38
  raise Exception("DATABASE_URL not found in environment variables")
39
  return database_url
40
 
41
  def fetch_training_data(self, progress=gr.Progress()):
42
- """Fetch training data from database"""
43
  try:
44
  database_url = self.get_database_url()
45
  engine = create_engine(database_url)
@@ -60,7 +58,6 @@ class TrainingInterface:
60
  raise gr.Error(f"Database error: {str(e)}")
61
 
62
  def prepare_training_data(self, df, progress=gr.Progress()):
63
- """Convert DataFrame into training format"""
64
  formatted_data = []
65
  try:
66
  total_rows = len(df)
@@ -71,7 +68,7 @@ class TrainingInterface:
71
  text = str(row_data['text']).strip()
72
 
73
  if chunk_id and text:
74
- formatted_text = f"User: {chunk_id}\nAssistant: {text}"
75
  formatted_data.append({"text": formatted_text})
76
 
77
  if not formatted_data:
@@ -82,7 +79,6 @@ class TrainingInterface:
82
  raise gr.Error(f"Data preparation error: {str(e)}")
83
 
84
  def stop_training(self):
85
- """Stop the training process"""
86
  self.is_training = False
87
  return "Training stopped by user."
88
 
@@ -93,17 +89,14 @@ class TrainingInterface:
93
  batch_size=4,
94
  progress=gr.Progress()
95
  ):
96
- """Main training function"""
97
  try:
98
  self.is_training = True
99
 
100
- # Create directories in /tmp for HF Spaces
101
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
102
  specific_output_dir = os.path.join(OUTPUT_DIR, f"run_{timestamp}")
103
  os.makedirs(specific_output_dir, exist_ok=True)
104
  os.makedirs(LOGS_DIR, exist_ok=True)
105
 
106
- # Data preparation
107
  progress(0.1, desc="Fetching data...")
108
  if not self.is_training:
109
  return "Training cancelled."
@@ -111,32 +104,27 @@ class TrainingInterface:
111
  df = self.fetch_training_data()
112
  formatted_data = self.prepare_training_data(df)
113
 
114
- # Model initialization
115
  progress(0.2, desc="Loading model...")
116
  if not self.is_training:
117
  return "Training cancelled."
118
 
119
- tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME, trust_remote_code=True)
120
  model = AutoModelForCausalLM.from_pretrained(
121
  MODEL_NAME,
122
- trust_remote_code=True,
123
  torch_dtype=torch.float16,
124
  load_in_8bit=True,
125
- device_map="auto" # Important for HF Spaces GPU allocation
126
  )
127
 
128
- # LoRA configuration
129
  progress(0.3, desc="Setting up LoRA...")
130
  if not self.is_training:
131
  return "Training cancelled."
132
 
 
133
  lora_config = LoraConfig(
134
  r=16,
135
  lora_alpha=32,
136
- target_modules=[
137
- "q_proj", "k_proj", "v_proj", "o_proj",
138
- "gate_proj", "up_proj", "down_proj"
139
- ],
140
  lora_dropout=0.05,
141
  bias="none",
142
  task_type="CAUSAL_LM"
@@ -145,7 +133,6 @@ class TrainingInterface:
145
  model = prepare_model_for_kbit_training(model)
146
  model = get_peft_model(model, lora_config)
147
 
148
- # Training setup
149
  progress(0.4, desc="Configuring training...")
150
  if not self.is_training:
151
  return "Training cancelled."
@@ -161,9 +148,9 @@ class TrainingInterface:
161
  logging_dir=os.path.join(LOGS_DIR, f"run_{timestamp}"),
162
  logging_steps=10,
163
  save_strategy="epoch",
164
- evaluation_strategy="epoch",
165
  save_total_limit=2,
166
- remove_unused_columns=False, # Important for HF Spaces
167
  )
168
 
169
  dataset = Dataset.from_dict({
@@ -175,7 +162,6 @@ class TrainingInterface:
175
  mlm=False
176
  )
177
 
178
- # Custom progress callback
179
  class ProgressCallback(gr.Progress):
180
  def __init__(self, progress_callback, training_interface):
181
  self.progress_callback = progress_callback
@@ -210,7 +196,6 @@ class TrainingInterface:
210
  if not self.is_training:
211
  return "Training cancelled."
212
 
213
- # Save model
214
  progress(0.9, desc="Saving model...")
215
  trainer.save_model()
216
  tokenizer.save_pretrained(specific_output_dir)
@@ -223,11 +208,10 @@ class TrainingInterface:
223
  raise gr.Error(f"Training error: {str(e)}")
224
 
225
  def create_training_interface():
226
- """Create Gradio interface"""
227
  interface = TrainingInterface()
228
 
229
- with gr.Blocks(title="DeepSeek Model Training Interface") as app:
230
- gr.Markdown("# DeepSeek Model Fine-tuning Interface")
231
 
232
  with gr.Row():
233
  with gr.Column():
 
20
  )
21
  from datetime import datetime
22
 
23
+ # Changed to a model that doesn't require flash-attention
24
+ MODEL_NAME = "deepseek-ai/deepseek-coder-6.7b-base"
25
+ OUTPUT_DIR = "/tmp/finetuned_models"
26
+ LOGS_DIR = "/tmp/training_logs"
27
 
28
  class TrainingInterface:
29
  def __init__(self):
 
32
  self.is_training = False
33
 
34
  def get_database_url(self):
 
35
  database_url = os.environ.get('DATABASE_URL')
36
  if not database_url:
37
  raise Exception("DATABASE_URL not found in environment variables")
38
  return database_url
39
 
40
  def fetch_training_data(self, progress=gr.Progress()):
 
41
  try:
42
  database_url = self.get_database_url()
43
  engine = create_engine(database_url)
 
58
  raise gr.Error(f"Database error: {str(e)}")
59
 
60
  def prepare_training_data(self, df, progress=gr.Progress()):
 
61
  formatted_data = []
62
  try:
63
  total_rows = len(df)
 
68
  text = str(row_data['text']).strip()
69
 
70
  if chunk_id and text:
71
+ formatted_text = f"Question: {chunk_id}\nAnswer: {text}" # Changed format for deepseek-coder
72
  formatted_data.append({"text": formatted_text})
73
 
74
  if not formatted_data:
 
79
  raise gr.Error(f"Data preparation error: {str(e)}")
80
 
81
  def stop_training(self):
 
82
  self.is_training = False
83
  return "Training stopped by user."
84
 
 
89
  batch_size=4,
90
  progress=gr.Progress()
91
  ):
 
92
  try:
93
  self.is_training = True
94
 
 
95
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
96
  specific_output_dir = os.path.join(OUTPUT_DIR, f"run_{timestamp}")
97
  os.makedirs(specific_output_dir, exist_ok=True)
98
  os.makedirs(LOGS_DIR, exist_ok=True)
99
 
 
100
  progress(0.1, desc="Fetching data...")
101
  if not self.is_training:
102
  return "Training cancelled."
 
104
  df = self.fetch_training_data()
105
  formatted_data = self.prepare_training_data(df)
106
 
 
107
  progress(0.2, desc="Loading model...")
108
  if not self.is_training:
109
  return "Training cancelled."
110
 
111
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
112
  model = AutoModelForCausalLM.from_pretrained(
113
  MODEL_NAME,
 
114
  torch_dtype=torch.float16,
115
  load_in_8bit=True,
116
+ device_map="auto"
117
  )
118
 
 
119
  progress(0.3, desc="Setting up LoRA...")
120
  if not self.is_training:
121
  return "Training cancelled."
122
 
123
+ # Updated LoRA config for deepseek-coder model
124
  lora_config = LoraConfig(
125
  r=16,
126
  lora_alpha=32,
127
+ target_modules=["q_proj", "k_proj", "v_proj", "o_proj"],
 
 
 
128
  lora_dropout=0.05,
129
  bias="none",
130
  task_type="CAUSAL_LM"
 
133
  model = prepare_model_for_kbit_training(model)
134
  model = get_peft_model(model, lora_config)
135
 
 
136
  progress(0.4, desc="Configuring training...")
137
  if not self.is_training:
138
  return "Training cancelled."
 
148
  logging_dir=os.path.join(LOGS_DIR, f"run_{timestamp}"),
149
  logging_steps=10,
150
  save_strategy="epoch",
151
+ evaluation_strategy="no", # Changed to "no" since we don't have eval data
152
  save_total_limit=2,
153
+ remove_unused_columns=False,
154
  )
155
 
156
  dataset = Dataset.from_dict({
 
162
  mlm=False
163
  )
164
 
 
165
  class ProgressCallback(gr.Progress):
166
  def __init__(self, progress_callback, training_interface):
167
  self.progress_callback = progress_callback
 
196
  if not self.is_training:
197
  return "Training cancelled."
198
 
 
199
  progress(0.9, desc="Saving model...")
200
  trainer.save_model()
201
  tokenizer.save_pretrained(specific_output_dir)
 
208
  raise gr.Error(f"Training error: {str(e)}")
209
 
210
  def create_training_interface():
 
211
  interface = TrainingInterface()
212
 
213
+ with gr.Blocks(title="DeepSeek Coder Training Interface") as app:
214
+ gr.Markdown("# DeepSeek Coder Fine-tuning Interface")
215
 
216
  with gr.Row():
217
  with gr.Column():