DANGDOCAO commited on
Commit
5bf8ca4
·
verified ·
1 Parent(s): a384a74
Files changed (1) hide show
  1. HVU_QA/fine_tune_qg.py +111 -139
HVU_QA/fine_tune_qg.py CHANGED
@@ -1,153 +1,125 @@
1
- import re
2
- import torch
3
- from difflib import SequenceMatcher
4
- from transformers import T5Tokenizer, T5ForConditionalGeneration
5
- from transformers.utils import logging as hf_logging
6
-
7
- hf_logging.set_verbosity_error()
8
-
9
- MODEL_DIR = "t5-viet-qg-finetuned"
10
-
11
- PATTERN = re.compile(
12
- r"""
13
- ([^”]{3,120})
14
- | "([^"]{3,120})"
15
- | \b(?:là|gồm|do|theo)\s+([^,.;:\n]{3,120})
16
- | \b\d{4}\b
17
- | \b(?:Điều|Khoản)\s+\d+\b
18
- """,
19
- re.VERBOSE | re.IGNORECASE,
20
- )
21
-
22
-
23
- def norm(s: str) -> str:
24
- return re.sub(r"\s+", " ", s).strip()
25
-
26
-
27
- def is_dup(q: str, qs: list[str], thr: float = 0.85) -> bool:
28
- ql = q.lower()
29
- for x in qs:
30
- if SequenceMatcher(None, ql, x.lower()).ratio() >= thr:
31
- return True
32
- return False
33
-
34
-
35
- def extract_answers(ctx: str, max_n: int = 60) -> list[str]:
36
- ctx = norm(ctx)
37
- answers, seen = [], set()
38
-
39
- for m in PATTERN.finditer(ctx):
40
- for g in m.groups():
41
- if not g:
42
- continue
43
- g = norm(g)
44
- k = g.lower()
45
- if 3 <= len(g) <= 120 and k not in seen:
46
- seen.add(k)
47
- answers.append(g)
48
- if len(answers) >= max_n:
49
- return answers
50
-
51
- if len(answers) < 8:
52
- for i in range(0, min(len(ctx), 500), 60):
53
- ch = norm(ctx[i : i + 60])
54
- k = ch.lower()
55
- if len(ch) >= 15 and k not in seen:
56
- seen.add(k)
57
- answers.append(ch)
58
- if len(answers) >= max_n:
59
- break
60
-
61
- if not answers and ctx:
62
- answers = [ctx[:120]]
63
-
64
- return answers
65
-
66
-
67
- def load_model():
68
- tok = T5Tokenizer.from_pretrained(MODEL_DIR)
69
- mdl = T5ForConditionalGeneration.from_pretrained(MODEL_DIR)
70
-
71
- dev = "cuda" if torch.cuda.is_available() else "cpu"
72
- try:
73
- mdl = mdl.to(dev)
74
- except RuntimeError:
75
- dev = "cpu"
76
- try:
77
- torch.cuda.empty_cache()
78
- except Exception:
79
- pass
80
- mdl = mdl.to(dev)
81
-
82
- mdl.eval()
83
- return tok, mdl, dev
84
 
85
 
86
- tokenizer, model, device = load_model()
 
 
 
 
87
 
88
 
89
- def generate_questions(context: str, n: int = 20) -> list[str]:
90
- ctx = norm(context)
91
- answers = extract_answers(ctx, max_n=80)
92
- questions = []
93
 
94
- gen_cfg = dict(
95
- do_sample=True,
96
- top_k=80,
97
- top_p=0.98,
98
- temperature=1.05,
99
- max_new_tokens=72,
100
- no_repeat_ngram_size=3,
101
- repetition_penalty=1.08,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
  )
103
 
104
- num_ret = 8 if n <= 20 else 10
105
-
106
- def run_prompt(ans: str, rounds: int):
107
- nonlocal gen_cfg
108
- prompt = f"answer: {ans}\ncontext: {ctx}\nquestion:"
109
- inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=512).to(device)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
 
111
- for _ in range(rounds):
112
- outs = model.generate(**inputs, num_return_sequences=num_ret, **gen_cfg)
113
- added = 0
114
- for o in outs:
115
- q = norm(tokenizer.decode(o, skip_special_tokens=True))
116
- if not q:
117
- continue
118
- if not q.endswith("?"):
119
- q += "?"
120
- if len(q) >= 6 and not is_dup(q, questions, thr=0.85):
121
- questions.append(q)
122
- added += 1
123
- if len(questions) >= n:
124
- return
125
- if added == 0:
126
- gen_cfg["temperature"] = min(1.25, gen_cfg["temperature"] + 0.05)
127
- gen_cfg["top_p"] = min(0.995, gen_cfg["top_p"] + 0.005)
128
 
129
- with torch.inference_mode():
130
- for ans in answers:
131
- if len(questions) >= n:
132
- break
133
- run_prompt(ans, rounds=6)
 
 
134
 
135
- if len(questions) < n:
136
- run_prompt(ctx[:120], rounds=12)
 
137
 
138
- return questions[:n]
139
 
140
 
141
  if __name__ == "__main__":
