eBlessings commited on
Commit
b4c5abc
·
verified ·
1 Parent(s): 2d399bd

Upload gpt4.py

Browse files
Files changed (1) hide show
  1. gpt4.py +609 -0
gpt4.py ADDED
@@ -0,0 +1,609 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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-based training on
7
+ 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.42.0)
13
+ - Gradio (>=5.12.0)
14
+ - PyTorch (==2.2.2)
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 sys
31
+ import traceback
32
+ import gc
33
+ import time
34
+ import psutil
35
+ import math
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
+ @dataclass
89
+ class WordAnalysis:
90
+ """Structured representation of word-level analysis"""
91
+ arabic: str
92
+ translation: str
93
+ position: str
94
+ morphology: Dict
95
+ features: List[str]
96
+ root: str
97
+ location: str
98
+ metadata: Dict
99
+
100
+ @dataclass
101
+ class VerseData:
102
+ """Structured representation of verse-level data"""
103
+ chapter: int
104
+ verse: int
105
+ arabic_text: str
106
+ translation: str
107
+ words: List[WordAnalysis]
108
+ metadata: Dict
109
+
110
+ class QuranicDataset(Dataset):
111
+ """Custom dataset for Quranic text training."""
112
+ def __init__(self, processed_data: List[Dict], tokenizer):
113
+ self.examples = []
114
+ self.tokenizer = tokenizer
115
+ for verse_data in processed_data:
116
+ self.examples.extend(self._create_training_examples(verse_data))
117
+
118
+ def _create_training_examples(self, verse_data: Dict) -> List[Dict]:
119
+ examples = []
120
+ text_block = (
121
+ f"[VERSE {verse_data['chapter']}:{verse_data['verse']}]\n"
122
+ f"Arabic: {verse_data['arabic_text']}\n"
123
+ f"Translation: {verse_data['translation']}\n"
124
+ "Morphological Analysis:\n"
125
+ )
126
+ for word in verse_data['words']:
127
+ text_block += (
128
+ f"[WORD] {word['arabic']}\n"
129
+ f"Root: {word['root']}\n"
130
+ f"Features: {', '.join(word['features'])}\n"
131
+ )
132
+ examples.append(self._format_example(text_block))
133
+ return examples
134
+
135
+ def _format_example(self, text: str) -> Dict:
136
+ encodings = self.tokenizer(
137
+ text,
138
+ truncation=True,
139
+ max_length=64,
140
+ padding="max_length",
141
+ return_tensors="pt"
142
+ )
143
+ return {
144
+ "input_ids": encodings["input_ids"][0],
145
+ "attention_mask": encodings["attention_mask"][0]
146
+ }
147
+
148
+ def __len__(self):
149
+ return len(self.examples)
150
+
151
+ def __getitem__(self, idx):
152
+ return self.examples[idx]
153
+
154
+ class QuranicDataProcessor:
155
+ """Processes Quranic data into structured training examples."""
156
+ def __init__(self, source_dir: str, output_dir: str):
157
+ self.source_dir = source_dir
158
+ self.output_dir = output_dir
159
+ self.morphological_data: Dict[str, Dict] = {}
160
+ self.word_by_word_data: Dict[str, List[str]] = {}
161
+ self.translation_data: Dict[str, str] = {}
162
+ self.processed_verses = set()
163
+ self.processing_lock = Lock()
164
+ os.makedirs(output_dir, exist_ok=True)
165
+ os.makedirs(os.path.join(output_dir, 'json'), exist_ok=True)
166
+ os.makedirs(os.path.join(output_dir, 'txt'), exist_ok=True)
167
+ os.makedirs(os.path.join(output_dir, 'checkpoints'), exist_ok=True)
168
+ logger.info(f"Initialized processor with source dir: {source_dir}")
169
+
170
+ def load_source_files(self) -> bool:
171
+ """Loads morphological, translation, and word-by-word data from project root."""
172
+ try:
173
+ logger.info("Loading morphological data...")
174
+ morph_path = os.path.join(self.source_dir, 'quranic-corpus-morphology-0.4.txt')
175
+ with open(morph_path, 'r', encoding='utf-8') as f:
176
+ next(f)
177
+ for line in f:
178
+ if line.strip() and not line.startswith('#'):
179
+ parts = line.strip().split('\t')
180
+ if len(parts) >= 4:
181
+ location = parts[0].strip('()')
182
+ self.morphological_data[location] = {
183
+ 'form': parts[1],
184
+ 'tag': parts[2],
185
+ 'features': parts[3]
186
+ }
187
+ logger.info(f"Loaded {len(self.morphological_data)} morphological entries")
188
+ logger.info("Loading translation data...")
189
+ trans_path = os.path.join(self.source_dir, 'en.sample.quran-maududi.txt')
190
+ with open(trans_path, 'r', encoding='utf-8') as f:
191
+ next(f)
192
+ for line in f:
193
+ if line.strip():
194
+ parts = line.strip().split('|')
195
+ if len(parts) >= 3:
196
+ key = f"{parts[0]}:{parts[1]}"
197
+ self.translation_data[key] = parts[2].strip()
198
+ logger.info(f"Loaded {len(self.translation_data)} verse translations")
199
+ logger.info("Loading word-by-word data...")
200
+ word_path = os.path.join(self.source_dir, 'en.w4w.qurandev.txt')
201
+ with open(word_path, 'r', encoding='utf-8-sig') as f:
202
+ lines = [line.strip() for line in f if line.strip()]
203
+ sorted_keys = sorted(self.translation_data.keys(), key=lambda x: (int(x.split(':')[0]), int(x.split(':')[1])))
204
+ if len(lines) != len(sorted_keys):
205
+ logger.warning("Mismatch between word-by-word file and translation data")
206
+ for i, verse_key in enumerate(sorted_keys):
207
+ if i < len(lines):
208
+ words = [w.strip() for w in lines[i].split('|') if w.strip()]
209
+ self.word_by_word_data[verse_key] = words
210
+ logger.info(f"Loaded word-by-word data for {len(self.word_by_word_data)} verses")
211
+ return True
212
+ except Exception as e:
213
+ logger.error(f"Error loading source files: {str(e)}")
214
+ logger.error(traceback.format_exc())
215
+ return False
216
+
217
+ def process_verse(self, chapter: int, verse: int) -> Optional[VerseData]:
218
+ """Processes a single verse into structured format."""
219
+ try:
220
+ verse_ref = f"{chapter}:{verse}"
221
+ logger.info(f"Processing verse {verse_ref}")
222
+ translation = self.translation_data.get(verse_ref)
223
+ if not translation:
224
+ logger.warning(f"No translation for verse {verse_ref}")
225
+ return None
226
+ verse_word_list = self.word_by_word_data.get(verse_ref, [])
227
+ if not verse_word_list:
228
+ logger.warning(f"No word-by-word data for verse {verse_ref}")
229
+ return None
230
+ verse_words: List[WordAnalysis] = []
231
+ arabic_text = ""
232
+ for pos in range(1, len(verse_word_list) + 1):
233
+ pattern = f"{chapter}:{verse}:{pos}:"
234
+ matching_entries = [data for loc, data in self.morphological_data.items() if loc.startswith(pattern)]
235
+ if not matching_entries:
236
+ logger.debug(f"No morphological data for {pattern}")
237
+ continue
238
+ combined_form = " ".join(entry['form'] for entry in matching_entries)
239
+ combined_features = []
240
+ root = ""
241
+ for entry in matching_entries:
242
+ features = entry['features'].split('|')
243
+ combined_features.extend(features)
244
+ if not root:
245
+ for f in features:
246
+ if 'ROOT:' in f:
247
+ root = f.split('ROOT:')[1]
248
+ break
249
+ word_translation = verse_word_list[pos - 1]
250
+ word = WordAnalysis(
251
+ arabic=combined_form,
252
+ translation=word_translation,
253
+ position=str(pos),
254
+ morphology=matching_entries[0],
255
+ features=combined_features,
256
+ root=root,
257
+ location=f"{chapter}:{verse}:{pos}",
258
+ metadata={}
259
+ )
260
+ verse_words.append(word)
261
+ arabic_text += f" {combined_form}"
262
+ verse_data = VerseData(
263
+ chapter=chapter,
264
+ verse=verse,
265
+ arabic_text=arabic_text.strip(),
266
+ translation=translation,
267
+ words=verse_words,
268
+ metadata={
269
+ "processed_timestamp": datetime.now().isoformat(),
270
+ "word_count": len(verse_words)
271
+ }
272
+ )
273
+ self._save_verse_data(verse_data)
274
+ return verse_data
275
+ except Exception as e:
276
+ logger.error(f"Error processing verse {chapter}:{verse}: {str(e)}")
277
+ logger.error(traceback.format_exc())
278
+ return None
279
+
280
+ def _save_verse_data(self, verse_data: VerseData):
281
+ """Saves processed verse data as JSON and TXT."""
282
+ try:
283
+ verse_ref = f"{verse_data.chapter}:{verse_data.verse}"
284
+ json_path = os.path.join(self.output_dir, 'json', f'verse_{verse_ref.replace(":", "_")}.json')
285
+ with open(json_path, 'w', encoding='utf-8') as f:
286
+ json.dump(asdict(verse_data), f, ensure_ascii=False, indent=2)
287
+ txt_path = os.path.join(self.output_dir, 'txt', f'verse_{verse_ref.replace(":", "_")}.txt')
288
+ with open(txt_path, 'w', encoding='utf-8') as f:
289
+ f.write(f"=== Verse {verse_ref} ===\n\n")
290
+ f.write(f"Arabic Text:\n{verse_data.arabic_text}\n\n")
291
+ f.write(f"Translation:\n{verse_data.translation}\n\n")
292
+ f.write("Word Analysis:\n")
293
+ for i, word in enumerate(verse_data.words, 1):
294
+ f.write(f"\nWord {i}:\n")
295
+ f.write(f" Arabic: {word.arabic}\n")
296
+ f.write(f" Translation: {word.translation}\n")
297
+ f.write(f" Root: {word.root}\n")
298
+ f.write(" Features:\n")
299
+ for feature in word.features:
300
+ f.write(f" - {feature}\n")
301
+ f.write("\n")
302
+ logger.info(f"Saved verse data to {json_path} and {txt_path}")
303
+ except Exception as e:
304
+ logger.error(f"Error saving verse data: {str(e)}")
305
+ logger.error(traceback.format_exc())
306
+
307
+ class QuranicModelTrainer:
308
+ """Trains the Gemma-2-2b model on Quranic data using chunked incremental updates."""
309
+ def __init__(self,
310
+ model_name: str = "google/gemma-2-2b",
311
+ processed_data_dir: str = "processed_data",
312
+ checkpoint_dir: str = "checkpoints"):
313
+ self.processed_data_dir = processed_data_dir
314
+ self.checkpoint_dir = checkpoint_dir
315
+ self.device = "cpu" # Training on CPU; ZeroGPU will handle GPU access.
316
+ logger.info("Loading tokenizer and model...")
317
+
318
+ # Load tokenizer with additional special tokens and HF token from environment
319
+ self.tokenizer = AutoTokenizer.from_pretrained(
320
+ model_name,
321
+ token=os.environ.get("HF_TOKEN"),
322
+ additional_special_tokens=["[VERSE]", "[WORD]", "[ROOT]", "[FEATURES]"],
323
+ trust_remote_code=True
324
+ )
325
+
326
+ if self.tokenizer.pad_token is None:
327
+ self.tokenizer.add_special_tokens({"pad_token": "[PAD]"})
328
+
329
+ # Load model with fallback parameters if needed.
330
+ # Note: low_cpu_mem_usage=True requires Accelerate (>=0.26.0) to be installed.
331
+ try:
332
+ self.model = AutoModelForCausalLM.from_pretrained(
333
+ model_name,
334
+ token=os.environ.get("HF_TOKEN"),
335
+ torch_dtype=torch.float32,
336
+ low_cpu_mem_usage=True,
337
+ trust_remote_code=True,
338
+ attn_implementation="eager" # Use eager attention for Gemma2 models
339
+ )
340
+ except Exception as e:
341
+ logger.error(f"Error loading model directly: {str(e)}")
342
+ logger.info("Attempting to load with additional fallback parameters...")
343
+ from transformers import AutoConfig
344
+ config = AutoConfig.from_pretrained(
345
+ model_name,
346
+ token=os.environ.get("HF_TOKEN"),
347
+ trust_remote_code=True
348
+ )
349
+ self.model = AutoModelForCausalLM.from_pretrained(
350
+ model_name,
351
+ token=os.environ.get("HF_TOKEN"),
352
+ config=config,
353
+ torch_dtype=torch.float32,
354
+ low_cpu_mem_usage=True,
355
+ trust_remote_code=True,
356
+ revision="main",
357
+ attn_implementation="eager" # Also use eager attention here
358
+ )
359
+
360
+ # Resize token embeddings to match tokenizer vocabulary size
361
+ self.model.resize_token_embeddings(len(self.tokenizer))
362
+ self.model.train()
363
+ self.model.config.use_cache = False
364
+
365
+ if hasattr(self.model, "gradient_checkpointing_enable"):
366
+ self.model.gradient_checkpointing_enable()
367
+ else:
368
+ logger.warning("Gradient checkpointing not available for this model")
369
+
370
+ def prepare_training_data(self, chapter_data: List[Dict]) -> Dataset:
371
+ """Creates a QuranicDataset from processed chapter data."""
372
+ return QuranicDataset(chapter_data, self.tokenizer)
373
+
374
+ def train_chapter(self,
375
+ chapter_num: int,
376
+ processed_verses: List[Dict],
377
+ chunk_size: int = 10,
378
+ num_train_epochs: int = 10,
379
+ per_device_train_batch_size: int = 1,
380
+ learning_rate: float = 3e-5,
381
+ weight_decay: float = 0.01,
382
+ gradient_accumulation_steps: int = 64) -> bool:
383
+ """
384
+ Splits chapter data into chunks and trains incrementally to reduce memory usage.
385
+ """
386
+ try:
387
+ total_examples = len(processed_verses)
388
+ total_chunks = math.ceil(total_examples / chunk_size)
389
+ logger.info(f"Chapter {chapter_num}: {total_examples} examples, {total_chunks} chunks.")
390
+ for chunk_index in range(total_chunks):
391
+ chunk_data = processed_verses[chunk_index * chunk_size: (chunk_index + 1) * chunk_size]
392
+ dataset = self.prepare_training_data(chunk_data)
393
+ chunk_output_dir = os.path.join(self.checkpoint_dir, f"chapter_{chapter_num}", f"chunk_{chunk_index}")
394
+ os.makedirs(chunk_output_dir, exist_ok=True)
395
+ training_args = TrainingArguments(
396
+ output_dir=chunk_output_dir,
397
+ overwrite_output_dir=True,
398
+ num_train_epochs=num_train_epochs,
399
+ per_device_train_batch_size=per_device_train_batch_size,
400
+ learning_rate=learning_rate,
401
+ weight_decay=weight_decay,
402
+ gradient_accumulation_steps=gradient_accumulation_steps,
403
+ fp16=False,
404
+ remove_unused_columns=False,
405
+ logging_steps=50,
406
+ report_to="none",
407
+ evaluation_strategy="no",
408
+ no_cuda=True,
409
+ dataloader_num_workers=0,
410
+ dataloader_pin_memory=False
411
+ )
412
+ data_collator = DataCollatorForLanguageModeling(
413
+ tokenizer=self.tokenizer,
414
+ mlm=False
415
+ )
416
+ trainer = Trainer(
417
+ model=self.model,
418
+ args=training_args,
419
+ train_dataset=dataset,
420
+ tokenizer=self.tokenizer,
421
+ data_collator=data_collator
422
+ )
423
+ logger.info(f"Training chunk {chunk_index+1}/{total_chunks} for Chapter {chapter_num}...")
424
+ trainer.train()
425
+ trainer.save_model(chunk_output_dir)
426
+ del trainer, dataset
427
+ gc.collect()
428
+ manage_memory()
429
+ logger.info(f"Completed training for Chapter {chapter_num}")
430
+ return True
431
+ except Exception as e:
432
+ logger.error(f"Error training chapter {chapter_num}: {str(e)}")
433
+ logger.error(traceback.format_exc())
434
+ return False
435
+
436
+ class QuranicPipeline:
437
+ """Integrates data processing and incremental model training for all chapters."""
438
+ def __init__(self,
439
+ source_dir: str = ".",
440
+ working_dir: str = "working_directory",
441
+ start_chapter: int = 1,
442
+ end_chapter: int = 114):
443
+ self.source_dir = source_dir
444
+ self.working_dir = working_dir
445
+ self.start_chapter = start_chapter
446
+ self.end_chapter = end_chapter
447
+ self.setup_directories()
448
+ global logger
449
+ logger = logging.getLogger(__name__)
450
+ self.state = {
451
+ "last_processed_chapter": 0,
452
+ "last_trained_chapter": 0,
453
+ "current_state": "initialized",
454
+ "errors": [],
455
+ "start_time": datetime.now().isoformat()
456
+ }
457
+ self.load_state()
458
+ try:
459
+ logger.info("Initializing Quranic Data Processor...")
460
+ self.processor = QuranicDataProcessor(
461
+ source_dir=self.source_dir,
462
+ output_dir=os.path.join(self.working_dir, "processed_data")
463
+ )
464
+ logger.info("Initializing Quranic Model Trainer...")
465
+ self.trainer = QuranicModelTrainer(
466
+ model_name="google/gemma-2-2b",
467
+ processed_data_dir=os.path.join(self.working_dir, "processed_data"),
468
+ checkpoint_dir=os.path.join(self.working_dir, "checkpoints")
469
+ )
470
+ self.state["current_state"] = "ready"
471
+ self.save_state()
472
+ except Exception as e:
473
+ self.handle_error("Initialization failed", e)
474
+ raise
475
+
476
+ def setup_directories(self):
477
+ dirs = [
478
+ self.working_dir,
479
+ os.path.join(self.working_dir, "processed_data"),
480
+ os.path.join(self.working_dir, "checkpoints"),
481
+ os.path.join(self.working_dir, "logs"),
482
+ os.path.join(self.working_dir, "state")
483
+ ]
484
+ for d in dirs:
485
+ os.makedirs(d, exist_ok=True)
486
+
487
+ def load_state(self):
488
+ state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
489
+ if os.path.exists(state_file):
490
+ try:
491
+ with open(state_file, 'r') as f:
492
+ saved_state = json.load(f)
493
+ self.state.update(saved_state)
494
+ logger.info(f"Loaded previous state: Last processed chapter {self.state.get('last_processed_chapter')}, "
495
+ f"last trained chapter {self.state.get('last_trained_chapter')}")
496
+ except Exception as e:
497
+ logger.warning(f"Could not load previous state: {str(e)}")
498
+
499
+ def save_state(self):
500
+ state_file = os.path.join(self.working_dir, "state", "pipeline_state.json")
501
+ with open(state_file, 'w') as f:
502
+ json.dump(self.state, f, indent=2)
503
+
504
+ def handle_error(self, context: str, error: Exception):
505
+ error_detail = {
506
+ "timestamp": datetime.now().isoformat(),
507
+ "context": context,
508
+ "error": str(error),
509
+ "traceback": traceback.format_exc()
510
+ }
511
+ self.state.setdefault("errors", []).append(error_detail)
512
+ logger.error(f"{context}: {str(error)}")
513
+ self.save_state()
514
+
515
+ def run_pipeline(self):
516
+ """Runs processing and training for chapters sequentially, then saves the final model."""
517
+ logger.info("Starting pipeline execution")
518
+ try:
519
+ if not self.processor.load_source_files():
520
+ raise Exception("Failed to load source files")
521
+ for chapter in range(self.start_chapter, self.end_chapter + 1):
522
+ logger.info(f"=== Processing Chapter {chapter} ===")
523
+ processed_chapter_data = []
524
+ verse = 1
525
+ while True:
526
+ verse_data = self.processor.process_verse(chapter, verse)
527
+ if verse_data is None:
528
+ break
529
+ processed_chapter_data.append(asdict(verse_data))
530
+ verse += 1
531
+ if processed_chapter_data:
532
+ success = self.trainer.train_chapter(chapter, processed_chapter_data)
533
+ if not success:
534
+ logger.error(f"Training failed for Chapter {chapter}. Stopping pipeline.")
535
+ break
536
+ self.state["last_trained_chapter"] = chapter
537
+ self.save_state()
538
+ else:
539
+ logger.warning(f"No processed data for Chapter {chapter}")
540
+ self.state["last_processed_chapter"] = chapter
541
+ self.save_state()
542
+ manage_memory()
543
+ logger.info("Pipeline execution completed")
544
+ # Save the final model and tokenizer after all training is complete.
545
+ final_model_dir = os.path.join(self.working_dir, "final_model")
546
+ os.makedirs(final_model_dir, exist_ok=True)
547
+ self.trainer.model.save_pretrained(final_model_dir)
548
+ self.trainer.tokenizer.save_pretrained(final_model_dir)
549
+ logger.info(f"Final model saved to {final_model_dir}")
550
+ except Exception as e:
551
+ self.handle_error("Pipeline execution failed", e)
552
+ raise
553
+
554
+ @spaces.GPU() # Request ZeroGPU hardware for the Space
555
+ def start_pipeline():
556
+ try:
557
+ logger.info("Starting Quranic Training Pipeline with Gemma-2-2b")
558
+ logger.info(f"PyTorch version: {torch.__version__}")
559
+ logger.info(f"CUDA available: {torch.cuda.is_available()}")
560
+ if torch.cuda.is_available():
561
+ logger.info(f"CUDA device count: {torch.cuda.device_count()}")
562
+ logger.info(f"CUDA device name: {torch.cuda.get_device_name(0)}")
563
+
564
+ if not os.environ.get("HF_TOKEN"):
565
+ logger.warning("HF_TOKEN environment variable not set. Model loading may fail.")
566
+
567
+ required_files = [
568
+ 'quranic-corpus-morphology-0.4.txt',
569
+ 'en.sample.quran-maududi.txt',
570
+ 'en.w4w.qurandev.txt'
571
+ ]
572
+ missing_files = [f for f in required_files if not os.path.exists(f)]
573
+ if missing_files:
574
+ return f"Missing required data files: {', '.join(missing_files)}"
575
+
576
+ pipeline = QuranicPipeline(
577
+ source_dir=".",
578
+ working_dir="working_directory",
579
+ start_chapter=1,
580
+ end_chapter=114
581
+ )
582
+ pipeline.run_pipeline()
583
+ return "Pipeline execution completed successfully."
584
+ except Exception as e:
585
+ error_msg = f"Pipeline execution failed: {str(e)}\n{traceback.format_exc()}"
586
+ logger.error(error_msg)
587
+ return error_msg
588
+
589
+ iface = gr.Interface(
590
+ fn=start_pipeline,
591
+ inputs=[],
592
+ outputs=gr.Textbox(label="Pipeline Status", lines=10),
593
+ title="Quranic Training Pipeline for Gemma-2-2b",
594
+ description="""This pipeline fine-tunes Google's Gemma-2-2b model on Quranic data.
595
+
596
+ Click 'Submit' to trigger the Quranic data processing and training pipeline on ZeroGPU.
597
+
598
+ Requirements:
599
+ - Transformers (>=4.42.0)
600
+ - Gradio (>=5.12.0)
601
+ - PyTorch (==2.2.2)
602
+ - psutil (==5.9.5)
603
+ - Accelerate (>=0.26.0)
604
+
605
+ The pipeline processes all 114 chapters of the Quran sequentially, with memory management optimizations for ZeroGPU environments."""
606
+ )
607
+
608
+ if __name__ == "__main__":
609
+ iface.launch()