eBlessings commited on
Commit
61575d5
·
verified ·
1 Parent(s): e682fad

Upload gpt13.py

Browse files
Files changed (1) hide show
  1. gpt13.py +683 -0
gpt13.py ADDED
@@ -0,0 +1,683 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ # Explicitly move tensors to CPU
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
+ # Force CPU mode initially regardless of GPU availability.
337
+ self.device = "cpu"
338
+ logger.info("Forcing training on CPU initially.")
339
+ logger.info("Loading tokenizer and model...")
340
+
341
+ self.tokenizer = AutoTokenizer.from_pretrained(
342
+ model_name,
343
+ token=os.environ.get("HF_TOKEN"),
344
+ additional_special_tokens=["[VERSE]", "[WORD]", "[ROOT]", "[FEATURES]"],
345
+ trust_remote_code=True
346
+ )
347
+ if self.tokenizer.pad_token is None:
348
+ self.tokenizer.add_special_tokens({"pad_token": "[PAD]"})
349
+
350
+ try:
351
+ self.model = AutoModelForCausalLM.from_pretrained(
352
+ model_name,
353
+ token=os.environ.get("HF_TOKEN"),
354
+ torch_dtype=torch.float32,
355
+ low_cpu_mem_usage=True,
356
+ trust_remote_code=True,
357
+ attn_implementation="eager"
358
+ )
359
+ except Exception as e:
360
+ logger.error(f"Error loading model directly: {str(e)}")
361
+ logger.info("Attempting to load with fallback parameters...")
362
+ from transformers import AutoConfig
363
+ config = AutoConfig.from_pretrained(
364
+ model_name,
365
+ token=os.environ.get("HF_TOKEN"),
366
+ trust_remote_code=True
367
+ )
368
+ self.model = AutoModelForCausalLM.from_pretrained(
369
+ model_name,
370
+ token=os.environ.get("HF_TOKEN"),
371
+ config=config,
372
+ torch_dtype=torch.float32,
373
+ low_cpu_mem_usage=True,
374
+ trust_remote_code=True,
375
+ revision="main",
376
+ attn_implementation="eager"
377
+ )
378
+
379
+ self.model.resize_token_embeddings(len(self.tokenizer))
380
+ self.model.train()
381
+ self.model.config.use_cache = False
382
+
383
+ if hasattr(self.model, "gradient_checkpointing_enable"):
384
+ self.model.gradient_checkpointing_enable()
385
+ else:
386
+ logger.warning("Gradient checkpointing not available for this model")
387
+
388
+ # Use Accelerate for device management; force CPU initially.
389
+ from accelerate import Accelerator
390
+ self.accelerator = Accelerator(cpu=True)
391
+ self.model = self.accelerator.prepare(self.model)
392
+
393
+ def prepare_training_data(self, chapter_data: List[Dict]) -> Dataset:
394
+ """Creates a QuranicDataset from processed chapter data."""
395
+ return QuranicDataset(chapter_data, self.tokenizer)
396
+
397
+ def train_chunk(self, training_args: TrainingArguments, dataset: Dataset, chunk_output_dir: str) -> bool:
398
+ """
399
+ Trains a single chunk. Returns True if successful.
400
+ """
401
+ try:
402
+ data_collator = DataCollatorForLanguageModeling(
403
+ tokenizer=self.tokenizer,
404
+ mlm=False
405
+ )
406
+ trainer = Trainer(
407
+ model=self.model,
408
+ args=training_args,
409
+ train_dataset=dataset,
410
+ processing_class=self.tokenizer, # Updated per deprecation notice.
411
+ data_collator=data_collator
412
+ )
413
+ logger.info(f"Starting training on chunk at {chunk_output_dir} with device {self.device}")
414
+ trainer.train()
415
+ trainer.save_model(chunk_output_dir)
416
+ zip_filename = zip_checkpoint(chunk_output_dir)
417
+ base_url = os.environ.get("HF_SPACE_URL", "http://localhost")
418
+ download_link = f"{base_url}/file/{zip_filename}"
419
+ logger.info(f"Checkpoint download link: {download_link}")
420
+ with open(os.path.join(chunk_output_dir, "download_link.txt"), "w") as f:
421
+ f.write(download_link)
422
+ del trainer
423
+ gc.collect()
424
+ manage_memory()
425
+ manage_gpu_resources()
426
+ return True
427
+ except Exception as e:
428
+ logger.error(f"Error in training chunk at {chunk_output_dir}: {str(e)}")
429
+ logger.error(traceback.format_exc())
430
+ return False
431
+
432
+ def poll_for_gpu(self, poll_interval: int = 10, max_attempts: int = 30) -> bool:
433
+ """
434
+ Polls periodically to check if GPU is available.
435
+ Returns True if GPU becomes available within the attempts, otherwise False.
436
+ """
437
+ attempts = 0
438
+ while attempts < max_attempts:
439
+ if torch.cuda.is_available():
440
+ manage_gpu_resources(1)
441
+ logger.info("GPU is now available for training.")
442
+ return True
443
+ time.sleep(poll_interval)
444
+ attempts += 1
445
+ logger.info(f"Polling for GPU availability... attempt {attempts}/{max_attempts}")
446
+ return False
447
+
448
+ def train_chapter(self,
449
+ chapter_num: int,
450
+ processed_verses: List[Dict],
451
+ chunk_size: int = 5, # Reduced chunk size
452
+ num_train_epochs: int = 5, # Lower epochs for testing
453
+ per_device_train_batch_size: int = 1,
454
+ learning_rate: float = 3e-5,
455
+ weight_decay: float = 0.01,
456
+ gradient_accumulation_steps: int = 32) -> bool:
457
+ """
458
+ Splits chapter data into chunks and trains incrementally.
459
+ The pipeline starts on CPU. After each chunk is trained on CPU, it polls for GPU.
460
+ If GPU becomes available, the model is moved to GPU for subsequent training.
461
+ In case GPU training fails, it falls back to CPU.
462
+ """
463
+ total_examples = len(processed_verses)
464
+ total_chunks = math.ceil(total_examples / chunk_size)
465
+ logger.info(f"Chapter {chapter_num}: {total_examples} examples, {total_chunks} chunks.")
466
+ for chunk_index in range(total_chunks):
467
+ chunk_data = processed_verses[chunk_index * chunk_size: (chunk_index + 1) * chunk_size]
468
+ dataset = self.prepare_training_data(chunk_data)
469
+ chunk_output_dir = os.path.join(self.checkpoint_dir, f"chapter_{chapter_num}", f"chunk_{chunk_index}")
470
+ os.makedirs(chunk_output_dir, exist_ok=True)
471
+
472
+ training_args = TrainingArguments(
473
+ output_dir=chunk_output_dir,
474
+ overwrite_output_dir=True,
475
+ num_train_epochs=num_train_epochs,
476
+ per_device_train_batch_size=per_device_train_batch_size,
477
+ learning_rate=learning_rate,
478
+ weight_decay=weight_decay,
479
+ gradient_accumulation_steps=gradient_accumulation_steps,
480
+ fp16=False,
481
+ remove_unused_columns=False,
482
+ logging_steps=50,
483
+ report_to="none",
484
+ eval_strategy="no",
485
+ no_cuda=(self.device == "cpu"), # Force-disable CUDA when on CPU
486
+ dataloader_num_workers=0,
487
+ dataloader_pin_memory=False
488
+ )
489
+ logger.info(f"Training chunk {chunk_index+1}/{total_chunks} for Chapter {chapter_num} on device {self.device}...")
490
+ success = self.train_chunk(training_args, dataset, chunk_output_dir)
491
+
492
+ # If training fails on GPU, fall back to CPU.
493
+ if not success and self.device == "cuda":
494
+ logger.info(f"GPU error detected on chunk {chunk_index+1}. Shifting to CPU for this chunk...")
495
+ self.model.to("cpu")
496
+ self.device = "cpu"
497
+ training_args.no_cuda = True
498
+ training_args.optim = "adamw_torch" # Explicit optimizer for CPU
499
+ success = self.train_chunk(training_args, dataset, chunk_output_dir)
500
+ if not success:
501
+ logger.error(f"Training failed for Chapter {chapter_num} on chunk {chunk_index+1} even on CPU. Stopping chapter training.")
502
+ return False
503
+
504
+ # If running on CPU, poll for GPU availability after the chunk
505
+ if self.device == "cpu":
506
+ if self.poll_for_gpu():
507
+ logger.info("GPU available; switching model to GPU for subsequent chunks.")
508
+ self.model.to("cuda")
509
+ self.device = "cuda"
510
+ logger.info(f"Completed training for Chapter {chapter_num}")
511
+ return True
512
+
513
+ class QuranicPipeline:
514
+ """Integrates data processing and incremental model training for all chapters."""
515
+ def __init__(self,
516
+ source_dir: str = ".",
517
+ working_dir: str = "working_directory",
518
+ start_chapter: int = 1,
519
+ end_chapter: int = 114):
520
+ self.source_dir = source_dir
521
+ self.working_dir = working_dir
522
+ self.start_chapter = start_chapter
523
+ self.end_chapter = end_chapter
524
+ self.setup_directories()
525
+ global logger
526
+ logger = logging.getLogger(__name__)
527
+ self.state = {
528
+ "last_processed_chapter": 0,
529
+ "last_trained_chapter": 0,
530
+ "current_state": "initialized",
531
+ "errors": [],
532
+ "start_time": datetime.now().isoformat()
533
+ }
534
+ self.load_state()
535
+ try:
536
+ logger.info("Initializing Quranic Data Processor...")
537
+ self.processor = QuranicDataProcessor(
538
+ source_dir=self.source_dir,
539
+ output_dir=os.path.join(self.working_dir, "processed_data")
540
+ )
541
+ logger.info("Initializing Quranic Model Trainer...")
542
+ self.trainer = QuranicModelTrainer(
543
+ model_name="google/gemma-2-2b",
544
+ processed_data_dir=os.path.join(self.working_dir, "processed_data"),
545
+ checkpoint_dir=os.path.join(self.working_dir, "checkpoints")
546
+ )
547
+ self.state["current_state"] = "ready"
548
+ self.save_state()
549
+ except Exception as e:
550
+ self.handle_error("Initialization failed", e)
551
+ raise
552
+
553
+ def setup_directories(self):
554
+ dirs = [
555
+ self.working_dir,
556
+ os.path.join(self.working_dir, "processed_data"),
557
+ os.path.join(self.working_dir, "checkpoints"),
558
+ os.path.join(self.working_dir, "logs"),
559
+ os.path.join(self.working_dir, "state")
560
+ ]
561
+ for d in dirs:
562
+ os.makedirs(d, exist_ok=True)
563
+
564
+ def load_state(self):
565
+ state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
566
+ if os.path.exists(state_file):
567
+ try:
568
+ with open(state_file, 'r') as f:
569
+ saved_state = json.load(f)
570
+ self.state.update(saved_state)
571
+ logger.info(f"Loaded previous state: Last processed chapter {self.state.get('last_processed_chapter')}, last trained chapter {self.state.get('last_trained_chapter')}")
572
+ except Exception as e:
573
+ logger.warning(f"Could not load previous state: {str(e)}")
574
+
575
+ def save_state(self):
576
+ state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
577
+ with open(state_file, 'w') as f:
578
+ json.dump(self.state, f, indent=2)
579
+
580
+ def handle_error(self, context: str, error: Exception):
581
+ error_detail = {
582
+ "timestamp": datetime.now().isoformat(),
583
+ "context": context,
584
+ "error": str(error),
585
+ "traceback": traceback.format_exc()
586
+ }
587
+ self.state.setdefault("errors", []).append(error_detail)
588
+ logger.error(f"{context}: {str(error)}")
589
+ self.save_state()
590
+
591
+ def run_pipeline(self):
592
+ """Runs processing and training for chapters sequentially, then saves the final model."""
593
+ logger.info("Starting pipeline execution")
594
+ try:
595
+ if not self.processor.load_source_files():
596
+ raise Exception("Failed to load source files")
597
+ for chapter in range(self.start_chapter, self.end_chapter + 1):
598
+ logger.info(f"=== Processing Chapter {chapter} ===")
599
+ processed_chapter_data = []
600
+ verse = 1
601
+ while True:
602
+ verse_data = self.processor.process_verse(chapter, verse)
603
+ if verse_data is None:
604
+ break
605
+ processed_chapter_data.append(asdict(verse_data))
606
+ verse += 1
607
+ if processed_chapter_data:
608
+ success = self.trainer.train_chapter(chapter, processed_chapter_data)
609
+ if not success:
610
+ logger.error(f"Training failed for Chapter {chapter}. Stopping pipeline.")
611
+ break
612
+ self.state["last_trained_chapter"] = chapter
613
+ self.save_state()
614
+ else:
615
+ logger.warning(f"No processed data for Chapter {chapter}")
616
+ self.state["last_processed_chapter"] = chapter
617
+ self.save_state()
618
+ manage_memory()
619
+ manage_gpu_resources()
620
+ logger.info("Pipeline execution completed")
621
+ final_model_dir = os.path.join(self.working_dir, "final_model")
622
+ os.makedirs(final_model_dir, exist_ok=True)
623
+ self.trainer.model.save_pretrained(final_model_dir)
624
+ self.trainer.tokenizer.save_pretrained(final_model_dir)
625
+ logger.info(f"Final model saved to {final_model_dir}")
626
+ except Exception as e:
627
+ self.handle_error("Pipeline execution failed", e)
628
+ raise
629
+
630
+ @spaces.GPU() # Request ZeroGPU hardware for the Space
631
+ def start_pipeline():
632
+ try:
633
+ logger.info("Starting Quranic Training Pipeline with Gemma-2-2b")
634
+ logger.info(f"PyTorch version: {torch.__version__}")
635
+ logger.info(f"CUDA available: {torch.cuda.is_available()}")
636
+ if torch.cuda.is_available():
637
+ logger.info(f"CUDA device count: {torch.cuda.device_count()}")
638
+ logger.info(f"CUDA device name: {torch.cuda.get_device_name(0)}")
639
+ if not os.environ.get("HF_TOKEN"):
640
+ logger.warning("HF_TOKEN environment variable not set. Model loading may fail.")
641
+ required_files = [
642
+ 'quranic-corpus-morphology-0.4.txt',
643
+ 'en.sample.quran-maududi.txt',
644
+ 'en.w4w.qurandev.txt'
645
+ ]
646
+ missing_files = [f for f in required_files if not os.path.exists(f)]
647
+ if missing_files:
648
+ return f"Missing required data files: {', '.join(missing_files)}"
649
+ pipeline = QuranicPipeline(
650
+ source_dir=".",
651
+ working_dir="working_directory",
652
+ start_chapter=1,
653
+ end_chapter=114
654
+ )
655
+ pipeline.run_pipeline()
656
+ return "Pipeline execution completed successfully."
657
+ except Exception as e:
658
+ error_msg = f"Pipeline execution failed: {str(e)}\n{traceback.format_exc()}"
659
+ logger.error(error_msg)
660
+ return error_msg
661
+
662
+ iface = gr.Interface(
663
+ fn=start_pipeline,
664
+ inputs=[],
665
+ outputs=gr.Textbox(label="Pipeline Status", lines=10),
666
+ title="Quranic Training Pipeline for Gemma-2-2b",
667
+ description="""This pipeline fine-tunes Google's Gemma-2-2b model on Quranic data.
668
+
669
+ Click 'Submit' to trigger the Quranic data processing and training pipeline on ZeroGPU.
670
+
671
+ Requirements:
672
+ - Transformers (==4.45.0)
673
+ - Gradio (>=5.12.0)
674
+ - PyTorch (==2.3.0)
675
+ - psutil (==5.9.5)
676
+ - Accelerate (>=0.26.0)
677
+
678
+ The pipeline processes all 114 chapters of the Quran sequentially, with memory and GPU resource management optimizations.
679
+ Checkpoint download links are provided after every training chunk."""
680
+ )
681
+
682
+ if __name__ == "__main__":
683
+ iface.launch()