142
- ctx = input("\nNhập đoạn văn bản:\n").strip()
143
- try:
144
- n = int((input("\nNhập số lượng câu hỏi cần sinh: ").strip() or "20"))
145
- except ValueError:
146
- n = 20
147
-
148
- n = max(1, min(n, 200))
149
- qs = generate_questions(ctx, n)
150
-
151
- print("\nCác câu hỏi sinh ra:")
152
- for i, q in enumerate(qs, 1):
153
- print(f"{i}. {q}")
 
1
+ import os, json
2
+ from datasets import Dataset
3
+ from sklearn.model_selection import train_test_split
4
+ from transformers import T5Tokenizer, T5ForConditionalGeneration, TrainingArguments, Trainer, DataCollatorForSeq2Seq
5
+
6
+
7
+ def load_squad(path: str):
8
+ with open(path, "r", encoding="utf-8") as f:
9
+ d = json.load(f)
10
+
11
+ data = []
12
+ for a in d.get("data", []):
13
+ for p in a.get("paragraphs", []):
14
+ ctx = p.get("context", "")
15
+ for qa in p.get("qas", []):
16
+ if qa.get("is_impossible") or not qa.get("answers"):
17
+ continue
18
+ ans = qa["answers"][0].get("text", "")
19
+ q = qa.get("question", "")
20
+ if ans and q and ctx:
21
+ data.append({"input": f"answer: {ans} context: {ctx}", "target": q})
22
+ return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
 
25
+ def tokenize(batch, tok, max_in=512, max_out=64):
26
+ x = tok(batch["input"], max_length=max_in, truncation=True)
27
+ y = tok(text_target=batch["target"], max_length=max_out, truncation=True)
28
+ x["labels"] = y["input_ids"]
29
+ return x
30
 
31
 
32
+ def latest_ckpt(out_dir: str):
33
+ if not os.path.isdir(out_dir):
34
+ return None
 
35
 
36
+ best_step, best_path = -1, None
37
+ for name in os.listdir(out_dir):
38
+ if not name.startswith("checkpoint-"):
39
+ continue
40
+ try:
41
+ step = int(name.split("-")[-1])
42
+ except ValueError:
43
+ continue
44
+ if step > best_step:
45
+ best_step, best_path = step, os.path.join(out_dir, name)
46
+
47
+ return best_path
48
+
49
+
50
+ def main():
51
+ data_path = "39k_train.json"
52
+ out_dir = "t5-viet-qg-finetuned"
53
+ logs_dir = "logs"
54
+ model_name = "VietAI/vit5-base"
55
+
56
+ print("Tải mô hình và tokenizer...")
57
+ tok = T5Tokenizer.from_pretrained(model_name)
58
+ model = T5ForConditionalGeneration.from_pretrained(model_name)
59
+
60
+ print("Đọc và chia dữ liệu...")
61
+ data = load_squad(data_path)
62
+ tr, va = train_test_split(data, test_size=0.2, random_state=42)
63
+
64
+ print("Tokenize dữ liệu...")
65
+ tr_ds = Dataset.from_list(tr).map(
66
+ lambda b: tokenize(b, tok),
67
+ batched=True,
68
+ remove_columns=["input", "target"],
69
+ )
70
+ va_ds = Dataset.from_list(va).map(
71
+ lambda b: tokenize(b, tok),
72
+ batched=True,
73
+ remove_columns=["input", "target"],
74
  )
75
 
76
+ print("Cấu hình huấn luyện (checkpoint + resume)...")
77
+ args = TrainingArguments(
78
+ output_dir=out_dir,
79
+ overwrite_output_dir=False,
80
+ per_device_train_batch_size=1,
81
+ gradient_accumulation_steps=1,
82
+ num_train_epochs=3,
83
+ learning_rate=2e-4,
84
+ weight_decay=0.01,
85
+ warmup_steps=0,
86
+ save_strategy="steps",
87
+ save_steps=500,
88
+ save_total_limit=100,
89
+ eval_strategy="steps",
90
+ eval_steps=500,
91
+ load_best_model_at_end=True,
92
+ metric_for_best_model="eval_loss",
93
+ greater_is_better=False,
94
+ logging_dir=logs_dir,
95
+ logging_steps=10,
96
+ fp16=True,
97
+ report_to="none",
98
+ )
99
 
100
+ trainer = Trainer(
101
+ model=model,
102
+ args=args,
103
+ train_dataset=tr_ds,
104
+ eval_dataset=va_ds,
105
+ tokenizer=tok,
106
+ data_collator=DataCollatorForSeq2Seq(tokenizer=tok, model=model),
107
+ )
 
 
 
 
 
 
 
 
 
108
 
109
+ ckpt = latest_ckpt(out_dir)
110
+ if ckpt:
111
+ print(f"Phát hiện checkpoint: {ckpt} → Resume training")
112
+ trainer.train(resume_from_checkpoint=ckpt)
113
+ else:
114
+ print("Không có checkpoint → Train từ đầu")
115
+ trainer.train()
116
 
117
+ print("Lưu hình cuối cùng...")
118
+ trainer.save_model(out_dir)
119
+ tok.save_pretrained(out_dir)
120
 
121
+ print("Huấn luyện hoàn tất!")
122
 
123
 
124
  if __name__ == "__main__":
125
+ main()