hoduyquocbao commited on
Commit
b63ef0b
·
1 Parent(s): f48f259

fix errors

Browse files
Files changed (1) hide show
  1. app.py +44 -32
app.py CHANGED
@@ -3,7 +3,6 @@ from threading import Thread
3
  from typing import Iterator, List, Tuple, Dict, Any
4
 
5
  import gradio as gr
6
- import spaces
7
  import torch
8
  from transformers import (
9
  TrainingArguments,
@@ -25,6 +24,9 @@ import time
25
 
26
  # ---------------------------- Cấu Hình ---------------------------- #
27
 
 
 
 
28
  DESCRIPTION = """\
29
  # Llama 3.2 3B Instruct với Chức Năng Nâng Cao
30
 
@@ -41,14 +43,33 @@ MAX_INPUT_TOKEN_LENGTH = int(os.getenv("MAX_INPUT_TOKEN_LENGTH", "128000")) #
41
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
42
 
43
  model_id = "meta-llama/Llama-3.2-3B-Instruct" # ID mô hình
 
 
44
  tokenizer = AutoTokenizer.from_pretrained(model_id)
45
- model = AutoModelForCausalLM.from_pretrained(
 
 
46
  model_id,
47
  device_map="auto",
48
- torch_dtype=torch.float16, # Sử dụng float16 để tương thích với fp16=True
 
49
  )
50
- model.to(device)
51
- model.eval()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
 
53
  # Khởi tạo pipeline phân tích tâm lý trên GPU nếu có
54
  sentiment_pipeline = pipeline(
@@ -129,7 +150,7 @@ def summarize_text(text: str, max_length: int = 150) -> str:
129
  "top_p": 0.95,
130
  "temperature": 0.7,
131
  }
132
- t = Thread(target=model.generate, kwargs=summary_kwargs)
133
  t.start()
134
 
135
  summary = ""
@@ -177,7 +198,7 @@ def generate_response(prompt: str, chat_history: List[Tuple[str, str]], max_new_
177
  "num_beams": 1,
178
  "repetition_penalty": repetition_penalty,
179
  }
180
- t = Thread(target=model.generate, kwargs=generate_kwargs) # Tạo luồng để sinh văn bản
181
  t.start()
182
 
183
  # Stream văn bản được tạo ra
@@ -364,14 +385,15 @@ class SaveCheckpointCallback(TrainerCallback):
364
  kwargs['trainer'].save_model(checkpoint_path)
365
  return control # Trả về đối tượng control hiện tại
366
 
367
- # Tải hình đã được pretrained
368
- pretrained = AutoModelForCausalLM.from_pretrained(
369
- model_id,
370
- device_map="auto",
371
- torch_dtype=torch.float16,
372
- load_in_8bit=False
373
- )
374
 
 
 
 
 
375
  data_collator = DataCollatorForLanguageModeling(
376
  tokenizer=tokenizer,
377
  mlm=False, # Vì bạn đang thực hiện Causal LM
@@ -397,19 +419,9 @@ def get_step_done() -> int:
397
  print(f"Lỗi khi phân tích tên checkpoint: {e}")
398
  return 0
399
 
400
- # Tải Cấu Hình Hình với LoRA (GPU)
401
- lora_config = LoraConfig(
402
- r=8,
403
- lora_alpha=32,
404
- target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
405
- lora_dropout=0.1,
406
- bias="none",
407
- )
408
-
409
- pretrained_model = get_peft_model(pretrained, lora_config)
410
- print(pretrained_model)
411
 
412
- @spaces.GPU(duration=30, queue=False)
413
  def run_training() -> str:
414
  """
415
  Hàm huấn luyện mô hình sử dụng GPU với thời gian hạn chế.
@@ -436,7 +448,7 @@ def run_training() -> str:
436
  save_total_limit=5, # Giới hạn số lượng checkpoint lưu trữ
437
  fp16=True, # Kích hoạt huấn luyện hỗn hợp độ chính xác
438
  report_to="none",
439
- load_best_model_at_end=True,
440
  )
441
 
442
  # Tạo Trainer (GPU)
@@ -447,7 +459,7 @@ def run_training() -> str:
447
  eval_dataset=final_dataset['validation'],
448
  tokenizer=tokenizer,
449
  data_collator=data_collator,
450
- callbacks=[SaveCheckpointCallback()], # Thêm callback
451
  )
452
 
453
  # Kiểm tra nếu có checkpoint
@@ -469,7 +481,7 @@ def run_training() -> str:
469
  return "Huấn luyện hoàn tất hoặc đã tiếp tục từ checkpoint."
470
 
471
  # Hàm Tự Động Hóa Việc Gọi Lặp Lại Hàm Huấn Luyện
472
- @spaces.GPU(duration=30, queue=False)
473
  def continuous_training(total_steps=300, steps_per_call=50):
474
  """
475
  Hàm tự động gọi lại `run_training` để hoàn thành quá trình huấn luyện.
@@ -502,7 +514,7 @@ def continuous_training(total_steps=300, steps_per_call=50):
502
  save_total_limit=5,
503
  fp16=True,
504
  report_to="none",
505
- load_best_model_at_end=True,
506
  )
507
 
508
  # Tạo Trainer với TrainingArguments mới
@@ -513,7 +525,7 @@ def continuous_training(total_steps=300, steps_per_call=50):
513
  eval_dataset=final_dataset['validation'],
514
  tokenizer=tokenizer,
515
  data_collator=data_collator,
516
- callbacks=[SaveCheckpointCallback()],
517
  )
518
 
519
  # Tiếp tục huấn luyện từ checkpoint hiện tại
@@ -541,7 +553,7 @@ def continuous_training(total_steps=300, steps_per_call=50):
541
 
542
  # ---------------------------- Giao Diện Gradio ---------------------------- #
543
 
544
- @spaces.GPU(duration=30, queue=False)
545
  def generate(
546
  message: str,
547
  chat_history: List[Tuple[str, str]],
 
3
  from typing import Iterator, List, Tuple, Dict, Any
4
 
5
  import gradio as gr
 
6
  import torch
7
  from transformers import (
8
  TrainingArguments,
 
24
 
25
  # ---------------------------- Cấu Hình ---------------------------- #
26
 
27
+ # Vô hiệu hóa cảnh báo tokenizers_parallelism
28
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
29
+
30
  DESCRIPTION = """\
