Diksha2001 commited on
Commit
b69431f
1 Parent(s): be3b9e4

Update Finetuning_Pipeline.py

Browse files
Files changed (1) hide show
  1. Finetuning_Pipeline.py +589 -589
Finetuning_Pipeline.py CHANGED
@@ -1,589 +1,589 @@
1
- # the code is structured to automate the process of extracting text from PDF documents,
2
- # generating question-answer pairs from that text,
3
- # fine-tuning a language model based on the generated data, and evaluating the model's performance.
4
- # The use of caching, error handling, and logging improves the robustness and maintainability of the script, making it suitable for practical applications in natural language processing and machine learning.
5
-
6
- import json
7
- import re
8
- import PyPDF2
9
- import time
10
- from openai import OpenAI
11
- import fitz # PyMuPDF
12
- import pytesseract
13
- from PIL import Image
14
- import io
15
- import os
16
- from pathlib import Path
17
- # We have to check which Torch version for Xformers (2.3 -> 0.0.27)
18
- from torch import __version__; from packaging.version import Version as V
19
- from unsloth import FastLanguageModel
20
- import torch
21
- import json
22
- from datasets import load_dataset
23
- from unsloth.chat_templates import get_chat_template
24
- from trl import SFTTrainer
25
- from transformers import TrainingArguments, TrainerCallback
26
- from unsloth import is_bfloat16_supported
27
- import gc
28
- import logging
29
- import sys
30
- import subprocess
31
- import requests
32
- # Set the GLOO_SOCKET_IFNAME environment variable
33
- os.environ["GLOO_SOCKET_IFNAME"] = "lo"
34
-
35
- # Configure logging
36
- # logging.basicConfig(level=logging.INFO)
37
- # input_data = json.loads(sys.argv[1])
38
-
39
- # # Process the data (example: just print it here)
40
- # response = f"Received data: {input_data}"
41
- def wait_for_server(max_attempts=60):
42
- """Wait for the vLLM server to become available."""
43
- url = "http://localhost:8000/health"
44
- for attempt in range(max_attempts):
45
- try:
46
- response = requests.get(url)
47
- if response.status_code == 200:
48
- logging.info("vLLM server is ready!")
49
- return True
50
- except requests.exceptions.RequestException as e:
51
- logging.info(f"Server not ready yet: {e}. Retrying in {2**attempt} seconds...")
52
- time.sleep(2**attempt)
53
-
54
-
55
- def log_output(pipe, log_func):
56
- """Helper function to log output from a subprocess pipe."""
57
- for line in iter(pipe.readline, ''):
58
- log_func(line.strip())
59
-
60
- def start_vllm_server(model_name):
61
- cmd = [
62
- "vllm",
63
- "serve",
64
- "hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4",
65
- "--gpu_memory_utilization=0.80",
66
- "--max_model_len=4096",
67
- "--enable-chunked-prefill=False",
68
- "--num_scheduler_steps=2"
69
- ]
70
-
71
- logging.info(f"Starting vLLM server with command: {' '.join(cmd)}")
72
-
73
- # Start the server subprocess
74
- server_process = subprocess.Popen(
75
- cmd,
76
- stdout=subprocess.PIPE,
77
- stderr=subprocess.PIPE,
78
- text=True,
79
- bufsize=1
80
- )
81
-
82
- # # Use threads to handle stdout and stderr in real-time
83
- # threading.Thread(target=log_output, args=(server_process.stdout, logging.info), daemon=True).start()
84
- # threading.Thread(target=log_output, args=(server_process.stderr, logging.error), daemon=True).start()
85
-
86
- # Wait for the server to become ready
87
- if not wait_for_server():
88
- server_process.terminate()
89
- raise Exception("Server failed to start in time.")
90
-
91
- return server_process
92
-
93
-
94
- try:
95
- # Validate that we have an argument
96
- if len(sys.argv) < 2:
97
- raise ValueError("No input JSON provided")
98
-
99
- # Parse the JSON input from command line argument
100
- input_data = json.loads(sys.argv[1])
101
-
102
- # Validate required fields
103
- required_fields = ['pdf_file', 'system_prompt', 'model_name', 'max_step', 'learning_rate', 'epochs']
104
- missing_fields = [field for field in required_fields if field not in input_data]
105
- if missing_fields:
106
- raise ValueError(f"Missing required fields: {', '.join(missing_fields)}")
107
-
108
- # Your existing pipeline code here
109
- # Access the fields from input_data dictionary:
110
- pdf_file = input_data['pdf_file']
111
- system_prompt = input_data['system_prompt']
112
- model_name = input_data['model_name']
113
- max_step = input_data['max_step']
114
- learning_rate = input_data['learning_rate']
115
- epochs = input_data['epochs']
116
-
117
- # Rest of your pipeline implementation...
118
-
119
- except json.JSONDecodeError as e:
120
- logging.error(f"Invalid JSON input: {str(e)}")
121
- sys.exit(1)
122
- except ValueError as e:
123
- logging.error(str(e))
124
- sys.exit(1)
125
- except Exception as e:
126
- logging.error(f"Pipeline error: {str(e)}")
127
- sys.exit(1)
128
- # Initialize the OpenAI Client with your RunPod API Key and Endpoint URL
129
-
130
- def get_cache_filename(pdf_path):
131
- pdf_stat = os.stat(pdf_path)
132
- pdf_modified_time = pdf_stat.st_mtime
133
- base_name = Path(pdf_path).stem
134
- cache_filename = f"{base_name}_{pdf_modified_time}.txt"
135
- cache_dir = "pdf_cache"
136
- return os.path.join(cache_dir, cache_filename)
137
-
138
- def save_text_cache(cache_path, text_pages):
139
- os.makedirs(os.path.dirname(cache_path), exist_ok=True)
140
- with open(cache_path, 'w', encoding='utf-8') as f:
141
- json.dump(text_pages, f, ensure_ascii=False, indent=2)
142
-
143
- def load_text_cache(cache_path):
144
- try:
145
- with open(cache_path, 'r', encoding='utf-8') as f:
146
- return json.load(f)
147
- except (FileNotFoundError, json.JSONDecodeError):
148
- return None
149
-
150
- def extract_pdf_text_by_page(pdf_path):
151
- cache_path = get_cache_filename(pdf_path)
152
- cached_text = load_text_cache(cache_path)
153
-
154
- if cached_text is not None:
155
- logging.info(f"Loading text from cache: {cache_path}")
156
- return cached_text
157
-
158
- logging.info("Cache not found, extracting text from PDF.")
159
- pdf_text_pages = []
160
-
161
- try:
162
- with open(pdf_path, "rb") as pdf_file:
163
- pdf_reader = PyPDF2.PdfReader(pdf_file)
164
- total_pages = len(pdf_reader.pages)
165
-
166
- for page_num in range(total_pages):
167
- page = pdf_reader.pages[page_num]
168
- page_text = page.extract_text() or ""
169
-
170
- if not page_text.strip():
171
- pdf_doc = fitz.open(pdf_path)
172
- pdf_page = pdf_doc.load_page(page_num)
173
- image_list = pdf_page.get_images(full=True)
174
-
175
- if image_list:
176
- for img in image_list:
177
- xref = img[0]
178
- base_image = pdf_doc.extract_image(xref)
179
- image_bytes = base_image["image"]
180
- image = Image.open(io.BytesIO(image_bytes))
181
- ocr_text = pytesseract.image_to_string(image)
182
- page_text += ocr_text.strip()
183
-
184
- pdf_doc.close()
185
- pdf_text_pages.append(page_text.strip() if page_text else "")
186
- save_text_cache(cache_path, pdf_text_pages)
187
- except Exception as e:
188
- print(f"Error extracting PDF text: {str(e)}")
189
-
190
- return pdf_text_pages or []
191
-
192
-
193
- def clean_json_response(response):
194
- """
195
- Attempt to extract a valid JSON array from a response, even if it is incomplete or contains unterminated strings.
196
- """
197
- response_str = "\n".join(response) if isinstance(response, list) else response
198
- response_str = response_str.replace("```json", "").replace("```", "").strip()
199
-
200
- # Search for a JSON array pattern using regex, even if it’s incomplete
201
- json_array_match = re.search(r'(\[.*?\])', response_str, re.DOTALL)
202
-
203
- # Attempt to parse as JSON and handle unterminated strings by retrying with a trimmed response
204
- if json_array_match:
205
- json_str = json_array_match.group(1)
206
-
207
- try:
208
- json_data = json.loads(json_str)
209
- return json_str # Return valid JSON if successful
210
-
211
- except json.JSONDecodeError as e:
212
- # If error is due to unterminated strings or missing brackets, try trimming and re-validating
213
- print(f"JSON extraction failed: {e}")
214
- # Try a progressive trim of the response
215
- for i in range(len(json_str), 0, -10):
216
- try:
217
- trimmed_json_str = json_str[:i] + "]" # Ensure it ends with a closing bracket
218
- json_data = json.loads(trimmed_json_str)
219
- return trimmed_json_str
220
- except json.JSONDecodeError:
221
- continue # Keep trimming until valid or no more retries
222
-
223
- print("JSON extraction failed: Incomplete or malformed response.")
224
- return "" # Return empty string if parsing fails
225
-
226
- def generate_qa_from_chunk(text_chunk, retries=2, max_tokens=2500):
227
- """
228
- Generate QA pairs based on a text chunk, with JSON validation, chunk splitting, and retry logic.
229
- """
230
- if not text_chunk.strip():
231
- return "" # Return empty if the chunk is blank
232
-
233
- if len(text_chunk) > max_tokens:
234
- # Recursively split chunk into smaller sections if it exceeds max token limit
235
- half = len(text_chunk) // 2
236
- return generate_qa_from_chunk(text_chunk[:half], retries) + \
237
- generate_qa_from_chunk(text_chunk[half:], retries)
238
- prompt = f"""You are an AI assistant tasked with generating informative question-answer pairs from text-based documents.
239
-
240
- INPUT CONTEXT:
241
- {text_chunk}
242
-
243
- TASK:
244
- Generate relevant question-answer pairs from the provided text. Each pair must:
245
- 1. Be directly based on the information in the text
246
- 2. Include a clear, specific question
247
- 3. Provide an accurate, complete response
248
- 4. Follow the exact JSON format specified below
249
-
250
- OUTPUT FORMAT REQUIREMENTS:
251
- 1. Respond ONLY with a JSON array
252
- 2. Each object must contain exactly two fields:
253
- - "prompt": the question
254
- - "response": the complete answer
255
- 3. Include no text outside the JSON array
256
- 4. Follow this exact structure:
257
-
258
- [
259
- {{
260
- "prompt": "What is the daily allowance for a Subedar on domestic travel?",
261
- "response": "A Subedar is entitled to a daily allowance of Rupees 600 for domestic travel. This allowance covers meals and minor incidental expenses."
262
- }},
263
- {{
264
- "prompt": "How much reimbursement can be claimed for travel by train for a Lieutenant Colonel?",
265
- "response": "A Lieutenant Colonel is entitled to AC 1st class travel by train. The full fare for AC 1st class is reimbursed, provided the journey is undertaken for official purposes and valid tickets are submitted."
266
- }},
267
- {{
268
- "prompt": "What is the limit for claiming hotel accommodation reimbursement for a Havildar?",
269
- "response": "A Havildar can claim up to Rupees 2,500 per night for hotel accommodations during official travel, subject to submission of valid receipts and adherence to the approved lodging limits."
270
- }}
271
- ]
272
-
273
- Generate the QA pairs now, following the exact format shown above."""
274
-
275
- attempt = 0
276
- while attempt < retries:
277
- try:
278
- """Query the vLLM server with retries."""
279
- url = "http://localhost:8000/v1/chat/completions"
280
- headers = {"Content-Type": "application/json"}
281
- data = {
282
- "model": f"hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4",
283
- "messages": [
284
- {"role": "system", "content": "You are a helpful assistant."},
285
- {"role": "user", "content": prompt}
286
- ]
287
- }
288
- response = requests.post(url, headers=headers, json=data, timeout=300)
289
- if response and response.choices:
290
- response_text = response.choices[0].message.content.strip()
291
-
292
- # Use improved JSON validation with trimming for incomplete responses
293
- json_str = clean_json_response(response_text)
294
- if json_str:
295
- return json_str
296
- else:
297
- print("JSON response incomplete, retrying with split chunks.")
298
- half = len(text_chunk) // 2
299
- return generate_qa_from_chunk(text_chunk[:half], retries) + \
300
- generate_qa_from_chunk(text_chunk[half:], retries)
301
-
302
- except Exception as e:
303
- print(f"Attempt {attempt + 1} failed: {e}")
304
- attempt += 1
305
- time.sleep(5) # Delay before retrying
306
-
307
- print("All attempts failed for this chunk.")
308
- return ""
309
-
310
-
311
- def process_pdf_file_by_pages(pdf_path, output_json_file, pages_per_chunk=4, overlap=1):
312
- pdf_text_pages = extract_pdf_text_by_page(pdf_path)
313
- chunks = [' '.join(pdf_text_pages[i:i + pages_per_chunk])
314
- for i in range(0, len(pdf_text_pages) - pages_per_chunk + 1, pages_per_chunk - overlap)]
315
-
316
- print(f"Total chunks to process: {len(chunks)}")
317
- all_qa_pairs = []
318
-
319
- for idx, chunk in enumerate(chunks):
320
- print(f"Processing chunk {idx + 1}...")
321
- try:
322
- qa_pairs = generate_qa_from_chunk(chunk)
323
-
324
- if not qa_pairs:
325
- print(f"No QA pairs generated for chunk {idx + 1}")
326
- continue
327
-
328
- qa_pairs_cleaned = clean_json_response(qa_pairs)
329
- if not qa_pairs_cleaned:
330
- print(f"Failed to clean JSON for chunk {idx + 1}")
331
- continue
332
-
333
- try:
334
- qa_pairs_json = json.loads(qa_pairs_cleaned)
335
- all_qa_pairs.extend(qa_pairs_json)
336
- print(f"Chunk {idx + 1} processed successfully.")
337
- except json.JSONDecodeError as e:
338
- print(f"JSON decoding error for chunk {idx + 1}: {e}")
339
- print(f"Raw cleaned response: {qa_pairs_cleaned}")
340
-
341
- except Exception as e:
342
- print(f"Error processing chunk {idx + 1}: {e}")
343
-
344
- if all_qa_pairs:
345
- with open(output_json_file, 'w', encoding='utf-8') as json_file:
346
- json.dump(all_qa_pairs, json_file, ensure_ascii=False, indent=4)
347
- print(f"QA pairs saved to {output_json_file}")
348
- else:
349
- print("No QA pairs were successfully processed.")
350
-
351
-
352
- # pdf_path = "/home/ubuntu/Diksha/finetuning_1/Finetuning_Complete/Dockerization/TravelEnglish 1.pdf"
353
- pdf_file=input_data["pdf_file"]
354
-
355
-
356
- output_json_file = 'output_json.json'
357
- process_pdf_file_by_pages(pdf_file, output_json_file)
358
- print(f"QA pairs saved to {output_json_file}")
359
-
360
- #Here Starts the Finetuning Process
361
-
362
- max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
363
- dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
364
- load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
365
-
366
-
367
- model, tokenizer = FastLanguageModel.from_pretrained(
368
- model_name = "unsloth/Meta-Llama-3.1-8B-bnb-4bit",
369
- max_seq_length = max_seq_length,
370
- dtype = dtype,
371
- load_in_4bit = load_in_4bit,
372
- )
373
-
374
- model = FastLanguageModel.get_peft_model(
375
- model,
376
- r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
377
- target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
378
- "gate_proj", "up_proj", "down_proj",],
379
- lora_alpha = 16,
380
- lora_dropout = 0, # Supports any, but = 0 is optimized
381
- bias = "none", # Supports any, but = "none" is optimized
382
- # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
383
- use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
384
- random_state = 3407,
385
- use_rslora = False, # We support rank stabilized LoRA
386
- loftq_config = None, # And LoftQ
387
- )
388
-
389
-
390
- def load_data_from_json(file_path):
391
- return load_dataset('json', data_files=file_path)['train']
392
-
393
-
394
- tokenizer = get_chat_template(
395
- tokenizer,
396
- chat_template="chatml", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
397
- mapping={"role": "from", "content": "value", "user": "human", "assistant": "gpt"}, # ShareGPT style
398
- map_eos_token=True, # Maps <|im_end|> to </s> instead
399
- )
400
-
401
- system_prompt=input_data["system_prompt"]
402
-
403
- def formatting_prompts_func(examples):
404
- prompts = examples['prompt']
405
- responses = examples['response']
406
-
407
- text = []
408
-
409
- for prompt, response in zip(prompts, responses):
410
- prompt = str(prompt).strip()
411
- response = str(response).strip()
412
-
413
- # Ensure punctuation for the prompt
414
- if not prompt.endswith(('?', '.', '!', ':')):
415
- prompt += '.'
416
-
417
- # Capitalize the response and ensure punctuation
418
- response = response.capitalize()
419
- if not response.endswith(('.', '?', '!')):
420
- response += '.'
421
-
422
- # Create conversation in dictionary format, including the system prompt
423
- convo = [
424
- {'from': 'system', 'value': system_prompt},
425
- {'from': 'human', 'value': prompt},
426
- {'from': 'gpt', 'value': response}
427
- ]
428
-
429
- # Apply tokenizer's chat template to format each conversation
430
- text.append(tokenizer.apply_chat_template(convo, tokenize=False, add_generation_prompt=False))
431
-
432
- return {"text": text} # Return the formatted text
433
-
434
- # Load your JSON file
435
-
436
- dataset = load_data_from_json(output_json_file)
437
-
438
- # Apply the formatting function to the dataset to create the 'text' column
439
- dataset = dataset.map(formatting_prompts_func, batched=True) # This line is crucial to add the 'text' column
440
-
441
- # Print a sample to verify the formatting
442
- print(dataset["text"][0])
443
-
444
-
445
-
446
- class TrackBestModelCallback(TrainerCallback):
447
-
448
- def __init__(self, output_dir):
449
- super().__init__()
450
- self.best_loss = float('inf')
451
- self.best_step = 0
452
- self.output_dir = output_dir
453
- os.makedirs(self.output_dir, exist_ok=True)
454
-
455
-
456
-
457
- def on_log(self, args, state, control, logs=None, **kwargs):
458
- train_loss = logs.get("loss")
459
- if train_loss is not None and train_loss < self.best_loss:
460
- self.best_loss = train_loss
461
- self.best_step = state.global_step
462
-
463
- # Save the model to disk
464
- model_path = os.path.join(self.output_dir, f"best_model_step_{self.best_step}.pt")
465
- torch.save(kwargs['model'].state_dict(), model_path)
466
- print(f"New best model saved at {model_path} with loss: {self.best_loss}")
467
-
468
- # Remove the previous best model if it exists
469
-
470
- for file in os.listdir(self.output_dir):
471
- if file.startswith("best_model_step_") and file != f"best_model_step_{self.best_step}.pt":
472
- os.remove(os.path.join(self.output_dir, file))
473
-
474
- def on_train_end(self, args, state, control, **kwargs):
475
- print("Training ended. Best model is saved on disk.")
476
-
477
- trainer = SFTTrainer(
478
- model=model,
479
- tokenizer=tokenizer,
480
- train_dataset=dataset,
481
- dataset_text_field="text",
482
- max_seq_length=max_seq_length,
483
- dataset_num_proc=4, # Reduced to balance between speed and CPU usage
484
- packing=False, # Re-enabled packing for efficiency
485
- args=TrainingArguments(
486
- per_device_train_batch_size=4, # Reduced to improve speed
487
- gradient_accumulation_steps=2, # Reduced to increase update frequency
488
- warmup_steps=100, # Reduced warmup steps
489
- num_train_epochs=epochs,
490
- max_steps=max_step,
491
- learning_rate=learning_rate, # Slightly reduced for stability with smaller batch size
492
- fp16=not is_bfloat16_supported(),
493
- bf16=is_bfloat16_supported(),
494
- logging_steps=50,
495
- optim="adamw_8bit",
496
- weight_decay=0.01,
497
- lr_scheduler_type="cosine",
498
- seed=3407,
499
- output_dir="outputs",
500
- max_grad_norm=1.0,
501
- dataloader_num_workers=4, # Adjusted to match dataset_num_proc
502
- gradient_checkpointing=True, # Re-enabled to save memory
503
- adam_beta1=0.9,
504
- adam_beta2=0.999,
505
- adam_epsilon=1e-8,
506
- ddp_find_unused_parameters=False,
507
- report_to="none", # Disable wandb logging if you're not using it
508
- ),
509
-
510
- )
511
-
512
-
513
- #@title Show current memory stats
514
-
515
- gpu_stats = torch.cuda.get_device_properties(0)
516
- start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
517
- max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
518
- print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
519
- print(f"{start_gpu_memory} GB of memory reserved.")
520
-
521
-
522
- # In your training script:
523
-
524
- output_dir = "outputs"
525
- best_model_tracker = TrackBestModelCallback(output_dir)
526
- trainer.add_callback(best_model_tracker)
527
-
528
-
529
-
530
- # Start training
531
-
532
- trainer_stats = trainer.train()
533
- print("Training completed.")
534
- print(f"Best loss: {best_model_tracker.best_loss} at step {best_model_tracker.best_step}")
535
- print("Final training loss:", trainer_stats.training_loss)
536
-
537
-
538
- #@title Show final memory and time stats
539
-
540
- used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
541
- used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
542
- used_percentage = round(used_memory /max_memory*100, 3)
543
- lora_percentage = round(used_memory_for_lora/max_memory*100, 3)
544
- print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
545
- print(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
546
- print(f"Peak reserved memory = {used_memory} GB.")
547
- print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
548
- print(f"Peak reserved memory % of max memory = {used_percentage} %.")
549
- print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
550
-
551
- # Saving the model for VLLM
552
- # Function to save and push model in different formats
553
- def save_and_push_model(format, save_method, model_name):
554
- try:
555
- model.save_pretrained_merged("model", tokenizer, save_method=save_method)
556
- model.push_to_hub_merged(f"PharynxAI/{model_name}", tokenizer, save_method=save_method, private=True, token=os.getenv('HF_Token'))
557
- print(f"Successfully saved and pushed model in {format} format.")
558
- except Exception as e:
559
- print(f"Error while saving or pushing model in {format} format: {e}")
560
- if __name__ == "__main__":
561
-
562
- server_process = None
563
-
564
- try:
565
- # # Start vLLM server
566
- server_process = start_vllm_server("hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4")
567
-
568
- except Exception as e:
569
- logging.error(f"An error occurred: {e}")
570
- sys.exit(1)
571
-
572
- finally:
573
- # Cleanup: terminate the server process if it exists
574
- if server_process:
575
- logging.info("Shutting down vLLM server...")
576
- server_process.terminate()
577
- try:
578
- server_process.wait(timeout=5)
579
- except subprocess.TimeoutExpired:
580
- logging.warning("Server didn't terminate gracefully, forcing kill...")
581
- server_process.kill()
582
- server_process.wait()
583
- logging.info("Server shutdown complete")
584
-
585
- # Assuming input_data is defined and contains 'model_name'
586
- save_and_push_model("16bit", "merged_16bit", input_data['model_name'])
587
- save_and_push_model("4bit", "merged_4bit", input_data['model_name'])
588
- save_and_push_model("LoRA adapters", "lora", input_data['model_name'])
589
-
 
1
+ # the code is structured to automate the process of extracting text from PDF documents,
2
+ # generating question-answer pairs from that text,
3
+ # fine-tuning a language model based on the generated data, and evaluating the model's performance.
4
+ # The use of caching, error handling, and logging improves the robustness and maintainability of the script, making it suitable for practical applications in natural language processing and machine learning.
5
+
6
+ import json
7
+ import re
8
+ import PyPDF2
9
+ import time
10
+ from openai import OpenAI
11
+ import fitz # PyMuPDF
12
+ import pytesseract
13
+ from PIL import Image
14
+ import io
15
+ import os
16
+ from pathlib import Path
17
+ # We have to check which Torch version for Xformers (2.3 -> 0.0.27)
18
+ from torch import __version__; from packaging.version import Version as V
19
+ from unsloth import FastLanguageModel
20
+ import torch
21
+ import json
22
+ from datasets import load_dataset
23
+ from unsloth.chat_templates import get_chat_template
24
+ from trl import SFTTrainer
25
+ from transformers import TrainingArguments, TrainerCallback
26
+ from unsloth import is_bfloat16_supported
27
+ import gc
28
+ import logging
29
+ import sys
30
+ import subprocess
31
+ import requests
32
+ # Set the GLOO_SOCKET_IFNAME environment variable
33
+ os.environ["GLOO_SOCKET_IFNAME"] = "lo"
34
+
35
+ # Configure logging
36
+ # logging.basicConfig(level=logging.INFO)
37
+ # input_data = json.loads(sys.argv[1])
38
+
39
+ # # Process the data (example: just print it here)
40
+ # response = f"Received data: {input_data}"
41
+ def wait_for_server(max_attempts=60):
42
+ """Wait for the vLLM server to become available."""
43
+ url = "http://localhost:8000/health"
44
+ for attempt in range(max_attempts):
45
+ try:
46
+ response = requests.get(url)
47
+ if response.status_code == 200:
48
+ logging.info("vLLM server is ready!")
49
+ return True
50
+ except requests.exceptions.RequestException as e:
51
+ logging.info(f"Server not ready yet: {e}. Retrying in {2**attempt} seconds...")
52
+ time.sleep(2**attempt)
53
+
54
+
55
+ def log_output(pipe, log_func):
56
+ """Helper function to log output from a subprocess pipe."""
57
+ for line in iter(pipe.readline, ''):
58
+ log_func(line.strip())
59
+
60
+ def start_vllm_server(model_name):
61
+ cmd = [
62
+ "vllm",
63
+ "serve",
64
+ "hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4",
65
+ "--gpu_memory_utilization=0.98",
66
+ "--max_model_len=4096",
67
+ "--enable-chunked-prefill=False",
68
+ "--num_scheduler_steps=2"
69
+ ]
70
+
71
+ logging.info(f"Starting vLLM server with command: {' '.join(cmd)}")
72
+
73
+ # Start the server subprocess
74
+ server_process = subprocess.Popen(
75
+ cmd,
76
+ stdout=subprocess.PIPE,
77
+ stderr=subprocess.PIPE,
78
+ text=True,
79
+ bufsize=1
80
+ )
81
+
82
+ # # Use threads to handle stdout and stderr in real-time
83
+ # threading.Thread(target=log_output, args=(server_process.stdout, logging.info), daemon=True).start()
84
+ # threading.Thread(target=log_output, args=(server_process.stderr, logging.error), daemon=True).start()
85
+
86
+ # Wait for the server to become ready
87
+ if not wait_for_server():
88
+ server_process.terminate()
89
+ raise Exception("Server failed to start in time.")
90
+
91
+ return server_process
92
+
93
+
94
+ try:
95
+ # Validate that we have an argument
96
+ if len(sys.argv) < 2:
97
+ raise ValueError("No input JSON provided")
98
+
99
+ # Parse the JSON input from command line argument
100
+ input_data = json.loads(sys.argv[1])
101
+
102
+ # Validate required fields
103
+ required_fields = ['pdf_file', 'system_prompt', 'model_name', 'max_step', 'learning_rate', 'epochs']
104
+ missing_fields = [field for field in required_fields if field not in input_data]
105
+ if missing_fields:
106
+ raise ValueError(f"Missing required fields: {', '.join(missing_fields)}")
107
+
108
+ # Your existing pipeline code here
109
+ # Access the fields from input_data dictionary:
110
+ pdf_file = input_data['pdf_file']
111
+ system_prompt = input_data['system_prompt']
112
+ model_name = input_data['model_name']
113
+ max_step = input_data['max_step']
114
+ learning_rate = input_data['learning_rate']
115
+ epochs = input_data['epochs']
116
+
117
+ # Rest of your pipeline implementation...
118
+
119
+ except json.JSONDecodeError as e:
120
+ logging.error(f"Invalid JSON input: {str(e)}")
121
+ sys.exit(1)
122
+ except ValueError as e:
123
+ logging.error(str(e))
124
+ sys.exit(1)
125
+ except Exception as e:
126
+ logging.error(f"Pipeline error: {str(e)}")
127
+ sys.exit(1)
128
+ # Initialize the OpenAI Client with your RunPod API Key and Endpoint URL
129
+
130
+ def get_cache_filename(pdf_path):
131
+ pdf_stat = os.stat(pdf_path)
132
+ pdf_modified_time = pdf_stat.st_mtime
133
+ base_name = Path(pdf_path).stem
134
+ cache_filename = f"{base_name}_{pdf_modified_time}.txt"
135
+ cache_dir = "pdf_cache"
136
+ return os.path.join(cache_dir, cache_filename)
137
+
138
+ def save_text_cache(cache_path, text_pages):
139
+ os.makedirs(os.path.dirname(cache_path), exist_ok=True)
140
+ with open(cache_path, 'w', encoding='utf-8') as f:
141
+ json.dump(text_pages, f, ensure_ascii=False, indent=2)
142
+
143
+ def load_text_cache(cache_path):
144
+ try:
145
+ with open(cache_path, 'r', encoding='utf-8') as f:
146
+ return json.load(f)
147
+ except (FileNotFoundError, json.JSONDecodeError):
148
+ return None
149
+
150
+ def extract_pdf_text_by_page(pdf_path):
151
+ cache_path = get_cache_filename(pdf_path)
152
+ cached_text = load_text_cache(cache_path)
153
+
154
+ if cached_text is not None:
155
+ logging.info(f"Loading text from cache: {cache_path}")
156
+ return cached_text
157
+
158
+ logging.info("Cache not found, extracting text from PDF.")
159
+ pdf_text_pages = []
160
+
161
+ try:
162
+ with open(pdf_path, "rb") as pdf_file:
163
+ pdf_reader = PyPDF2.PdfReader(pdf_file)
164
+ total_pages = len(pdf_reader.pages)
165
+
166
+ for page_num in range(total_pages):
167
+ page = pdf_reader.pages[page_num]
168
+ page_text = page.extract_text() or ""
169
+
170
+ if not page_text.strip():
171
+ pdf_doc = fitz.open(pdf_path)
172
+ pdf_page = pdf_doc.load_page(page_num)
173
+ image_list = pdf_page.get_images(full=True)
174
+
175
+ if image_list:
176
+ for img in image_list:
177
+ xref = img[0]
178
+ base_image = pdf_doc.extract_image(xref)
179
+ image_bytes = base_image["image"]
180
+ image = Image.open(io.BytesIO(image_bytes))
181
+ ocr_text = pytesseract.image_to_string(image)
182
+ page_text += ocr_text.strip()
183
+
184
+ pdf_doc.close()
185
+ pdf_text_pages.append(page_text.strip() if page_text else "")
186
+ save_text_cache(cache_path, pdf_text_pages)
187
+ except Exception as e:
188
+ print(f"Error extracting PDF text: {str(e)}")
189
+
190
+ return pdf_text_pages or []
191
+
192
+
193
+ def clean_json_response(response):
194
+ """
195
+ Attempt to extract a valid JSON array from a response, even if it is incomplete or contains unterminated strings.
196
+ """
197
+ response_str = "\n".join(response) if isinstance(response, list) else response
198
+ response_str = response_str.replace("```json", "").replace("```", "").strip()
199
+
200
+ # Search for a JSON array pattern using regex, even if it’s incomplete
201
+ json_array_match = re.search(r'(\[.*?\])', response_str, re.DOTALL)
202
+
203
+ # Attempt to parse as JSON and handle unterminated strings by retrying with a trimmed response
204
+ if json_array_match:
205
+ json_str = json_array_match.group(1)
206
+
207
+ try:
208
+ json_data = json.loads(json_str)
209
+ return json_str # Return valid JSON if successful
210
+
211
+ except json.JSONDecodeError as e:
212
+ # If error is due to unterminated strings or missing brackets, try trimming and re-validating
213
+ print(f"JSON extraction failed: {e}")
214
+ # Try a progressive trim of the response
215
+ for i in range(len(json_str), 0, -10):
216
+ try:
217
+ trimmed_json_str = json_str[:i] + "]" # Ensure it ends with a closing bracket
218
+ json_data = json.loads(trimmed_json_str)
219
+ return trimmed_json_str
220
+ except json.JSONDecodeError:
221
+ continue # Keep trimming until valid or no more retries
222
+
223
+ print("JSON extraction failed: Incomplete or malformed response.")
224
+ return "" # Return empty string if parsing fails
225
+
226
+ def generate_qa_from_chunk(text_chunk, retries=2, max_tokens=2500):
227
+ """
228
+ Generate QA pairs based on a text chunk, with JSON validation, chunk splitting, and retry logic.
229
+ """
230
+ if not text_chunk.strip():
231
+ return "" # Return empty if the chunk is blank
232
+
233
+ if len(text_chunk) > max_tokens:
234
+ # Recursively split chunk into smaller sections if it exceeds max token limit
235
+ half = len(text_chunk) // 2
236
+ return generate_qa_from_chunk(text_chunk[:half], retries) + \
237
+ generate_qa_from_chunk(text_chunk[half:], retries)
238
+ prompt = f"""You are an AI assistant tasked with generating informative question-answer pairs from text-based documents.
239
+
240
+ INPUT CONTEXT:
241
+ {text_chunk}
242
+
243
+ TASK:
244
+ Generate relevant question-answer pairs from the provided text. Each pair must:
245
+ 1. Be directly based on the information in the text
246
+ 2. Include a clear, specific question
247
+ 3. Provide an accurate, complete response
248
+ 4. Follow the exact JSON format specified below
249
+
250
+ OUTPUT FORMAT REQUIREMENTS:
251
+ 1. Respond ONLY with a JSON array
252
+ 2. Each object must contain exactly two fields:
253
+ - "prompt": the question
254
+ - "response": the complete answer
255
+ 3. Include no text outside the JSON array
256
+ 4. Follow this exact structure:
257
+
258
+ [
259
+ {{
260
+ "prompt": "What is the daily allowance for a Subedar on domestic travel?",
261
+ "response": "A Subedar is entitled to a daily allowance of Rupees 600 for domestic travel. This allowance covers meals and minor incidental expenses."
262
+ }},
263
+ {{
264
+ "prompt": "How much reimbursement can be claimed for travel by train for a Lieutenant Colonel?",
265
+ "response": "A Lieutenant Colonel is entitled to AC 1st class travel by train. The full fare for AC 1st class is reimbursed, provided the journey is undertaken for official purposes and valid tickets are submitted."
266
+ }},
267
+ {{
268
+ "prompt": "What is the limit for claiming hotel accommodation reimbursement for a Havildar?",
269
+ "response": "A Havildar can claim up to Rupees 2,500 per night for hotel accommodations during official travel, subject to submission of valid receipts and adherence to the approved lodging limits."
270
+ }}
271
+ ]
272
+
273
+ Generate the QA pairs now, following the exact format shown above."""
274
+
275
+ attempt = 0
276
+ while attempt < retries:
277
+ try:
278
+ """Query the vLLM server with retries."""
279
+ url = "http://localhost:8000/v1/chat/completions"
280
+ headers = {"Content-Type": "application/json"}
281
+ data = {
282
+ "model": f"hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4",
283
+ "messages": [
284
+ {"role": "system", "content": "You are a helpful assistant."},
285
+ {"role": "user", "content": prompt}
286
+ ]
287
+ }
288
+ response = requests.post(url, headers=headers, json=data, timeout=300)
289
+ if response and response.choices:
290
+ response_text = response.choices[0].message.content.strip()
291
+
292
+ # Use improved JSON validation with trimming for incomplete responses
293
+ json_str = clean_json_response(response_text)
294
+ if json_str:
295
+ return json_str
296
+ else:
297
+ print("JSON response incomplete, retrying with split chunks.")
298
+ half = len(text_chunk) // 2
299
+ return generate_qa_from_chunk(text_chunk[:half], retries) + \
300
+ generate_qa_from_chunk(text_chunk[half:], retries)
301
+
302
+ except Exception as e:
303
+ print(f"Attempt {attempt + 1} failed: {e}")
304
+ attempt += 1
305
+ time.sleep(5) # Delay before retrying
306
+
307
+ print("All attempts failed for this chunk.")
308
+ return ""
309
+
310
+
311
+ def process_pdf_file_by_pages(pdf_path, output_json_file, pages_per_chunk=4, overlap=1):
312
+ pdf_text_pages = extract_pdf_text_by_page(pdf_path)
313
+ chunks = [' '.join(pdf_text_pages[i:i + pages_per_chunk])
314
+ for i in range(0, len(pdf_text_pages) - pages_per_chunk + 1, pages_per_chunk - overlap)]
315
+
316
+ print(f"Total chunks to process: {len(chunks)}")
317
+ all_qa_pairs = []
318
+
319
+ for idx, chunk in enumerate(chunks):
320
+ print(f"Processing chunk {idx + 1}...")
321
+ try:
322
+ qa_pairs = generate_qa_from_chunk(chunk)
323
+
324
+ if not qa_pairs:
325
+ print(f"No QA pairs generated for chunk {idx + 1}")
326
+ continue
327
+
328
+ qa_pairs_cleaned = clean_json_response(qa_pairs)
329
+ if not qa_pairs_cleaned:
330
+ print(f"Failed to clean JSON for chunk {idx + 1}")
331
+ continue
332
+
333
+ try:
334
+ qa_pairs_json = json.loads(qa_pairs_cleaned)
335
+ all_qa_pairs.extend(qa_pairs_json)
336
+ print(f"Chunk {idx + 1} processed successfully.")
337
+ except json.JSONDecodeError as e:
338
+ print(f"JSON decoding error for chunk {idx + 1}: {e}")
339
+ print(f"Raw cleaned response: {qa_pairs_cleaned}")
340
+
341
+ except Exception as e:
342
+ print(f"Error processing chunk {idx + 1}: {e}")
343
+
344
+ if all_qa_pairs:
345
+ with open(output_json_file, 'w', encoding='utf-8') as json_file:
346
+ json.dump(all_qa_pairs, json_file, ensure_ascii=False, indent=4)
347
+ print(f"QA pairs saved to {output_json_file}")
348
+ else:
349
+ print("No QA pairs were successfully processed.")
350
+
351
+
352
+ # pdf_path = "/home/ubuntu/Diksha/finetuning_1/Finetuning_Complete/Dockerization/TravelEnglish 1.pdf"
353
+ pdf_file=input_data["pdf_file"]
354
+
355
+
356
+ output_json_file = 'output_json.json'
357
+ process_pdf_file_by_pages(pdf_file, output_json_file)
358
+ print(f"QA pairs saved to {output_json_file}")
359
+
360
+ #Here Starts the Finetuning Process
361
+
362
+ max_seq_length = 2048 # Choose any! We auto support RoPE Scaling internally!
363
+ dtype = None # None for auto detection. Float16 for Tesla T4, V100, Bfloat16 for Ampere+
364
+ load_in_4bit = True # Use 4bit quantization to reduce memory usage. Can be False.
365
+
366
+
367
+ model, tokenizer = FastLanguageModel.from_pretrained(
368
+ model_name = "unsloth/Meta-Llama-3.1-8B-bnb-4bit",
369
+ max_seq_length = max_seq_length,
370
+ dtype = dtype,
371
+ load_in_4bit = load_in_4bit,
372
+ )
373
+
374
+ model = FastLanguageModel.get_peft_model(
375
+ model,
376
+ r = 16, # Choose any number > 0 ! Suggested 8, 16, 32, 64, 128
377
+ target_modules = ["q_proj", "k_proj", "v_proj", "o_proj",
378
+ "gate_proj", "up_proj", "down_proj",],
379
+ lora_alpha = 16,
380
+ lora_dropout = 0, # Supports any, but = 0 is optimized
381
+ bias = "none", # Supports any, but = "none" is optimized
382
+ # [NEW] "unsloth" uses 30% less VRAM, fits 2x larger batch sizes!
383
+ use_gradient_checkpointing = "unsloth", # True or "unsloth" for very long context
384
+ random_state = 3407,
385
+ use_rslora = False, # We support rank stabilized LoRA
386
+ loftq_config = None, # And LoftQ
387
+ )
388
+
389
+
390
+ def load_data_from_json(file_path):
391
+ return load_dataset('json', data_files=file_path)['train']
392
+
393
+
394
+ tokenizer = get_chat_template(
395
+ tokenizer,
396
+ chat_template="chatml", # Supports zephyr, chatml, mistral, llama, alpaca, vicuna, vicuna_old, unsloth
397
+ mapping={"role": "from", "content": "value", "user": "human", "assistant": "gpt"}, # ShareGPT style
398
+ map_eos_token=True, # Maps <|im_end|> to </s> instead
399
+ )
400
+
401
+ system_prompt=input_data["system_prompt"]
402
+
403
+ def formatting_prompts_func(examples):
404
+ prompts = examples['prompt']
405
+ responses = examples['response']
406
+
407
+ text = []
408
+
409
+ for prompt, response in zip(prompts, responses):
410
+ prompt = str(prompt).strip()
411
+ response = str(response).strip()
412
+
413
+ # Ensure punctuation for the prompt
414
+ if not prompt.endswith(('?', '.', '!', ':')):
415
+ prompt += '.'
416
+
417
+ # Capitalize the response and ensure punctuation
418
+ response = response.capitalize()
419
+ if not response.endswith(('.', '?', '!')):
420
+ response += '.'
421
+
422
+ # Create conversation in dictionary format, including the system prompt
423
+ convo = [
424
+ {'from': 'system', 'value': system_prompt},
425
+ {'from': 'human', 'value': prompt},
426
+ {'from': 'gpt', 'value': response}
427
+ ]
428
+
429
+ # Apply tokenizer's chat template to format each conversation
430
+ text.append(tokenizer.apply_chat_template(convo, tokenize=False, add_generation_prompt=False))
431
+
432
+ return {"text": text} # Return the formatted text
433
+
434
+ # Load your JSON file
435
+
436
+ dataset = load_data_from_json(output_json_file)
437
+
438
+ # Apply the formatting function to the dataset to create the 'text' column
439
+ dataset = dataset.map(formatting_prompts_func, batched=True) # This line is crucial to add the 'text' column
440
+
441
+ # Print a sample to verify the formatting
442
+ print(dataset["text"][0])
443
+
444
+
445
+
446
+ class TrackBestModelCallback(TrainerCallback):
447
+
448
+ def __init__(self, output_dir):
449
+ super().__init__()
450
+ self.best_loss = float('inf')
451
+ self.best_step = 0
452
+ self.output_dir = output_dir
453
+ os.makedirs(self.output_dir, exist_ok=True)
454
+
455
+
456
+
457
+ def on_log(self, args, state, control, logs=None, **kwargs):
458
+ train_loss = logs.get("loss")
459
+ if train_loss is not None and train_loss < self.best_loss:
460
+ self.best_loss = train_loss
461
+ self.best_step = state.global_step
462
+
463
+ # Save the model to disk
464
+ model_path = os.path.join(self.output_dir, f"best_model_step_{self.best_step}.pt")
465
+ torch.save(kwargs['model'].state_dict(), model_path)
466
+ print(f"New best model saved at {model_path} with loss: {self.best_loss}")
467
+
468
+ # Remove the previous best model if it exists
469
+
470
+ for file in os.listdir(self.output_dir):
471
+ if file.startswith("best_model_step_") and file != f"best_model_step_{self.best_step}.pt":
472
+ os.remove(os.path.join(self.output_dir, file))
473
+
474
+ def on_train_end(self, args, state, control, **kwargs):
475
+ print("Training ended. Best model is saved on disk.")
476
+
477
+ trainer = SFTTrainer(
478
+ model=model,
479
+ tokenizer=tokenizer,
480
+ train_dataset=dataset,
481
+ dataset_text_field="text",
482
+ max_seq_length=max_seq_length,
483
+ dataset_num_proc=4, # Reduced to balance between speed and CPU usage
484
+ packing=False, # Re-enabled packing for efficiency
485
+ args=TrainingArguments(
486
+ per_device_train_batch_size=4, # Reduced to improve speed
487
+ gradient_accumulation_steps=2, # Reduced to increase update frequency
488
+ warmup_steps=100, # Reduced warmup steps
489
+ num_train_epochs=epochs,
490
+ max_steps=max_step,
491
+ learning_rate=learning_rate, # Slightly reduced for stability with smaller batch size
492
+ fp16=not is_bfloat16_supported(),
493
+ bf16=is_bfloat16_supported(),
494
+ logging_steps=50,
495
+ optim="adamw_8bit",
496
+ weight_decay=0.01,
497
+ lr_scheduler_type="cosine",
498
+ seed=3407,
499
+ output_dir="outputs",
500
+ max_grad_norm=1.0,
501
+ dataloader_num_workers=4, # Adjusted to match dataset_num_proc
502
+ gradient_checkpointing=True, # Re-enabled to save memory
503
+ adam_beta1=0.9,
504
+ adam_beta2=0.999,
505
+ adam_epsilon=1e-8,
506
+ ddp_find_unused_parameters=False,
507
+ report_to="none", # Disable wandb logging if you're not using it
508
+ ),
509
+
510
+ )
511
+
512
+
513
+ #@title Show current memory stats
514
+
515
+ gpu_stats = torch.cuda.get_device_properties(0)
516
+ start_gpu_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
517
+ max_memory = round(gpu_stats.total_memory / 1024 / 1024 / 1024, 3)
518
+ print(f"GPU = {gpu_stats.name}. Max memory = {max_memory} GB.")
519
+ print(f"{start_gpu_memory} GB of memory reserved.")
520
+
521
+
522
+ # In your training script:
523
+
524
+ output_dir = "outputs"
525
+ best_model_tracker = TrackBestModelCallback(output_dir)
526
+ trainer.add_callback(best_model_tracker)
527
+
528
+
529
+
530
+ # Start training
531
+
532
+ trainer_stats = trainer.train()
533
+ print("Training completed.")
534
+ print(f"Best loss: {best_model_tracker.best_loss} at step {best_model_tracker.best_step}")
535
+ print("Final training loss:", trainer_stats.training_loss)
536
+
537
+
538
+ #@title Show final memory and time stats
539
+
540
+ used_memory = round(torch.cuda.max_memory_reserved() / 1024 / 1024 / 1024, 3)
541
+ used_memory_for_lora = round(used_memory - start_gpu_memory, 3)
542
+ used_percentage = round(used_memory /max_memory*100, 3)
543
+ lora_percentage = round(used_memory_for_lora/max_memory*100, 3)
544
+ print(f"{trainer_stats.metrics['train_runtime']} seconds used for training.")
545
+ print(f"{round(trainer_stats.metrics['train_runtime']/60, 2)} minutes used for training.")
546
+ print(f"Peak reserved memory = {used_memory} GB.")
547
+ print(f"Peak reserved memory for training = {used_memory_for_lora} GB.")
548
+ print(f"Peak reserved memory % of max memory = {used_percentage} %.")
549
+ print(f"Peak reserved memory for training % of max memory = {lora_percentage} %.")
550
+
551
+ # Saving the model for VLLM
552
+ # Function to save and push model in different formats
553
+ def save_and_push_model(format, save_method, model_name):
554
+ try:
555
+ model.save_pretrained_merged("model", tokenizer, save_method=save_method)
556
+ model.push_to_hub_merged(f"PharynxAI/{model_name}", tokenizer, save_method=save_method, private=True, token=os.getenv('HF_Token'))
557
+ print(f"Successfully saved and pushed model in {format} format.")
558
+ except Exception as e:
559
+ print(f"Error while saving or pushing model in {format} format: {e}")
560
+ if __name__ == "__main__":
561
+
562
+ server_process = None
563
+
564
+ try:
565
+ # # Start vLLM server
566
+ server_process = start_vllm_server("hugging-quants/Meta-Llama-3.1-8B-Instruct-AWQ-INT4")
567
+
568
+ except Exception as e:
569
+ logging.error(f"An error occurred: {e}")
570
+ sys.exit(1)
571
+
572
+ finally:
573
+ # Cleanup: terminate the server process if it exists
574
+ if server_process:
575
+ logging.info("Shutting down vLLM server...")
576
+ server_process.terminate()
577
+ try:
578
+ server_process.wait(timeout=5)
579
+ except subprocess.TimeoutExpired:
580
+ logging.warning("Server didn't terminate gracefully, forcing kill...")
581
+ server_process.kill()
582
+ server_process.wait()
583
+ logging.info("Server shutdown complete")
584
+
585
+ # Assuming input_data is defined and contains 'model_name'
586
+ save_and_push_model("16bit", "merged_16bit", input_data['model_name'])
587
+ save_and_push_model("4bit", "merged_4bit", input_data['model_name'])
588
+ save_and_push_model("LoRA adapters", "lora", input_data['model_name'])
589
+