Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,270 +1,200 @@
|
|
| 1 |
-
"""
|
| 2 |
-
PromptWizard Qwen Training
|
| 3 |
-
Optimized for HuggingFace Spaces with
|
| 4 |
-
"""
|
| 5 |
-
|
| 6 |
-
import gradio as gr
|
| 7 |
-
import spaces
|
| 8 |
-
import torch
|
| 9 |
-
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 10 |
-
from datasets import load_dataset, Dataset
|
| 11 |
-
from peft import LoraConfig, get_peft_model, TaskType
|
| 12 |
-
import
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
output_log.append("
|
| 39 |
-
|
| 40 |
-
#
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
#
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
output_log.append("
|
| 99 |
-
|
| 100 |
-
#
|
| 101 |
-
progress(0.
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
|
| 158 |
-
|
| 159 |
-
|
| 160 |
-
|
| 161 |
-
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
-
|
| 171 |
-
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
|
| 175 |
-
|
| 176 |
-
|
| 177 |
-
|
| 178 |
-
|
| 179 |
-
|
| 180 |
-
|
| 181 |
-
|
| 182 |
-
|
| 183 |
-
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
|
| 188 |
-
|
| 189 |
-
|
| 190 |
-
|
| 191 |
-
|
| 192 |
-
|
| 193 |
-
|
| 194 |
-
|
| 195 |
-
|
| 196 |
-
|
| 197 |
-
|
| 198 |
-
|
| 199 |
-
|
| 200 |
-
|
| 201 |
-
|
| 202 |
-
with gr.Row():
|
| 203 |
-
with gr.Column():
|
| 204 |
-
gpu_status = gr.Textbox(
|
| 205 |
-
label="GPU Status",
|
| 206 |
-
value=check_gpu_status(),
|
| 207 |
-
interactive=False
|
| 208 |
-
)
|
| 209 |
-
|
| 210 |
-
model_name = gr.Dropdown(
|
| 211 |
-
choices=[
|
| 212 |
-
"Qwen/Qwen2.5-0.5B",
|
| 213 |
-
"Qwen/Qwen2.5-1.5B",
|
| 214 |
-
],
|
| 215 |
-
value="Qwen/Qwen2.5-0.5B",
|
| 216 |
-
label="Model (0.5B works best for Zero GPU)"
|
| 217 |
-
)
|
| 218 |
-
|
| 219 |
-
num_epochs = gr.Slider(
|
| 220 |
-
minimum=1,
|
| 221 |
-
maximum=3,
|
| 222 |
-
value=1,
|
| 223 |
-
step=1,
|
| 224 |
-
label="Number of Epochs (1 for quick demo)"
|
| 225 |
-
)
|
| 226 |
-
|
| 227 |
-
batch_size = gr.Slider(
|
| 228 |
-
minimum=1,
|
| 229 |
-
maximum=4,
|
| 230 |
-
value=2,
|
| 231 |
-
step=1,
|
| 232 |
-
label="Batch Size (2 for Zero GPU)"
|
| 233 |
-
)
|
| 234 |
-
|
| 235 |
-
learning_rate = gr.Number(
|
| 236 |
-
value=5e-5,
|
| 237 |
-
label="Learning Rate"
|
| 238 |
-
)
|
| 239 |
-
|
| 240 |
-
train_btn = gr.Button("🚀 Start Training", variant="primary")
|
| 241 |
-
|
| 242 |
-
with gr.Column():
|
| 243 |
-
output = gr.Textbox(
|
| 244 |
-
label="Training Output",
|
| 245 |
-
lines=20,
|
| 246 |
-
max_lines=30,
|
| 247 |
-
value="Click 'Start Training' to begin...\n\nZero GPU will automatically allocate a GPU when training starts."
|
| 248 |
-
)
|
| 249 |
-
|
| 250 |
-
# Connect button to training function
|
| 251 |
-
train_btn.click(
|
| 252 |
-
fn=train_model,
|
| 253 |
-
inputs=[model_name, num_epochs, batch_size, learning_rate],
|
| 254 |
-
outputs=output
|
| 255 |
-
)
|
| 256 |
-
|
| 257 |
-
gr.Markdown("""
|
| 258 |
-
## Notes:
|
| 259 |
-
- Zero GPU provides free GPU access for public Spaces
|
| 260 |
-
- Training will automatically get GPU allocation when started
|
| 261 |
-
- Using smaller model (1.5B) for faster demo
|
| 262 |
-
- Real GSM8K data - no fake metrics!
|
| 263 |
-
""")
|
| 264 |
-
|
| 265 |
-
return demo
|
| 266 |
-
|
| 267 |
-
# Launch app
|
| 268 |
-
if __name__ == "__main__":
|
| 269 |
-
demo = create_interface()
|
| 270 |
-
demo.launch()
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
PromptWizard Qwen Training using rahul7star/Gita dataset (.csv)
|
| 3 |
+
Optimized for HuggingFace Spaces with Zero GPU allocation
|
| 4 |
+
"""
|
| 5 |
+
|
| 6 |
+
import gradio as gr
|
| 7 |
+
import spaces
|
| 8 |
+
import torch
|
| 9 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, Trainer, TrainingArguments
|
| 10 |
+
from datasets import load_dataset, Dataset
|
| 11 |
+
from peft import LoraConfig, get_peft_model, TaskType
|
| 12 |
+
import os
|
| 13 |
+
|
| 14 |
+
# GPU check (Zero GPU compatible)
|
| 15 |
+
def check_gpu_status():
|
| 16 |
+
return "🚀 Zero GPU Ready - GPU will be allocated when training starts"
|
| 17 |
+
|
| 18 |
+
@spaces.GPU(duration=300) # request GPU for 5 min
|
| 19 |
+
def train_model(model_name, num_epochs, batch_size, learning_rate, progress=gr.Progress()):
|
| 20 |
+
progress(0, desc="Initializing...")
|
| 21 |
+
output_log = []
|
| 22 |
+
|
| 23 |
+
try:
|
| 24 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 25 |
+
output_log.append(f"🎮 Using device: {device}")
|
| 26 |
+
if device == "cuda":
|
| 27 |
+
output_log.append(f"✅ GPU: {torch.cuda.get_device_name(0)}")
|
| 28 |
+
|
| 29 |
+
# === Load your dataset ===
|
| 30 |
+
progress(0.1, desc="Loading Gita dataset...")
|
| 31 |
+
output_log.append("\n📚 Loading rahul7star/Gita dataset from Hugging Face Hub...")
|
| 32 |
+
|
| 33 |
+
# Load CSV from Hugging Face repo
|
| 34 |
+
dataset = load_dataset("rahul7star/Gita", split="train")
|
| 35 |
+
output_log.append(f" Loaded {len(dataset)} examples from rahul7star/Gita")
|
| 36 |
+
|
| 37 |
+
# Preview columns
|
| 38 |
+
output_log.append(f" Columns: {dataset.column_names}")
|
| 39 |
+
|
| 40 |
+
# === Format each row into text prompt ===
|
| 41 |
+
def format_example(item):
|
| 42 |
+
# You can customize this depending on your CSV structure
|
| 43 |
+
# Assuming CSV has columns like: "chapter", "verse", "content" or "text"
|
| 44 |
+
text = ""
|
| 45 |
+
if "text" in item:
|
| 46 |
+
text = item["text"]
|
| 47 |
+
elif "content" in item:
|
| 48 |
+
text = item["content"]
|
| 49 |
+
else:
|
| 50 |
+
# fallback: join all columns
|
| 51 |
+
text = " ".join(str(v) for v in item.values())
|
| 52 |
+
|
| 53 |
+
prompt = f"""<|system|>
|
| 54 |
+
You are a spiritual teacher interpreting Bhagavad Gita verses with deep meaning.
|
| 55 |
+
<|user|>
|
| 56 |
+
{ text }
|
| 57 |
+
<|assistant|>
|
| 58 |
+
"""
|
| 59 |
+
return {"text": prompt}
|
| 60 |
+
|
| 61 |
+
train_dataset = dataset.map(format_example)
|
| 62 |
+
output_log.append(f" Formatted {len(train_dataset)} training samples")
|
| 63 |
+
|
| 64 |
+
# === Load Qwen model & tokenizer ===
|
| 65 |
+
progress(0.3, desc="Loading model...")
|
| 66 |
+
model_name = "Qwen/Qwen2.5-0.5B" # Force small model for free GPU
|
| 67 |
+
output_log.append(f"\n🤖 Loading {model_name}...")
|
| 68 |
+
|
| 69 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
| 70 |
+
if tokenizer.pad_token is None:
|
| 71 |
+
tokenizer.pad_token = tokenizer.eos_token
|
| 72 |
+
|
| 73 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 74 |
+
model_name,
|
| 75 |
+
trust_remote_code=True,
|
| 76 |
+
torch_dtype=torch.float16 if device == "cuda" else torch.float32,
|
| 77 |
+
low_cpu_mem_usage=True
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
if device == "cuda":
|
| 81 |
+
model = model.to(device)
|
| 82 |
+
output_log.append(" ✅ Model loaded successfully")
|
| 83 |
+
|
| 84 |
+
# === LoRA configuration ===
|
| 85 |
+
progress(0.4, desc="Configuring LoRA...")
|
| 86 |
+
output_log.append("\n⚙️ Setting up LoRA for efficient training...")
|
| 87 |
+
|
| 88 |
+
lora_config = LoraConfig(
|
| 89 |
+
task_type=TaskType.CAUSAL_LM,
|
| 90 |
+
r=8,
|
| 91 |
+
lora_alpha=16,
|
| 92 |
+
lora_dropout=0.1,
|
| 93 |
+
target_modules=["q_proj", "v_proj"],
|
| 94 |
+
bias="none"
|
| 95 |
+
)
|
| 96 |
+
model = get_peft_model(model, lora_config)
|
| 97 |
+
trainable_params = sum(p.numel() for p in model.parameters() if p.requires_grad)
|
| 98 |
+
output_log.append(f" Trainable params: {trainable_params:,}")
|
| 99 |
+
|
| 100 |
+
# === Tokenize ===
|
| 101 |
+
progress(0.5, desc="Tokenizing data...")
|
| 102 |
+
def tokenize_fn(examples):
|
| 103 |
+
return tokenizer(
|
| 104 |
+
examples["text"],
|
| 105 |
+
padding="max_length",
|
| 106 |
+
truncation=True,
|
| 107 |
+
max_length=256
|
| 108 |
+
)
|
| 109 |
+
train_dataset = train_dataset.map(tokenize_fn, batched=True)
|
| 110 |
+
output_log.append(" ✅ Tokenization done")
|
| 111 |
+
|
| 112 |
+
# === Training configuration ===
|
| 113 |
+
progress(0.6, desc="Setting up training...")
|
| 114 |
+
training_args = TrainingArguments(
|
| 115 |
+
output_dir="./qwen-gita-lora",
|
| 116 |
+
num_train_epochs=num_epochs,
|
| 117 |
+
per_device_train_batch_size=batch_size,
|
| 118 |
+
gradient_accumulation_steps=2,
|
| 119 |
+
warmup_steps=10,
|
| 120 |
+
logging_steps=5,
|
| 121 |
+
save_strategy="no",
|
| 122 |
+
fp16=device == "cuda",
|
| 123 |
+
optim="adamw_torch",
|
| 124 |
+
learning_rate=learning_rate,
|
| 125 |
+
max_steps=50, # Short demo
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
trainer = Trainer(
|
| 129 |
+
model=model,
|
| 130 |
+
args=training_args,
|
| 131 |
+
train_dataset=train_dataset,
|
| 132 |
+
tokenizer=tokenizer,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
# === Train ===
|
| 136 |
+
progress(0.7, desc="Training model...")
|
| 137 |
+
output_log.append("\n🚀 Starting training...\n" + "="*50)
|
| 138 |
+
train_result = trainer.train()
|
| 139 |
+
|
| 140 |
+
progress(0.9, desc="Finalizing...")
|
| 141 |
+
output_log.append("="*50)
|
| 142 |
+
output_log.append("\n✅ Training completed successfully!")
|
| 143 |
+
output_log.append(f" Final loss: {train_result.training_loss:.4f}")
|
| 144 |
+
output_log.append(f" Steps: {train_result.global_step}")
|
| 145 |
+
|
| 146 |
+
progress(1.0, desc="Complete!")
|
| 147 |
+
except Exception as e:
|
| 148 |
+
output_log.append(f"\n❌ Error: {e}")
|
| 149 |
+
|
| 150 |
+
return "\n".join(output_log)
|
| 151 |
+
|
| 152 |
+
|
| 153 |
+
# === Gradio UI ===
|
| 154 |
+
def create_interface():
|
| 155 |
+
with gr.Blocks(title="PromptWizard Gita Trainer") as demo:
|
| 156 |
+
gr.Markdown("""
|
| 157 |
+
# 🧘 PromptWizard Qwen Fine-tuning — Gita Edition
|
| 158 |
+
Train Qwen models using verses from **rahul7star/Gita** (CSV-based dataset).
|
| 159 |
+
This uses **Zero GPU** on Hugging Face Spaces for free GPU access.
|
| 160 |
+
""")
|
| 161 |
+
|
| 162 |
+
with gr.Row():
|
| 163 |
+
with gr.Column():
|
| 164 |
+
gpu_status = gr.Textbox(
|
| 165 |
+
label="GPU Status",
|
| 166 |
+
value=check_gpu_status(),
|
| 167 |
+
interactive=False
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
model_name = gr.Dropdown(
|
| 171 |
+
choices=["Qwen/Qwen2.5-0.5B", "Qwen/Qwen2.5-1.5B"],
|
| 172 |
+
value="Qwen/Qwen2.5-0.5B",
|
| 173 |
+
label="Model (recommended: 0.5B)"
|
| 174 |
+
)
|
| 175 |
+
|
| 176 |
+
num_epochs = gr.Slider(1, 3, value=1, step=1, label="Epochs")
|
| 177 |
+
batch_size = gr.Slider(1, 4, value=2, step=1, label="Batch Size")
|
| 178 |
+
learning_rate = gr.Number(value=5e-5, label="Learning Rate")
|
| 179 |
+
train_btn = gr.Button("🚀 Start Training", variant="primary")
|
| 180 |
+
|
| 181 |
+
with gr.Column():
|
| 182 |
+
output = gr.Textbox(
|
| 183 |
+
label="Training Output",
|
| 184 |
+
lines=20,
|
| 185 |
+
max_lines=30,
|
| 186 |
+
value="Click 'Start Training' to fine-tune on Gita dataset."
|
| 187 |
+
)
|
| 188 |
+
|
| 189 |
+
train_btn.click(
|
| 190 |
+
fn=train_model,
|
| 191 |
+
inputs=[model_name, num_epochs, batch_size, learning_rate],
|
| 192 |
+
outputs=output
|
| 193 |
+
)
|
| 194 |
+
|
| 195 |
+
return demo
|
| 196 |
+
|
| 197 |
+
|
| 198 |
+
if __name__ == "__main__":
|
| 199 |
+
demo = create_interface()
|
| 200 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|