31
  # Llama 3.2 3B Instruct với Chức Năng Nâng Cao
32
 
 
43
  device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")
44
 
45
  model_id = "meta-llama/Llama-3.2-3B-Instruct" # ID mô hình
46
+
47
+ # Tải tokenizer
48
  tokenizer = AutoTokenizer.from_pretrained(model_id)
49
+
50
+ # Tải mô hình cho huấn luyện và áp dụng LoRA
51
+ pretrained = AutoModelForCausalLM.from_pretrained(
52
  model_id,
53
  device_map="auto",
54
+ torch_dtype=torch.float16,
55
+ load_in_8bit=False
56
  )
57
+
58
+ # Cấu hình LoRA
59
+ lora_config = LoraConfig(
60
+ r=8,
61
+ lora_alpha=32,
62
+ target_modules=["q_proj", "k_proj", "v_proj", "out_proj"],
63
+ lora_dropout=0.1,
64
+ bias="none",
65
+ )
66
+
67
+ # Áp dụng LoRA vào mô hình
68
+ pretrained_model = get_peft_model(pretrained, lora_config)
69
+ pretrained_model.print_trainable_parameters()
70
+
71
+ # Đảm bảo mô hình ở chế độ huấn luyện
72
+ pretrained_model.train()
73
 
74
  # Khởi tạo pipeline phân tích tâm lý trên GPU nếu có
75
  sentiment_pipeline = pipeline(
 
150
  "top_p": 0.95,
151
  "temperature": 0.7,
152
  }
153
+ t = Thread(target=pretrained_model.generate, kwargs=summary_kwargs)
154
  t.start()
155
 
156
  summary = ""
 
198
  "num_beams": 1,
199
  "repetition_penalty": repetition_penalty,
200
  }
201
+ t = Thread(target=pretrained_model.generate, kwargs=generate_kwargs) # Tạo luồng để sinh văn bản
202
  t.start()
203
 
204
  # Stream văn bản được tạo ra
 
385
  kwargs['trainer'].save_model(checkpoint_path)
386
  return control # Trả về đối tượng control hiện tại
387
 
388
+ # Định Nghĩa TrainerCallback để Xử Lý Kết Thúc Huấn Luyện
389
+ class PrintCallback(TrainerCallback):
390
+ def on_train_begin(self, args, state, control, **kwargs):
391
+ print("Bắt đầu quá trình huấn luyện...")
 
 
 
392
 
393
+ def on_train_end(self, args, state, control, **kwargs):
394
+ print("Quá trình huấn luyện đã kết thúc.")
395
+
396
+ # Data Collator
397
  data_collator = DataCollatorForLanguageModeling(
398
  tokenizer=tokenizer,
399
  mlm=False, # Vì bạn đang thực hiện Causal LM
 
419
  print(f"Lỗi khi phân tích tên checkpoint: {e}")
420
  return 0
421
 
422
+ # ---------------------------- Định Nghĩa Huấn Luyện ---------------------------- #
 
 
 
 
 
 
 
 
 
 
423
 
424
+ @gradio.GPU # Sử dụng decorator phù hợp nếu cần
425
  def run_training() -> str:
426
  """
427
  Hàm huấn luyện mô hình sử dụng GPU với thời gian hạn chế.
 
448
  save_total_limit=5, # Giới hạn số lượng checkpoint lưu trữ
449
  fp16=True, # Kích hoạt huấn luyện hỗn hợp độ chính xác
450
  report_to="none",
451
+ load_best_model_at_end=False, # Tắt load best model để tránh xung đột
452
  )
453
 
454
  # Tạo Trainer (GPU)
 
459
  eval_dataset=final_dataset['validation'],
460
  tokenizer=tokenizer,
461
  data_collator=data_collator,
462
+ callbacks=[SaveCheckpointCallback(), PrintCallback()], # Thêm callback
463
  )
464
 
465
  # Kiểm tra nếu có checkpoint
 
481
  return "Huấn luyện hoàn tất hoặc đã tiếp tục từ checkpoint."
482
 
483
  # Hàm Tự Động Hóa Việc Gọi Lặp Lại Hàm Huấn Luyện
484
+ @gradio.GPU
485
  def continuous_training(total_steps=300, steps_per_call=50):
486
  """
487
  Hàm tự động gọi lại `run_training` để hoàn thành quá trình huấn luyện.
 
514
  save_total_limit=5,
515
  fp16=True,
516
  report_to="none",
517
+ load_best_model_at_end=False,
518
  )
519
 
520
  # Tạo Trainer với TrainingArguments mới
 
525
  eval_dataset=final_dataset['validation'],
526
  tokenizer=tokenizer,
527
  data_collator=data_collator,
528
+ callbacks=[SaveCheckpointCallback(), PrintCallback()],
529
  )
530
 
531
  # Tiếp tục huấn luyện từ checkpoint hiện tại
 
553
 
554
  # ---------------------------- Giao Diện Gradio ---------------------------- #
555
 
556
+ @gradio.GPU
557
  def generate(
558
  message: str,
559
  chat_history: List[Tuple[str, str]],