Spaces:
Sleeping
Sleeping
Delete app.py
Browse files
app.py
DELETED
@@ -1,685 +0,0 @@
|
|
1 |
-
#!/usr/bin/env python3
|
2 |
-
"""
|
3 |
-
app.py – Quranic Data Training Pipeline Endpoint for ZeroGPU Spaces
|
4 |
-
--------------------------------------------------------------------
|
5 |
-
This script integrates a full Quranic data processing and training pipeline
|
6 |
-
into a Gradio interface endpoint. It is optimized for CPU/GPU-based training
|
7 |
-
on Hugging Face ZeroGPU (using the Gradio SDK) and uses chunked incremental
|
8 |
-
training, memory management, and gradient checkpointing to efficiently update
|
9 |
-
Google's Gemma-2-2b model with Quranic data.
|
10 |
-
|
11 |
-
Requirements:
|
12 |
-
- Transformers (==4.45.0)
|
13 |
-
- Gradio (>=5.12.0)
|
14 |
-
- PyTorch (==2.3.0)
|
15 |
-
- psutil (==5.9.5)
|
16 |
-
- Accelerate (>=0.26.0)
|
17 |
-
- Hugging Face PRO subscription with ZeroGPU enabled (ensure your HF token is set as an environment variable HF_TOKEN)
|
18 |
-
- Ubuntu CPU/Linux with access to ZeroGPU hardware via Spaces
|
19 |
-
- Input data files placed in the project root.
|
20 |
-
- Sufficient storage in "working_directory"
|
21 |
-
|
22 |
-
Author: [M-Saddam Hussain]
|
23 |
-
Date: March 2025
|
24 |
-
Data References: [Tanzil.net, IslamSource, QuranicCorpus]
|
25 |
-
"""
|
26 |
-
|
27 |
-
import json
|
28 |
-
import logging
|
29 |
-
import os
|
30 |
-
import traceback
|
31 |
-
import gc
|
32 |
-
import time
|
33 |
-
import psutil
|
34 |
-
import math
|
35 |
-
import shutil
|
36 |
-
from datetime import datetime
|
37 |
-
from typing import Dict, List, Optional
|
38 |
-
from dataclasses import dataclass, asdict
|
39 |
-
|
40 |
-
import torch
|
41 |
-
# Limit PyTorch threads for CPU stability.
|
42 |
-
torch.set_num_threads(8)
|
43 |
-
|
44 |
-
from torch.utils.data import Dataset
|
45 |
-
from transformers import (
|
46 |
-
AutoTokenizer,
|
47 |
-
AutoModelForCausalLM,
|
48 |
-
TrainingArguments,
|
49 |
-
Trainer,
|
50 |
-
DataCollatorForLanguageModeling,
|
51 |
-
__version__ as transformers_version
|
52 |
-
)
|
53 |
-
from threading import Lock
|
54 |
-
|
55 |
-
import gradio as gr
|
56 |
-
import spaces
|
57 |
-
|
58 |
-
# Check for minimum required Transformers version for custom model support
|
59 |
-
MIN_TRANSFORMERS_VERSION = "4.42.0"
|
60 |
-
if tuple(map(int, transformers_version.split("."))) < tuple(map(int, MIN_TRANSFORMERS_VERSION.split("."))):
|
61 |
-
logging.warning(f"Transformers version {transformers_version} detected. Please upgrade to at least {MIN_TRANSFORMERS_VERSION} for proper support of the 'gemma2' architecture.")
|
62 |
-
|
63 |
-
# Configure logging
|
64 |
-
logging.basicConfig(
|
65 |
-
level=logging.INFO,
|
66 |
-
format='%(asctime)s - %(levelname)s - %(message)s',
|
67 |
-
handlers=[
|
68 |
-
logging.FileHandler('pipeline.log'),
|
69 |
-
logging.StreamHandler()
|
70 |
-
]
|
71 |
-
)
|
72 |
-
logger = logging.getLogger(__name__)
|
73 |
-
|
74 |
-
def manage_memory(threshold_percent: int = 90, min_available_mb: int = 500, sleep_duration: int = 10):
|
75 |
-
"""
|
76 |
-
Check memory usage; if usage is high or available memory is low,
|
77 |
-
force garbage collection and sleep briefly.
|
78 |
-
"""
|
79 |
-
vm = psutil.virtual_memory()
|
80 |
-
used_percent = vm.percent
|
81 |
-
available_mb = vm.available / (1024 * 1024)
|
82 |
-
logger.info(f"Memory usage: {used_percent}% used, {available_mb:.2f} MB available")
|
83 |
-
if used_percent > threshold_percent or available_mb < min_available_mb:
|
84 |
-
logger.warning("High memory usage detected, forcing garbage collection and sleeping...")
|
85 |
-
gc.collect()
|
86 |
-
time.sleep(sleep_duration)
|
87 |
-
|
88 |
-
def manage_gpu_resources(sleep_duration: int = 5):
|
89 |
-
"""
|
90 |
-
Checks GPU memory and empties cache if necessary.
|
91 |
-
"""
|
92 |
-
if torch.cuda.is_available():
|
93 |
-
allocated = torch.cuda.memory_allocated() / (1024 * 1024)
|
94 |
-
cached = torch.cuda.memory_reserved() / (1024 * 1024)
|
95 |
-
logger.info(f"GPU Memory Allocated: {allocated:.2f} MB, Reserved: {cached:.2f} MB")
|
96 |
-
torch.cuda.empty_cache()
|
97 |
-
time.sleep(sleep_duration)
|
98 |
-
|
99 |
-
def zip_checkpoint(checkpoint_dir: str) -> str:
|
100 |
-
"""
|
101 |
-
Zips the checkpoint directory and returns the path to the zip file.
|
102 |
-
"""
|
103 |
-
zip_file = checkpoint_dir + ".zip"
|
104 |
-
if os.path.exists(zip_file):
|
105 |
-
os.remove(zip_file)
|
106 |
-
shutil.make_archive(checkpoint_dir, 'zip', checkpoint_dir)
|
107 |
-
return os.path.basename(zip_file)
|
108 |
-
|
109 |
-
@dataclass
|
110 |
-
class WordAnalysis:
|
111 |
-
"""Structured representation of word-level analysis"""
|
112 |
-
arabic: str
|
113 |
-
translation: str
|
114 |
-
position: str
|
115 |
-
morphology: Dict
|
116 |
-
features: List[str]
|
117 |
-
root: str
|
118 |
-
location: str
|
119 |
-
metadata: Dict
|
120 |
-
|
121 |
-
@dataclass
|
122 |
-
class VerseData:
|
123 |
-
"""Structured representation of verse-level data"""
|
124 |
-
chapter: int
|
125 |
-
verse: int
|
126 |
-
arabic_text: str
|
127 |
-
translation: str
|
128 |
-
words: List[WordAnalysis]
|
129 |
-
metadata: Dict
|
130 |
-
|
131 |
-
class QuranicDataset(Dataset):
|
132 |
-
"""Custom dataset for Quranic text training."""
|
133 |
-
def __init__(self, processed_data: List[Dict], tokenizer):
|
134 |
-
self.examples = []
|
135 |
-
self.tokenizer = tokenizer
|
136 |
-
for verse_data in processed_data:
|
137 |
-
self.examples.extend(self._create_training_examples(verse_data))
|
138 |
-
|
139 |
-
def _create_training_examples(self, verse_data: Dict) -> List[Dict]:
|
140 |
-
examples = []
|
141 |
-
text_block = (
|
142 |
-
f"[VERSE {verse_data['chapter']}:{verse_data['verse']}]\n"
|
143 |
-
f"Arabic: {verse_data['arabic_text']}\n"
|
144 |
-
f"Translation: {verse_data['translation']}\n"
|
145 |
-
"Morphological Analysis:\n"
|
146 |
-
)
|
147 |
-
for word in verse_data['words']:
|
148 |
-
text_block += (
|
149 |
-
f"[WORD] {word['arabic']}\n"
|
150 |
-
f"Root: {word['root']}\n"
|
151 |
-
f"Features: {', '.join(word['features'])}\n"
|
152 |
-
)
|
153 |
-
examples.append(self._format_example(text_block))
|
154 |
-
return examples
|
155 |
-
|
156 |
-
def _format_example(self, text: str) -> Dict:
|
157 |
-
encodings = self.tokenizer(
|
158 |
-
text,
|
159 |
-
truncation=True,
|
160 |
-
max_length=64,
|
161 |
-
padding="max_length",
|
162 |
-
return_tensors="pt"
|
163 |
-
)
|
164 |
-
# Move tensors to CPU explicitly
|
165 |
-
return {
|
166 |
-
"input_ids": encodings["input_ids"][0].cpu(),
|
167 |
-
"attention_mask": encodings["attention_mask"][0].cpu()
|
168 |
-
}
|
169 |
-
|
170 |
-
def __len__(self):
|
171 |
-
return len(self.examples)
|
172 |
-
|
173 |
-
def __getitem__(self, idx):
|
174 |
-
return self.examples[idx]
|
175 |
-
|
176 |
-
class QuranicDataProcessor:
|
177 |
-
"""Processes Quranic data into structured training examples."""
|
178 |
-
def __init__(self, source_dir: str, output_dir: str):
|
179 |
-
self.source_dir = source_dir
|
180 |
-
self.output_dir = output_dir
|
181 |
-
self.morphological_data: Dict[str, Dict] = {}
|
182 |
-
self.word_by_word_data: Dict[str, List[str]] = {}
|
183 |
-
self.translation_data: Dict[str, str] = {}
|
184 |
-
self.processing_lock = Lock()
|
185 |
-
os.makedirs(output_dir, exist_ok=True)
|
186 |
-
os.makedirs(os.path.join(output_dir, 'json'), exist_ok=True)
|
187 |
-
os.makedirs(os.path.join(output_dir, 'txt'), exist_ok=True)
|
188 |
-
os.makedirs(os.path.join(output_dir, 'checkpoints'), exist_ok=True)
|
189 |
-
logger.info(f"Initialized processor with source dir: {source_dir}")
|
190 |
-
|
191 |
-
def load_source_files(self) -> bool:
|
192 |
-
"""Loads morphological, translation, and word-by-word data from project root."""
|
193 |
-
try:
|
194 |
-
logger.info("Loading morphological data...")
|
195 |
-
morph_path = os.path.join(self.source_dir, 'quranic-corpus-morphology-0.4.txt')
|
196 |
-
with open(morph_path, 'r', encoding='utf-8') as f:
|
197 |
-
next(f)
|
198 |
-
for line in f:
|
199 |
-
if line.strip() and not line.startswith('#'):
|
200 |
-
parts = line.strip().split('\t')
|
201 |
-
if len(parts) >= 4:
|
202 |
-
location = parts[0].strip('()')
|
203 |
-
self.morphological_data[location] = {
|
204 |
-
'form': parts[1],
|
205 |
-
'tag': parts[2],
|
206 |
-
'features': parts[3]
|
207 |
-
}
|
208 |
-
logger.info(f"Loaded {len(self.morphological_data)} morphological entries")
|
209 |
-
logger.info("Loading translation data...")
|
210 |
-
trans_path = os.path.join(self.source_dir, 'en.sample.quran-maududi.txt')
|
211 |
-
with open(trans_path, 'r', encoding='utf-8') as f:
|
212 |
-
next(f)
|
213 |
-
for line in f:
|
214 |
-
if line.strip():
|
215 |
-
parts = line.strip().split('|')
|
216 |
-
if len(parts) >= 3:
|
217 |
-
key = f"{parts[0]}:{parts[1]}"
|
218 |
-
self.translation_data[key] = parts[2].strip()
|
219 |
-
logger.info(f"Loaded {len(self.translation_data)} verse translations")
|
220 |
-
logger.info("Loading word-by-word data...")
|
221 |
-
word_path = os.path.join(self.source_dir, 'en.w4w.qurandev.txt')
|
222 |
-
with open(word_path, 'r', encoding='utf-8-sig') as f:
|
223 |
-
lines = [line.strip() for line in f if line.strip()]
|
224 |
-
sorted_keys = sorted(self.translation_data.keys(), key=lambda x: (int(x.split(':')[0]), int(x.split(':')[1])))
|
225 |
-
if len(lines) != len(sorted_keys):
|
226 |
-
logger.warning("Mismatch between word-by-word file and translation data")
|
227 |
-
for i, verse_key in enumerate(sorted_keys):
|
228 |
-
if i < len(lines):
|
229 |
-
words = [w.strip() for w in lines[i].split('|') if w.strip()]
|
230 |
-
self.word_by_word_data[verse_key] = words
|
231 |
-
logger.info(f"Loaded word-by-word data for {len(self.word_by_word_data)} verses")
|
232 |
-
return True
|
233 |
-
except Exception as e:
|
234 |
-
logger.error(f"Error loading source files: {str(e)}")
|
235 |
-
logger.error(traceback.format_exc())
|
236 |
-
return False
|
237 |
-
|
238 |
-
def process_verse(self, chapter: int, verse: int) -> Optional[VerseData]:
|
239 |
-
"""Processes a single verse into structured format."""
|
240 |
-
try:
|
241 |
-
verse_ref = f"{chapter}:{verse}"
|
242 |
-
logger.info(f"Processing verse {verse_ref}")
|
243 |
-
translation = self.translation_data.get(verse_ref)
|
244 |
-
if not translation:
|
245 |
-
logger.warning(f"No translation for verse {verse_ref}")
|
246 |
-
return None
|
247 |
-
verse_word_list = self.word_by_word_data.get(verse_ref, [])
|
248 |
-
if not verse_word_list:
|
249 |
-
logger.warning(f"No word-by-word data for verse {verse_ref}")
|
250 |
-
return None
|
251 |
-
verse_words: List[WordAnalysis] = []
|
252 |
-
arabic_text = ""
|
253 |
-
for pos in range(1, len(verse_word_list) + 1):
|
254 |
-
pattern = f"{chapter}:{verse}:{pos}:"
|
255 |
-
matching_entries = [data for loc, data in self.morphological_data.items() if loc.startswith(pattern)]
|
256 |
-
if not matching_entries:
|
257 |
-
logger.debug(f"No morphological data for {pattern}")
|
258 |
-
continue
|
259 |
-
combined_form = " ".join(entry['form'] for entry in matching_entries)
|
260 |
-
combined_features = []
|
261 |
-
root = ""
|
262 |
-
for entry in matching_entries:
|
263 |
-
features = entry['features'].split('|')
|
264 |
-
combined_features.extend(features)
|
265 |
-
if not root:
|
266 |
-
for f in features:
|
267 |
-
if 'ROOT:' in f:
|
268 |
-
root = f.split('ROOT:')[1]
|
269 |
-
break
|
270 |
-
word_translation = verse_word_list[pos - 1]
|
271 |
-
word = WordAnalysis(
|
272 |
-
arabic=combined_form,
|
273 |
-
translation=word_translation,
|
274 |
-
position=str(pos),
|
275 |
-
morphology=matching_entries[0],
|
276 |
-
features=combined_features,
|
277 |
-
root=root,
|
278 |
-
location=f"{chapter}:{verse}:{pos}",
|
279 |
-
metadata={}
|
280 |
-
)
|
281 |
-
verse_words.append(word)
|
282 |
-
arabic_text += f" {combined_form}"
|
283 |
-
verse_data = VerseData(
|
284 |
-
chapter=chapter,
|
285 |
-
verse=verse,
|
286 |
-
arabic_text=arabic_text.strip(),
|
287 |
-
translation=translation,
|
288 |
-
words=verse_words,
|
289 |
-
metadata={
|
290 |
-
"processed_timestamp": datetime.now().isoformat(),
|
291 |
-
"word_count": len(verse_words)
|
292 |
-
}
|
293 |
-
)
|
294 |
-
self._save_verse_data(verse_data)
|
295 |
-
return verse_data
|
296 |
-
except Exception as e:
|
297 |
-
logger.error(f"Error processing verse {chapter}:{verse}: {str(e)}")
|
298 |
-
logger.error(traceback.format_exc())
|
299 |
-
return None
|
300 |
-
|
301 |
-
def _save_verse_data(self, verse_data: VerseData):
|
302 |
-
"""Saves processed verse data as JSON and TXT."""
|
303 |
-
try:
|
304 |
-
verse_ref = f"{verse_data.chapter}:{verse_data.verse}"
|
305 |
-
json_path = os.path.join(self.output_dir, 'json', f'verse_{verse_ref.replace(":", "_")}.json')
|
306 |
-
with open(json_path, 'w', encoding='utf-8') as f:
|
307 |
-
json.dump(asdict(verse_data), f, ensure_ascii=False, indent=2)
|
308 |
-
txt_path = os.path.join(self.output_dir, 'txt', f'verse_{verse_ref.replace(":", "_")}.txt')
|
309 |
-
with open(txt_path, 'w', encoding='utf-8') as f:
|
310 |
-
f.write(f"=== Verse {verse_ref} ===\n\n")
|
311 |
-
f.write(f"Arabic Text:\n{verse_data.arabic_text}\n\n")
|
312 |
-
f.write(f"Translation:\n{verse_data.translation}\n\n")
|
313 |
-
f.write("Word Analysis:\n")
|
314 |
-
for i, word in enumerate(verse_data.words, 1):
|
315 |
-
f.write(f"\nWord {i}:\n")
|
316 |
-
f.write(f" Arabic: {word.arabic}\n")
|
317 |
-
f.write(f" Translation: {word.translation}\n")
|
318 |
-
f.write(f" Root: {word.root}\n")
|
319 |
-
f.write(" Features:\n")
|
320 |
-
for feature in word.features:
|
321 |
-
f.write(f" - {feature}\n")
|
322 |
-
f.write("\n")
|
323 |
-
logger.info(f"Saved verse data to {json_path} and {txt_path}")
|
324 |
-
except Exception as e:
|
325 |
-
logger.error(f"Error saving verse data: {str(e)}")
|
326 |
-
logger.error(traceback.format_exc())
|
327 |
-
|
328 |
-
class QuranicModelTrainer:
|
329 |
-
"""Trains the Gemma-2-2b model on Quranic data using chunked incremental updates."""
|
330 |
-
def __init__(self,
|
331 |
-
model_name: str = "google/gemma-2-2b",
|
332 |
-
processed_data_dir: str = "processed_data",
|
333 |
-
checkpoint_dir: str = "checkpoints"):
|
334 |
-
self.processed_data_dir = processed_data_dir
|
335 |
-
self.checkpoint_dir = checkpoint_dir
|
336 |
-
self.device = "cuda" if torch.cuda.is_available() else "cpu"
|
337 |
-
logger.info(f"Using device: {self.device}")
|
338 |
-
logger.info("Loading tokenizer and model...")
|
339 |
-
|
340 |
-
self.tokenizer = AutoTokenizer.from_pretrained(
|
341 |
-
model_name,
|
342 |
-
token=os.environ.get("HF_TOKEN"),
|
343 |
-
additional_special_tokens=["[VERSE]", "[WORD]", "[ROOT]", "[FEATURES]"],
|
344 |
-
trust_remote_code=True
|
345 |
-
)
|
346 |
-
if self.tokenizer.pad_token is None:
|
347 |
-
self.tokenizer.add_special_tokens({"pad_token": "[PAD]"})
|
348 |
-
|
349 |
-
try:
|
350 |
-
self.model = AutoModelForCausalLM.from_pretrained(
|
351 |
-
model_name,
|
352 |
-
token=os.environ.get("HF_TOKEN"),
|
353 |
-
torch_dtype=torch.float32,
|
354 |
-
low_cpu_mem_usage=True,
|
355 |
-
trust_remote_code=True,
|
356 |
-
attn_implementation="eager"
|
357 |
-
)
|
358 |
-
except Exception as e:
|
359 |
-
logger.error(f"Error loading model directly: {str(e)}")
|
360 |
-
logger.info("Attempting to load with fallback parameters...")
|
361 |
-
from transformers import AutoConfig
|
362 |
-
config = AutoConfig.from_pretrained(
|
363 |
-
model_name,
|
364 |
-
token=os.environ.get("HF_TOKEN"),
|
365 |
-
trust_remote_code=True
|
366 |
-
)
|
367 |
-
self.model = AutoModelForCausalLM.from_pretrained(
|
368 |
-
model_name,
|
369 |
-
token=os.environ.get("HF_TOKEN"),
|
370 |
-
config=config,
|
371 |
-
torch_dtype=torch.float32,
|
372 |
-
low_cpu_mem_usage=True,
|
373 |
-
trust_remote_code=True,
|
374 |
-
revision="main",
|
375 |
-
attn_implementation="eager"
|
376 |
-
)
|
377 |
-
|
378 |
-
self.model.resize_token_embeddings(len(self.tokenizer))
|
379 |
-
self.model.train()
|
380 |
-
self.model.config.use_cache = False
|
381 |
-
|
382 |
-
if hasattr(self.model, "gradient_checkpointing_enable"):
|
383 |
-
self.model.gradient_checkpointing_enable()
|
384 |
-
else:
|
385 |
-
logger.warning("Gradient checkpointing not available for this model")
|
386 |
-
|
387 |
-
# Use Accelerate for device management
|
388 |
-
from accelerate import Accelerator
|
389 |
-
self.accelerator = Accelerator()
|
390 |
-
self.model = self.accelerator.prepare(self.model)
|
391 |
-
|
392 |
-
def prepare_training_data(self, chapter_data: List[Dict]) -> Dataset:
|
393 |
-
"""Creates a QuranicDataset from processed chapter data."""
|
394 |
-
return QuranicDataset(chapter_data, self.tokenizer)
|
395 |
-
|
396 |
-
def train_chunk(self, training_args: TrainingArguments, dataset: Dataset, chunk_output_dir: str) -> bool:
|
397 |
-
"""
|
398 |
-
Trains a single chunk. Returns True if successful.
|
399 |
-
"""
|
400 |
-
try:
|
401 |
-
data_collator = DataCollatorForLanguageModeling(
|
402 |
-
tokenizer=self.tokenizer,
|
403 |
-
mlm=False
|
404 |
-
)
|
405 |
-
trainer = Trainer(
|
406 |
-
model=self.model,
|
407 |
-
args=training_args,
|
408 |
-
train_dataset=dataset,
|
409 |
-
processing_class=self.tokenizer, # Updated per deprecation notice.
|
410 |
-
data_collator=data_collator
|
411 |
-
)
|
412 |
-
logger.info(f"Starting training on chunk at {chunk_output_dir} with device {self.device}")
|
413 |
-
trainer.train()
|
414 |
-
trainer.save_model(chunk_output_dir)
|
415 |
-
zip_filename = zip_checkpoint(chunk_output_dir)
|
416 |
-
base_url = os.environ.get("HF_SPACE_URL", "http://localhost")
|
417 |
-
download_link = f"{base_url}/file/{zip_filename}"
|
418 |
-
logger.info(f"Checkpoint download link: {download_link}")
|
419 |
-
with open(os.path.join(chunk_output_dir, "download_link.txt"), "w") as f:
|
420 |
-
f.write(download_link)
|
421 |
-
del trainer
|
422 |
-
gc.collect()
|
423 |
-
manage_memory()
|
424 |
-
manage_gpu_resources()
|
425 |
-
return True
|
426 |
-
except Exception as e:
|
427 |
-
logger.error(f"Error in training chunk at {chunk_output_dir}: {str(e)}")
|
428 |
-
logger.error(traceback.format_exc())
|
429 |
-
return False
|
430 |
-
|
431 |
-
def poll_for_gpu(self, poll_interval: int = 10, max_attempts: int = 30) -> bool:
|
432 |
-
"""
|
433 |
-
Polls periodically to check if GPU is available.
|
434 |
-
Returns True if GPU becomes available within the attempts, otherwise False.
|
435 |
-
"""
|
436 |
-
attempts = 0
|
437 |
-
while attempts < max_attempts:
|
438 |
-
if torch.cuda.is_available():
|
439 |
-
manage_gpu_resources(1)
|
440 |
-
logger.info("GPU is now available for training.")
|
441 |
-
return True
|
442 |
-
time.sleep(poll_interval)
|
443 |
-
attempts += 1
|
444 |
-
logger.info(f"Polling for GPU availability... attempt {attempts}/{max_attempts}")
|
445 |
-
return False
|
446 |
-
|
447 |
-
def train_chapter(self,
|
448 |
-
chapter_num: int,
|
449 |
-
processed_verses: List[Dict],
|
450 |
-
chunk_size: int = 5, # Reduced chunk size
|
451 |
-
num_train_epochs: int = 5, # Lower epochs for testing
|
452 |
-
per_device_train_batch_size: int = 1,
|
453 |
-
learning_rate: float = 3e-5,
|
454 |
-
weight_decay: float = 0.01,
|
455 |
-
gradient_accumulation_steps: int = 32) -> bool:
|
456 |
-
"""
|
457 |
-
Splits chapter data into chunks and trains incrementally.
|
458 |
-
If GPU training fails, shifts to CPU and then polls for GPU availability
|
459 |
-
to switch back.
|
460 |
-
"""
|
461 |
-
total_examples = len(processed_verses)
|
462 |
-
total_chunks = math.ceil(total_examples / chunk_size)
|
463 |
-
logger.info(f"Chapter {chapter_num}: {total_examples} examples, {total_chunks} chunks.")
|
464 |
-
for chunk_index in range(total_chunks):
|
465 |
-
chunk_data = processed_verses[chunk_index * chunk_size: (chunk_index + 1) * chunk_size]
|
466 |
-
dataset = self.prepare_training_data(chunk_data)
|
467 |
-
chunk_output_dir = os.path.join(self.checkpoint_dir, f"chapter_{chapter_num}", f"chunk_{chunk_index}")
|
468 |
-
os.makedirs(chunk_output_dir, exist_ok=True)
|
469 |
-
|
470 |
-
training_args = TrainingArguments(
|
471 |
-
output_dir=chunk_output_dir,
|
472 |
-
overwrite_output_dir=True,
|
473 |
-
num_train_epochs=num_train_epochs,
|
474 |
-
per_device_train_batch_size=per_device_train_batch_size,
|
475 |
-
learning_rate=learning_rate,
|
476 |
-
weight_decay=weight_decay,
|
477 |
-
gradient_accumulation_steps=gradient_accumulation_steps,
|
478 |
-
fp16=False,
|
479 |
-
remove_unused_columns=False,
|
480 |
-
logging_steps=50,
|
481 |
-
report_to="none",
|
482 |
-
eval_strategy="no",
|
483 |
-
no_cuda=(self.device == "cpu"), # Force-disable CUDA when on CPU
|
484 |
-
dataloader_num_workers=0,
|
485 |
-
dataloader_pin_memory=False
|
486 |
-
)
|
487 |
-
logger.info(f"Training chunk {chunk_index+1}/{total_chunks} for Chapter {chapter_num} on device {self.device}...")
|
488 |
-
success = self.train_chunk(training_args, dataset, chunk_output_dir)
|
489 |
-
|
490 |
-
# If training fails on GPU, shift to CPU and retry with reinitialized optimizer
|
491 |
-
if not success and self.device == "cuda":
|
492 |
-
logger.info(f"GPU error detected on chunk {chunk_index+1}. Shifting to CPU for this chunk...")
|
493 |
-
self.model.to("cpu")
|
494 |
-
self.device = "cpu"
|
495 |
-
# Reinitialize optimizer for CPU by setting the explicit optimizer type
|
496 |
-
training_args.no_cuda = True
|
497 |
-
training_args.optim = "adamw_torch" # Explicit optimizer for CPU
|
498 |
-
success = self.train_chunk(training_args, dataset, chunk_output_dir)
|
499 |
-
if not success:
|
500 |
-
logger.error(f"Training failed for Chapter {chapter_num} on chunk {chunk_index+1} even on CPU. Stopping chapter training.")
|
501 |
-
return False
|
502 |
-
# Poll for GPU availability before switching back
|
503 |
-
if self.poll_for_gpu():
|
504 |
-
self.model.to("cuda")
|
505 |
-
self.device = "cuda"
|
506 |
-
else:
|
507 |
-
logger.warning("GPU did not become available during polling. Continuing on CPU.")
|
508 |
-
|
509 |
-
if not success:
|
510 |
-
logger.error(f"Training failed for Chapter {chapter_num} on chunk {chunk_index+1}. Stopping chapter training.")
|
511 |
-
return False
|
512 |
-
logger.info(f"Completed training for Chapter {chapter_num}")
|
513 |
-
return True
|
514 |
-
|
515 |
-
class QuranicPipeline:
|
516 |
-
"""Integrates data processing and incremental model training for all chapters."""
|
517 |
-
def __init__(self,
|
518 |
-
source_dir: str = ".",
|
519 |
-
working_dir: str = "working_directory",
|
520 |
-
start_chapter: int = 1,
|
521 |
-
end_chapter: int = 114):
|
522 |
-
self.source_dir = source_dir
|
523 |
-
self.working_dir = working_dir
|
524 |
-
self.start_chapter = start_chapter
|
525 |
-
self.end_chapter = end_chapter
|
526 |
-
self.setup_directories()
|
527 |
-
global logger
|
528 |
-
logger = logging.getLogger(__name__)
|
529 |
-
self.state = {
|
530 |
-
"last_processed_chapter": 0,
|
531 |
-
"last_trained_chapter": 0,
|
532 |
-
"current_state": "initialized",
|
533 |
-
"errors": [],
|
534 |
-
"start_time": datetime.now().isoformat()
|
535 |
-
}
|
536 |
-
self.load_state()
|
537 |
-
try:
|
538 |
-
logger.info("Initializing Quranic Data Processor...")
|
539 |
-
self.processor = QuranicDataProcessor(
|
540 |
-
source_dir=self.source_dir,
|
541 |
-
output_dir=os.path.join(self.working_dir, "processed_data")
|
542 |
-
)
|
543 |
-
logger.info("Initializing Quranic Model Trainer...")
|
544 |
-
self.trainer = QuranicModelTrainer(
|
545 |
-
model_name="google/gemma-2-2b",
|
546 |
-
processed_data_dir=os.path.join(self.working_dir, "processed_data"),
|
547 |
-
checkpoint_dir=os.path.join(self.working_dir, "checkpoints")
|
548 |
-
)
|
549 |
-
self.state["current_state"] = "ready"
|
550 |
-
self.save_state()
|
551 |
-
except Exception as e:
|
552 |
-
self.handle_error("Initialization failed", e)
|
553 |
-
raise
|
554 |
-
|
555 |
-
def setup_directories(self):
|
556 |
-
dirs = [
|
557 |
-
self.working_dir,
|
558 |
-
os.path.join(self.working_dir, "processed_data"),
|
559 |
-
os.path.join(self.working_dir, "checkpoints"),
|
560 |
-
os.path.join(self.working_dir, "logs"),
|
561 |
-
os.path.join(self.working_dir, "state")
|
562 |
-
]
|
563 |
-
for d in dirs:
|
564 |
-
os.makedirs(d, exist_ok=True)
|
565 |
-
|
566 |
-
def load_state(self):
|
567 |
-
state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
|
568 |
-
if os.path.exists(state_file):
|
569 |
-
try:
|
570 |
-
with open(state_file, 'r') as f:
|
571 |
-
saved_state = json.load(f)
|
572 |
-
self.state.update(saved_state)
|
573 |
-
logger.info(f"Loaded previous state: Last processed chapter {self.state.get('last_processed_chapter')}, last trained chapter {self.state.get('last_trained_chapter')}")
|
574 |
-
except Exception as e:
|
575 |
-
logger.warning(f"Could not load previous state: {str(e)}")
|
576 |
-
|
577 |
-
def save_state(self):
|
578 |
-
state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
|
579 |
-
with open(state_file, 'w') as f:
|
580 |
-
json.dump(self.state, f, indent=2)
|
581 |
-
|
582 |
-
def handle_error(self, context: str, error: Exception):
|
583 |
-
error_detail = {
|
584 |
-
"timestamp": datetime.now().isoformat(),
|
585 |
-
"context": context,
|
586 |
-
"error": str(error),
|
587 |
-
"traceback": traceback.format_exc()
|
588 |
-
}
|
589 |
-
self.state.setdefault("errors", []).append(error_detail)
|
590 |
-
logger.error(f"{context}: {str(error)}")
|
591 |
-
self.save_state()
|
592 |
-
|
593 |
-
def run_pipeline(self):
|
594 |
-
"""Runs processing and training for chapters sequentially, then saves the final model."""
|
595 |
-
logger.info("Starting pipeline execution")
|
596 |
-
try:
|
597 |
-
if not self.processor.load_source_files():
|
598 |
-
raise Exception("Failed to load source files")
|
599 |
-
for chapter in range(self.start_chapter, self.end_chapter + 1):
|
600 |
-
logger.info(f"=== Processing Chapter {chapter} ===")
|
601 |
-
processed_chapter_data = []
|
602 |
-
verse = 1
|
603 |
-
while True:
|
604 |
-
verse_data = self.processor.process_verse(chapter, verse)
|
605 |
-
if verse_data is None:
|
606 |
-
break
|
607 |
-
processed_chapter_data.append(asdict(verse_data))
|
608 |
-
verse += 1
|
609 |
-
if processed_chapter_data:
|
610 |
-
success = self.trainer.train_chapter(chapter, processed_chapter_data)
|
611 |
-
if not success:
|
612 |
-
logger.error(f"Training failed for Chapter {chapter}. Stopping pipeline.")
|
613 |
-
break
|
614 |
-
self.state["last_trained_chapter"] = chapter
|
615 |
-
self.save_state()
|
616 |
-
else:
|
617 |
-
logger.warning(f"No processed data for Chapter {chapter}")
|
618 |
-
self.state["last_processed_chapter"] = chapter
|
619 |
-
self.save_state()
|
620 |
-
manage_memory()
|
621 |
-
manage_gpu_resources()
|
622 |
-
logger.info("Pipeline execution completed")
|
623 |
-
final_model_dir = os.path.join(self.working_dir, "final_model")
|
624 |
-
os.makedirs(final_model_dir, exist_ok=True)
|
625 |
-
self.trainer.model.save_pretrained(final_model_dir)
|
626 |
-
self.trainer.tokenizer.save_pretrained(final_model_dir)
|
627 |
-
logger.info(f"Final model saved to {final_model_dir}")
|
628 |
-
except Exception as e:
|
629 |
-
self.handle_error("Pipeline execution failed", e)
|
630 |
-
raise
|
631 |
-
|
632 |
-
@spaces.GPU() # Request ZeroGPU hardware for the Space
|
633 |
-
def start_pipeline():
|
634 |
-
try:
|
635 |
-
logger.info("Starting Quranic Training Pipeline with Gemma-2-2b")
|
636 |
-
logger.info(f"PyTorch version: {torch.__version__}")
|
637 |
-
logger.info(f"CUDA available: {torch.cuda.is_available()}")
|
638 |
-
if torch.cuda.is_available():
|
639 |
-
logger.info(f"CUDA device count: {torch.cuda.device_count()}")
|
640 |
-
logger.info(f"CUDA device name: {torch.cuda.get_device_name(0)}")
|
641 |
-
if not os.environ.get("HF_TOKEN"):
|
642 |
-
logger.warning("HF_TOKEN environment variable not set. Model loading may fail.")
|
643 |
-
required_files = [
|
644 |
-
'quranic-corpus-morphology-0.4.txt',
|
645 |
-
'en.sample.quran-maududi.txt',
|
646 |
-
'en.w4w.qurandev.txt'
|
647 |
-
]
|
648 |
-
missing_files = [f for f in required_files if not os.path.exists(f)]
|
649 |
-
if missing_files:
|
650 |
-
return f"Missing required data files: {', '.join(missing_files)}"
|
651 |
-
pipeline = QuranicPipeline(
|
652 |
-
source_dir=".",
|
653 |
-
working_dir="working_directory",
|
654 |
-
start_chapter=1,
|
655 |
-
end_chapter=114
|
656 |
-
)
|
657 |
-
pipeline.run_pipeline()
|
658 |
-
return "Pipeline execution completed successfully."
|
659 |
-
except Exception as e:
|
660 |
-
error_msg = f"Pipeline execution failed: {str(e)}\n{traceback.format_exc()}"
|
661 |
-
logger.error(error_msg)
|
662 |
-
return error_msg
|
663 |
-
|
664 |
-
iface = gr.Interface(
|
665 |
-
fn=start_pipeline,
|
666 |
-
inputs=[],
|
667 |
-
outputs=gr.Textbox(label="Pipeline Status", lines=10),
|
668 |
-
title="Quranic Training Pipeline for Gemma-2-2b",
|
669 |
-
description="""This pipeline fine-tunes Google's Gemma-2-2b model on Quranic data.
|
670 |
-
|
671 |
-
Click 'Submit' to trigger the Quranic data processing and training pipeline on ZeroGPU.
|
672 |
-
|
673 |
-
Requirements:
|
674 |
-
- Transformers (==4.45.0)
|
675 |
-
- Gradio (>=5.12.0)
|
676 |
-
- PyTorch (==2.3.0)
|
677 |
-
- psutil (==5.9.5)
|
678 |
-
- Accelerate (>=0.26.0)
|
679 |
-
|
680 |
-
The pipeline processes all 114 chapters of the Quran sequentially, with memory and GPU resource management optimizations.
|
681 |
-
Checkpoint download links are provided after every training chunk."""
|
682 |
-
)
|
683 |
-
|
684 |
-
if __name__ == "__main__":
|
685 |
-
iface.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|