DANGDOCAO commited on
Commit
8a3f531
·
verified ·
1 Parent(s): b5e6c8b

Upload 6 files

Browse files
.gitattributes CHANGED
@@ -1 +1,2 @@
1
  QA/frontend/HVU.png filter=lfs diff=lfs merge=lfs -text
 
 
1
  QA/frontend/HVU.png filter=lfs diff=lfs merge=lfs -text
2
+ QA/45k_train.json filter=lfs diff=lfs merge=lfs -text
QA/45k_train.json ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:31c51730f2c34919ded3e09c91b96179299474048b2cb6652ecc64f88134de21
3
+ size 119008253
QA/README.md ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ license: mit
3
+ task_categories:
4
+ - question-answering
5
+ - text-generation
6
+ - table-question-answering
7
+ - sentence-similarity
8
+ - feature-extraction
9
+ language:
10
+ - vi
11
+ tags:
12
+ - question-generation
13
+ - nlp
14
+ - faq
15
+ - low-resource
16
+ - code
17
+ pretty_name: HVU_QA
18
+ size_categories:
19
+ - 10K<n<100K
20
+ configs:
21
+ - config_name: default
22
+ data_files:
23
+ - split: train
24
+ path: 40k_train.json
25
+ ---
26
+ # HVU_QA
27
+
28
+ **HVU_QA** is an open-source Vietnamese Question-Context-Answer (QCA) corpus, accompanied by supporting tools, created to facilitate the development of FAQ-style question generation and question answering systems, particularly for low-resource language settings. The dataset was developed by a research team at Hung Vuong University, Phu Tho, Vietnam, led by Dr. Ha Nguyen, Deputy Head of the Department of Engineering Technology. HVU_QA was constructed using a fully automated data-building pipeline that combines web crawling from reliable sources, semantic tag-based extraction, and AI-assisted filtering, helping ensure high factual accuracy, consistent structure, and practical usability for real-world applications.
29
+
30
+ ## 📋 Dataset Description
31
+
32
+ - **Language:** Vietnamese
33
+ - **Format:** SQuAD-style JSON
34
+ - **Total samples:** 40,000 QCA triples (full corpus released)
35
+ - **Domains covered:** Social services, labor law, administrative processes, and other public service topics.
36
+ - **Structure of each sample:**
37
+ - **Question:** Generated or extracted question
38
+ - **Context:** Supporting text passage from which the answer is derived
39
+ - **Answer:** Answer span within the context
40
+
41
+ ## ⚙️ Creation Pipeline
42
+
43
+ The dataset was built using a 5-stage automated process:
44
+ 1. **Selecting relevant QA websites** from trusted sources.
45
+ 2. **Automated data crawling** to collect raw QA webpages.
46
+ 3. **Extraction via semantic tags** to obtain clean Question-Context-Answer triples.
47
+ 4. **AI-assisted filtering** to remove noisy or factually inconsistent samples.
48
+ 5. **Final canonicalization and deduplication** to eliminate redundancy and maintain corpus diversity.
49
+
50
+ ## 📊 Quality Evaluation
51
+ A fine-tuned `vit5-base` model trained on HVU_QA achieved:
52
+
53
+ | Metric | Score |
54
+ |-------------------------|----------------|
55
+ | BLEU | 89.1 |
56
+ | Semantic similarity | 91.5% (cos ≥ 0.8) |
57
+ | Human grammar score | 4.58 / 5 |
58
+ | Human usefulness score | 4.29 / 5 |
59
+
60
+ These results confirm that HVU_QA is a high-quality resource for developing robust FAQ-style question generation models.
61
+
62
+ ## 📁 Project Structure
63
+ ```text
64
+ HVU_QA/
65
+ ├── backend/
66
+ │ ├── __init__.py
67
+ │ └── app.py
68
+ ├── frontend/
69
+ │ ├── HVU.png
70
+ │ ├── index.html
71
+ │ ├── app.js
72
+ │ └── style.css
73
+ ├── t5-viet-qg-finetuned/
74
+ ├── fine_tune_qg.py
75
+ ├── generate_question.py
76
+ ├── HVU_QA_tool.py
77
+ ├── main.py
78
+ ├── 40k_train.json
79
+ ├── requirements.txt
80
+ └── README.md
81
+ ```
82
+ ## 📁 Vietnamese Question Generation Toolkit
83
+
84
+ This repository includes four main entry points:
85
+
86
+ * `main.py`: starts the local Flask web application with the current `backend/` and `frontend/`.
87
+ * `fine_tune_qg.py`: fine-tunes the Vietnamese T5-based question generation model using `40k_train.json`.
88
+ * `generate_question.py`: command-line script for generating questions from a Vietnamese passage.
89
+ * `HVU_QA_tool.py`: one-file launcher that can prepare a standalone runtime, install missing dependencies, download the model from Hugging Face, and launch the web app automatically.
90
+
91
+ ## 🛠️ Requirements
92
+
93
+ * Python 3.10+
94
+ * `pip`
95
+ * Optional: NVIDIA GPU with CUDA for faster inference
96
+
97
+ ### 📦 Install Required Libraries
98
+
99
+ For running the full repository locally:
100
+
101
+ ```bash
102
+ python -m venv venv
103
+
104
+ # Windows
105
+ venv\Scripts\activate
106
+
107
+ # macOS / Linux
108
+ source venv/bin/activate
109
+
110
+ python -m pip install --upgrade pip
111
+ python -m pip install -r requirements.txt
112
+ ```
113
+
114
+ If you want to use NVIDIA GPU, install the PyTorch build that matches your CUDA setup from [pytorch.org](https://pytorch.org) before installing the remaining requirements.
115
+
116
+ `HVU_QA_tool.py` can also create its own virtual environment, prepare a standalone runtime, and sync the model automatically, so the manual installation steps above are mainly for direct repo usage.
117
+
118
+ ### 📥 Load Dataset from Hugging Face Hub
119
+ ```python
120
+ from datasets import load_dataset
121
+
122
+ ds = load_dataset("DANGDOCAO/GeneratingQuestions", split="train")
123
+ print(ds[0])
124
+ ```
125
+ ## 📚 Usage
126
+
127
+ * Run the local web interface for question generation.
128
+ * Generate questions from the command line.
129
+ * Fine-tune or evaluate the Vietnamese question generation model.
130
+
131
+ ### 🔹 Run the web app
132
+
133
+ ```bash
134
+ python main.py
135
+ ```
136
+
137
+ Open `http://127.0.0.1:5000` in your browser.
138
+
139
+ ### 🔹 Launch with `HVU_QA_tool.py`
140
+
141
+ ```bash
142
+ python HVU_QA_tool.py
143
+ ```
144
+
145
+ This launcher is useful when you want the project to set itself up automatically. It can detect the local repo, prepare a standalone runtime when needed, install missing dependencies, download the model, and then start the web application.
146
+
147
+ ### 🔹 Fine-tuning
148
+
149
+ ```bash
150
+ python fine_tune_qg.py
151
+ ```
152
+
153
+ This will:
154
+
155
+ 1. Load the dataset from `40k_train.json`.
156
+ 2. Fine-tune `VietAI/vit5-base`.
157
+ 3. Save the trained model into `t5-viet-qg-finetuned/`.
158
+
159
+ *(Or download the pre-trained model: [t5-viet-qg-finetuned](https://huggingface.co/datasets/DANGDOCAO/GeneratingQuestions/tree/main).)*
160
+
161
+ ### 🔹 Generating Questions
162
+ ```bash
163
+ python generate_question.py
164
+ ```
165
+
166
+ **Example:**
167
+ ```
168
+ Input passage:
169
+ Cà phê sữa đá là một loại đồ uống nổi tiếng ở Việt Nam
170
+ (Iced milk coffee is a famous drink in Vietnam)
171
+
172
+ Number of questions: 5
173
+ ```
174
+ **Output:**
175
+ ```
176
+ 1. Loại cà phê nào nổi tiếng ở Việt Nam?
177
+ (What type of coffee is famous in Vietnam?)
178
+ 2. Tại sao cà phê sữa đá lại phổ biến?
179
+ (Why is iced milk coffee popular?)
180
+ 3. Cà phê sữa đá bao gồm những nguyên liệu gì?
181
+ (What ingredients are included in iced milk coffee?)
182
+ 4. Cà phê sữa đá có nguồn gốc từ đâu?
183
+ (Where does iced milk coffee originate from?)
184
+ 5. Cà phê sữa đá Việt Nam được pha chế như thế nào?
185
+ (How is Vietnamese iced milk coffee prepared?)
186
+ ```
187
+ **You can adjust** in `generate_question.py`:
188
+
189
+ * `--model_dir`, `--num_questions`, `--max_source_length`, `--max_new_tokens`, `--device`, `GENERATION_PASSES`, `no_repeat_ngram_size`, `repetition_penalty`
190
+
191
+ ## 📌 Citation
192
+ If you use **HVU_QA** in your research, please cite:
193
+
194
+ ```bibtex
195
+ @inproceedings{nguyen2025method,
196
+ author = {Ha Nguyen and Phuc Le and Dang Do and Cuong Nguyen and Chung Mai},
197
+ title = {A Method for Building QA Corpora for Low-Resource Languages},
198
+ booktitle = {Proceedings of the 2025 International Symposium on Information and Communication Technology (SOICT 2025)},
199
+ year = {2025},
200
+ publisher = {Springer},
201
+ series = {Communications in Computer and Information Science (CCIS)},
202
+ address = {Nha Trang, Vietnam},
203
+ note = {To appear}
204
+ }
205
+ ```
206
+ ## ❤️ Support / Funding
207
+
208
+ If you find **HVU_QA** useful, please consider supporting our work.
209
+ Your contributions help us maintain the dataset, improve quality, and release new versions (cleaning, expansion, benchmarks, and tools).
210
+
211
+ ### 🇻🇳 Donate via VietQR (scan to support)
212
+ This **VietQR / NAPAS 247** code can be scanned by Vietnamese banking apps and some international payment apps that support QR bank transfers.
213
+
214
+ Mã QR VietQR chưa được đính kèm trong thư mục hiện tại.
215
+
216
+ - 🏦 **Bank:** VietinBank (Vietnam)
217
+ - 👤 **Account name:** NGUYEN TIEN HA
218
+ - 💳 **Account number:** 103004492490
219
+ - 📍 **Branch:** VietinBank CN PHU THO - HOI SO
220
+
221
+ ### 🌍 International Support (Quick card payment)
222
+ If you are outside Vietnam, you can support this project via **Buy Me a Coffee**
223
+ (no PayPal account needed - pay directly with a credit/debit card):
224
+ - BuyMeACoffee: https://buymeacoffee.com/hanguyen0408
225
+
226
+ ### 🌍 International Support (PayPal)
227
+ If you prefer PayPal, you can also support us here:
228
+ - PayPal.me: https://paypal.me/HaNguyen0408
229
+
230
+ ### ✨ Other ways to support
231
+ - ⭐ Star this repository / dataset on Hugging Face
232
+ - 📌 Cite our paper if you use it in your research
233
+ - 🐛 Open issues / pull requests to improve the dataset and tools
234
+
235
+ ## 📬 Contact / Maintainers
236
+ For questions, feedback, collaborations, or issue reports related to HVU_QA, please contact:
237
+ Lê Hồng Phúc
238
+ Hung Vuong University, Phu Tho, Vietnam
239
+ Email: lehongphuc@hvu.edu.vn
QA/fine_tune_qg.py ADDED
@@ -0,0 +1,556 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import subprocess
7
+ import sys
8
+ from importlib import metadata
9
+ from inspect import signature
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
14
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
15
+
16
+
17
+ def raise_missing_dependency_error(exc: ModuleNotFoundError) -> None:
18
+ root = Path(__file__).resolve().parent
19
+ script = Path(__file__).resolve()
20
+ requirements = root / "requirements.txt"
21
+ venv_python = root / "venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
22
+ lines = [f"Thiếu thư viện Python: {exc.name}", f"Interpreter hiện tại: {sys.executable}"]
23
+ if venv_python.exists():
24
+ lines.extend([f"Venv của project: {venv_python}", f"Chạy lại bằng: {venv_python} {script}"])
25
+ if requirements.exists():
26
+ lines.extend(
27
+ [
28
+ "Hoặc cài dependencies cho interpreter hiện tại bằng:",
29
+ f"{sys.executable} -m pip install -r {requirements}",
30
+ ]
31
+ )
32
+ raise SystemExit("\n".join(lines)) from exc
33
+
34
+
35
+ try:
36
+ import torch
37
+ from datasets import Dataset
38
+ from transformers import (
39
+ AutoModelForSeq2SeqLM,
40
+ AutoTokenizer,
41
+ DataCollatorForSeq2Seq,
42
+ EarlyStoppingCallback,
43
+ Seq2SeqTrainer,
44
+ Seq2SeqTrainingArguments,
45
+ set_seed,
46
+ )
47
+ from transformers.trainer_utils import get_last_checkpoint
48
+ except ModuleNotFoundError as exc:
49
+ raise_missing_dependency_error(exc)
50
+
51
+
52
+ def normalize_text(text: Any) -> str:
53
+ return " ".join(str(text or "").split())
54
+
55
+
56
+ def dedupe(items) -> list[str]:
57
+ seen, output = set(), []
58
+ for item in items:
59
+ if item and item not in seen:
60
+ seen.add(item)
61
+ output.append(item)
62
+ return output
63
+
64
+
65
+ def save_json(data: dict[str, Any], path: Path) -> None:
66
+ path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
67
+
68
+
69
+ def get_installed_version(package_name: str) -> tuple[int, ...]:
70
+ try:
71
+ version = metadata.version(package_name)
72
+ except metadata.PackageNotFoundError:
73
+ return ()
74
+
75
+ parts = []
76
+ for chunk in version.replace("-", ".").split("."):
77
+ digits = "".join(ch for ch in chunk if ch.isdigit())
78
+ if not digits:
79
+ break
80
+ parts.append(int(digits))
81
+ return tuple(parts)
82
+
83
+
84
+ def supports_data_seed() -> bool:
85
+ return get_installed_version("accelerate") >= (1, 1, 0)
86
+
87
+
88
+ def run_nvidia_smi(query: str) -> list[list[str]]:
89
+ try:
90
+ result = subprocess.run(
91
+ ["nvidia-smi", f"--query-{query}", "--format=csv,noheader,nounits"],
92
+ check=True,
93
+ capture_output=True,
94
+ text=True,
95
+ )
96
+ except (FileNotFoundError, subprocess.CalledProcessError):
97
+ return []
98
+
99
+ return [
100
+ [part.strip() for part in line.split(",")]
101
+ for line in result.stdout.strip().splitlines()
102
+ if line.strip()
103
+ ]
104
+
105
+
106
+ def query_gpu_memory():
107
+ rows = run_nvidia_smi("gpu=memory.total,memory.used,memory.free")
108
+ if not rows or len(rows[0]) < 3:
109
+ return None
110
+ try:
111
+ total_mb, used_mb, free_mb = (int(value) for value in rows[0][:3])
112
+ except ValueError:
113
+ return None
114
+ return {"total_mb": total_mb, "used_mb": used_mb, "free_mb": free_mb}
115
+
116
+
117
+ def query_gpu_processes() -> list[dict[str, Any]]:
118
+ processes = []
119
+ for row in run_nvidia_smi("compute-apps=pid,process_name,used_memory"):
120
+ if len(row) != 3:
121
+ continue
122
+ try:
123
+ pid = int(row[0])
124
+ used_memory_mb = int(row[2])
125
+ except ValueError:
126
+ continue
127
+ processes.append({"pid": pid, "process_name": row[1], "used_memory_mb": used_memory_mb})
128
+ return processes
129
+
130
+
131
+ def format_memory_mb(memory_mb: int) -> str:
132
+ return f"{memory_mb} MiB ({memory_mb / 1024:.2f} GiB)"
133
+
134
+
135
+ def active_gpu_processes() -> list[dict[str, Any]]:
136
+ current_pid = os.getpid()
137
+ return sorted(
138
+ [proc for proc in query_gpu_processes() if proc["pid"] != current_pid and proc["used_memory_mb"] > 0],
139
+ key=lambda item: item["used_memory_mb"],
140
+ reverse=True,
141
+ )
142
+
143
+
144
+ def append_process_lines(lines: list[str], header: str, processes: list[dict[str, Any]]) -> None:
145
+ if not processes:
146
+ return
147
+ lines.append(header)
148
+ lines.extend(
149
+ f"- PID {proc['pid']} | {proc['process_name']} | {format_memory_mb(proc['used_memory_mb'])}"
150
+ for proc in processes
151
+ )
152
+
153
+
154
+ def ensure_device_ready(args) -> None:
155
+ if args.device == "cpu":
156
+ return
157
+ if not torch.cuda.is_available():
158
+ if args.device == "cuda":
159
+ raise SystemExit("Bạn đã chọn --device cuda nhưng môi trường hiện tại không có CUDA.")
160
+ return
161
+ if args.skip_gpu_preflight:
162
+ return
163
+
164
+ gpu_memory = query_gpu_memory()
165
+ if gpu_memory is None or gpu_memory["free_mb"] >= args.min_free_gpu_mb:
166
+ return
167
+
168
+ lines = [
169
+ "GPU không đủ bộ nhớ để bắt đầu train ổn định.",
170
+ f"GPU free: {format_memory_mb(gpu_memory['free_mb'])} / total: {format_memory_mb(gpu_memory['total_mb'])}.",
171
+ f"Ngưỡng tối thiểu hiện tại: {format_memory_mb(args.min_free_gpu_mb)}.",
172
+ ]
173
+ append_process_lines(lines, "Các tiến trình CUDA đang chiếm GPU:", active_gpu_processes())
174
+ lines.extend(
175
+ [
176
+ "Cách xử lý:",
177
+ "- Giải phóng tiến trình đang chiếm GPU rồi chạy lại.",
178
+ "- Hoặc train trên CPU bằng `python fine_tune_qg.py --device cpu`.",
179
+ "- Nếu GPU đã rảnh mà vẫn thiếu VRAM, thử `--per_device_train_batch_size 1 --per_device_eval_batch_size 1 --gradient_accumulation_steps 16 --gradient_checkpointing`.",
180
+ "- Nếu bạn vẫn muốn thử trên GPU hiện tại, thêm `--skip_gpu_preflight` để bỏ qua kiểm tra này.",
181
+ ]
182
+ )
183
+ raise SystemExit("\n".join(lines))
184
+
185
+
186
+ def raise_cuda_oom(args) -> None:
187
+ gpu_memory = query_gpu_memory()
188
+ lines = ["Train thất bại do CUDA out of memory."]
189
+ if gpu_memory is not None:
190
+ lines.append(
191
+ f"VRAM hiện tại: free {format_memory_mb(gpu_memory['free_mb'])}, used {format_memory_mb(gpu_memory['used_mb'])}, total {format_memory_mb(gpu_memory['total_mb'])}."
192
+ )
193
+ append_process_lines(lines, "Các tiến trình khác đang dùng GPU:", active_gpu_processes())
194
+ lines.extend(
195
+ [
196
+ "Gợi ý:",
197
+ "- Dừng tiến trình CUDA khác rồi chạy lại.",
198
+ f"- Hoặc chạy trên CPU: python fine_tune_qg.py --device cpu --output_dir {args.output_dir}-cpu",
199
+ "- Khi GPU rảnh, nếu vẫn thiếu VRAM, giảm batch: `--per_device_train_batch_size 1 --per_device_eval_batch_size 1 --gradient_accumulation_steps 16 --gradient_checkpointing`.",
200
+ ]
201
+ )
202
+ raise SystemExit("\n".join(lines))
203
+
204
+
205
+ def build_source(title: str, context: str, answer: str, task_prefix: str) -> str:
206
+ parts = [f"{task_prefix}:"]
207
+ if title:
208
+ parts.append(f"tiêu đề: {title}")
209
+ parts.extend((f"ngữ cảnh: {context}", f"đáp án: {answer}"))
210
+ return "\n".join(parts)
211
+
212
+
213
+ def load_squad_qg_examples(
214
+ file_path: str,
215
+ use_all_answers: bool = True,
216
+ task_prefix: str = "sinh câu hỏi",
217
+ require_answer_in_context: bool = False,
218
+ ) -> tuple[list[dict[str, str]], dict[str, int]]:
219
+ data = json.loads(Path(file_path).read_text(encoding="utf-8"))
220
+ examples = []
221
+ stats = {
222
+ "articles": 0,
223
+ "paragraphs": 0,
224
+ "qas": 0,
225
+ "examples": 0,
226
+ "skipped_impossible": 0,
227
+ "skipped_no_context": 0,
228
+ "skipped_no_question": 0,
229
+ "skipped_no_answers": 0,
230
+ "skipped_answer_not_in_context": 0,
231
+ "answers_not_in_context_but_kept": 0,
232
+ }
233
+
234
+ for article in data.get("data", []):
235
+ stats["articles"] += 1
236
+ title = normalize_text(article.get("title"))
237
+ for paragraph in article.get("paragraphs", []):
238
+ stats["paragraphs"] += 1
239
+ context = normalize_text(paragraph.get("context"))
240
+ if not context:
241
+ stats["skipped_no_context"] += 1
242
+ continue
243
+
244
+ for qa in paragraph.get("qas", []):
245
+ stats["qas"] += 1
246
+ question = normalize_text(qa.get("question"))
247
+ if qa.get("is_impossible", False):
248
+ stats["skipped_impossible"] += 1
249
+ continue
250
+ if not question:
251
+ stats["skipped_no_question"] += 1
252
+ continue
253
+
254
+ answers = dedupe(normalize_text(answer.get("text")) for answer in qa.get("answers", []))
255
+ if not answers:
256
+ stats["skipped_no_answers"] += 1
257
+ continue
258
+ if not use_all_answers:
259
+ answers = answers[:1]
260
+
261
+ for answer in answers:
262
+ in_context = answer in context
263
+ if require_answer_in_context and not in_context:
264
+ stats["skipped_answer_not_in_context"] += 1
265
+ continue
266
+ if not in_context:
267
+ stats["answers_not_in_context_but_kept"] += 1
268
+
269
+ examples.append(
270
+ {
271
+ "source": build_source(title, context, answer, task_prefix),
272
+ "target": question,
273
+ }
274
+ )
275
+ stats["examples"] += 1
276
+
277
+ return examples, stats
278
+
279
+
280
+ def preprocess_function(batch, tokenizer, max_source_length: int, max_target_length: int) -> dict[str, Any]:
281
+ model_inputs = tokenizer(batch["source"], max_length=max_source_length, truncation=True)
282
+ model_inputs["labels"] = tokenizer(
283
+ text_target=batch["target"],
284
+ max_length=max_target_length,
285
+ truncation=True,
286
+ )["input_ids"]
287
+ return model_inputs
288
+
289
+
290
+ def build_supported_kwargs(cls, kwargs: dict[str, Any], aliases=None) -> dict[str, Any]:
291
+ params = set(signature(cls.__init__).parameters)
292
+ aliases = aliases or {}
293
+ resolved = {}
294
+ for key, value in kwargs.items():
295
+ if value is None:
296
+ continue
297
+ target = key if key in params else aliases.get(key)
298
+ if target in params:
299
+ resolved[target] = value
300
+ return resolved
301
+
302
+
303
+ def build_training_args(args, has_eval: bool):
304
+ kwargs = {
305
+ "output_dir": args.output_dir,
306
+ "overwrite_output_dir": False,
307
+ "learning_rate": args.learning_rate,
308
+ "per_device_train_batch_size": args.per_device_train_batch_size,
309
+ "per_device_eval_batch_size": args.per_device_eval_batch_size,
310
+ "gradient_accumulation_steps": args.gradient_accumulation_steps,
311
+ "weight_decay": args.weight_decay,
312
+ "num_train_epochs": args.num_train_epochs,
313
+ "warmup_ratio": args.warmup_ratio,
314
+ "logging_strategy": "steps",
315
+ "logging_steps": args.logging_steps,
316
+ "save_strategy": args.save_strategy_type,
317
+ "save_steps": args.save_steps if args.save_strategy_type == "steps" else None,
318
+ "save_total_limit": args.save_total_limit,
319
+ "report_to": "none",
320
+ "fp16": args.fp16,
321
+ "bf16": args.bf16,
322
+ "predict_with_generate": False,
323
+ "generation_max_length": args.max_target_length,
324
+ "dataloader_num_workers": args.dataloader_num_workers,
325
+ "dataloader_pin_memory": not args.no_pin_memory,
326
+ "save_only_model": args.save_only_model,
327
+ "restore_callback_states_from_checkpoint": args.restore_callback_states_from_checkpoint,
328
+ "torch_empty_cache_steps": args.torch_empty_cache_steps or None,
329
+ "seed": args.seed,
330
+ "data_seed": args.seed if supports_data_seed() else None,
331
+ "use_cpu": True if args.device == "cpu" else None,
332
+ "gradient_checkpointing": True if args.gradient_checkpointing else None,
333
+ "load_best_model_at_end": has_eval,
334
+ "metric_for_best_model": "eval_loss" if has_eval else None,
335
+ "greater_is_better": False if has_eval else None,
336
+ "eval_strategy": args.save_strategy_type if has_eval else None,
337
+ "eval_steps": args.eval_steps if has_eval and args.save_strategy_type == "steps" else None,
338
+ }
339
+ return Seq2SeqTrainingArguments(
340
+ **build_supported_kwargs(
341
+ Seq2SeqTrainingArguments,
342
+ kwargs,
343
+ aliases={"eval_strategy": "evaluation_strategy", "use_cpu": "no_cuda"},
344
+ )
345
+ )
346
+
347
+
348
+ def resolve_resume_checkpoint(args):
349
+ if args.resume_checkpoint:
350
+ if not Path(args.resume_checkpoint).is_dir():
351
+ raise FileNotFoundError(f"Không tìm thấy resume_checkpoint: {args.resume_checkpoint}")
352
+ return args.resume_checkpoint
353
+ if args.resume_from_latest and Path(args.output_dir).is_dir():
354
+ return get_last_checkpoint(args.output_dir)
355
+ return None
356
+
357
+
358
+ def validate_args(args, has_eval: bool) -> None:
359
+ if has_eval and args.save_strategy_type == "steps":
360
+ if args.eval_steps <= 0 or args.save_steps <= 0:
361
+ raise ValueError("save_steps và eval_steps phải > 0")
362
+ if args.save_steps % args.eval_steps != 0:
363
+ raise ValueError("save_steps phải là bội số của eval_steps")
364
+ if args.save_only_model and (args.resume_from_latest or args.resume_checkpoint):
365
+ print("Cảnh báo: save_only_model sẽ không resume train đầy đủ được.")
366
+
367
+
368
+ def build_parser() -> argparse.ArgumentParser:
369
+ parser = argparse.ArgumentParser()
370
+ add = parser.add_argument
371
+
372
+ add("--train_file", default="40k_train.json")
373
+ add("--validation_file", default=None)
374
+ add("--output_dir", default="t5-viet-qg-finetuned")
375
+ add("--model_name", default="VietAI/vit5-base")
376
+ add("--task_prefix", default="sinh câu hỏi")
377
+
378
+ add("--max_source_length", type=int, default=512)
379
+ add("--max_target_length", type=int, default=64)
380
+ add("--val_ratio", type=float, default=0.1)
381
+
382
+ add("--per_device_train_batch_size", type=int, default=4)
383
+ add("--per_device_eval_batch_size", type=int, default=4)
384
+ add("--gradient_accumulation_steps", type=int, default=4)
385
+ add("--learning_rate", type=float, default=1e-4)
386
+ add("--weight_decay", type=float, default=0.01)
387
+ add("--warmup_ratio", type=float, default=0.05)
388
+ add("--num_train_epochs", type=int, default=3)
389
+ add("--logging_steps", type=int, default=50)
390
+ add("--seed", type=int, default=42)
391
+ add("--early_stopping_patience", type=int, default=2)
392
+
393
+ add("--save_strategy_type", default="steps", choices=["steps", "epoch"])
394
+ add("--save_steps", type=int, default=500)
395
+ add("--eval_steps", type=int, default=500)
396
+ add("--save_total_limit", type=int, default=1)
397
+
398
+ parser.set_defaults(resume_from_latest=True)
399
+ add("--resume_from_latest", dest="resume_from_latest", action="store_true")
400
+ add("--no_resume_from_latest", dest="resume_from_latest", action="store_false")
401
+ add("--resume_checkpoint", default=None)
402
+ add("--save_only_model", action="store_true")
403
+ add("--restore_callback_states_from_checkpoint", action="store_true")
404
+
405
+ add("--fp16", action="store_true")
406
+ add("--bf16", action="store_true")
407
+ add("--gradient_checkpointing", action="store_true")
408
+ add("--dataloader_num_workers", type=int, default=0)
409
+ add("--no_pin_memory", action="store_true")
410
+ add("--torch_empty_cache_steps", type=int, default=0)
411
+ add("--device", default="auto", choices=["auto", "cuda", "cpu"])
412
+ add("--min_free_gpu_mb", type=int, default=4096)
413
+ add("--skip_gpu_preflight", action="store_true")
414
+
415
+ add("--use_first_answer_only", action="store_true")
416
+ add("--require_answer_in_context", action="store_true")
417
+ return parser
418
+
419
+
420
+ def load_datasets(args):
421
+ load_kwargs = {
422
+ "use_all_answers": not args.use_first_answer_only,
423
+ "task_prefix": args.task_prefix,
424
+ "require_answer_in_context": args.require_answer_in_context,
425
+ }
426
+ train_examples, train_stats = load_squad_qg_examples(args.train_file, **load_kwargs)
427
+ if not train_examples:
428
+ raise ValueError("Không có dữ liệu train hợp lệ sau khi tiền xử lý.")
429
+
430
+ train_dataset = Dataset.from_list(train_examples)
431
+ val_dataset = None
432
+ val_stats = None
433
+
434
+ if args.validation_file:
435
+ val_examples, val_stats = load_squad_qg_examples(args.validation_file, **load_kwargs)
436
+ if not val_examples:
437
+ raise ValueError("Không có dữ liệu validation hợp lệ sau khi tiền xử lý.")
438
+ val_dataset = Dataset.from_list(val_examples)
439
+ elif args.val_ratio > 0 and len(train_dataset) > 10:
440
+ split = train_dataset.train_test_split(test_size=args.val_ratio, seed=args.seed)
441
+ train_dataset, val_dataset = split["train"], split["test"]
442
+
443
+ return train_dataset, val_dataset, train_stats, val_stats
444
+
445
+
446
+ def tokenize_dataset(dataset, tokenizer, args):
447
+ return dataset.map(
448
+ lambda batch: preprocess_function(batch, tokenizer, args.max_source_length, args.max_target_length),
449
+ batched=True,
450
+ remove_columns=dataset.column_names,
451
+ )
452
+
453
+
454
+ def build_trainer(model, tokenizer, training_args, train_dataset, eval_dataset, args):
455
+ kwargs = {
456
+ "model": model,
457
+ "args": training_args,
458
+ "data_collator": DataCollatorForSeq2Seq(tokenizer=tokenizer, model=model),
459
+ "train_dataset": train_dataset,
460
+ "eval_dataset": eval_dataset,
461
+ "callbacks": [EarlyStoppingCallback(early_stopping_patience=args.early_stopping_patience)]
462
+ if eval_dataset is not None
463
+ else None,
464
+ "processing_class": tokenizer,
465
+ }
466
+ return Seq2SeqTrainer(
467
+ **build_supported_kwargs(Seq2SeqTrainer, kwargs, aliases={"processing_class": "tokenizer"})
468
+ )
469
+
470
+
471
+ def main() -> None:
472
+ args = build_parser().parse_args()
473
+ output_dir = Path(args.output_dir)
474
+ output_dir.mkdir(parents=True, exist_ok=True)
475
+
476
+ set_seed(args.seed)
477
+ ensure_device_ready(args)
478
+
479
+ raw_train_dataset, raw_val_dataset, train_stats, val_stats = load_datasets(args)
480
+ has_eval = raw_val_dataset is not None
481
+ validate_args(args, has_eval)
482
+
483
+ tokenizer = AutoTokenizer.from_pretrained(args.model_name)
484
+ model = AutoModelForSeq2SeqLM.from_pretrained(args.model_name)
485
+
486
+ if args.gradient_checkpointing:
487
+ model.gradient_checkpointing_enable()
488
+ if hasattr(model.config, "use_cache"):
489
+ model.config.use_cache = False
490
+
491
+ tokenized_train = tokenize_dataset(raw_train_dataset, tokenizer, args)
492
+ tokenized_val = tokenize_dataset(raw_val_dataset, tokenizer, args) if has_eval else None
493
+ trainer = build_trainer(
494
+ model,
495
+ tokenizer,
496
+ build_training_args(args, has_eval),
497
+ tokenized_train,
498
+ tokenized_val,
499
+ args,
500
+ )
501
+
502
+ resume_checkpoint = resolve_resume_checkpoint(args)
503
+ try:
504
+ train_result = trainer.train(resume_from_checkpoint=resume_checkpoint)
505
+ except torch.OutOfMemoryError:
506
+ raise_cuda_oom(args)
507
+ except RuntimeError as exc:
508
+ if "CUDA out of memory" in str(exc):
509
+ raise_cuda_oom(args)
510
+ raise
511
+
512
+ trainer.save_state()
513
+
514
+ export_dir = output_dir / ("best-model" if has_eval else "final-model")
515
+ export_dir.mkdir(parents=True, exist_ok=True)
516
+ for path in (export_dir, output_dir):
517
+ trainer.save_model(str(path))
518
+ tokenizer.save_pretrained(str(path))
519
+
520
+ train_metrics = train_result.metrics
521
+ trainer.log_metrics("train", train_metrics)
522
+ trainer.save_metrics("train", train_metrics)
523
+
524
+ eval_metrics = None
525
+ if has_eval:
526
+ eval_metrics = trainer.evaluate(
527
+ max_length=args.max_target_length,
528
+ num_beams=4,
529
+ metric_key_prefix="eval",
530
+ )
531
+ trainer.log_metrics("eval", eval_metrics)
532
+ trainer.save_metrics("eval", eval_metrics)
533
+
534
+ save_json(
535
+ {
536
+ "base_model": args.model_name,
537
+ "task_prefix": args.task_prefix,
538
+ "output_dir": str(output_dir),
539
+ "export_dir": str(export_dir),
540
+ "train_size": len(raw_train_dataset),
541
+ "val_size": len(raw_val_dataset) if raw_val_dataset is not None else 0,
542
+ "train_stats": train_stats,
543
+ "val_stats": val_stats,
544
+ "best_model_checkpoint": trainer.state.best_model_checkpoint,
545
+ "best_metric": trainer.state.best_metric,
546
+ "resumed_from_checkpoint": resume_checkpoint,
547
+ "args": vars(args),
548
+ "train_metrics": train_metrics,
549
+ "eval_metrics": eval_metrics,
550
+ },
551
+ output_dir / "training_summary.json",
552
+ )
553
+
554
+
555
+ if __name__ == "__main__":
556
+ main()
QA/generate_question.py ADDED
@@ -0,0 +1,473 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import hashlib
5
+ import json
6
+ import os
7
+ import re
8
+ import shutil
9
+ import sys
10
+ import tempfile
11
+ import threading
12
+ import warnings
13
+ from pathlib import Path
14
+ from typing import Any
15
+
16
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
17
+ if os.environ.get("PYTORCH_CUDA_ALLOC_CONF") == "expandable_segments:True":
18
+ os.environ.pop("PYTORCH_CUDA_ALLOC_CONF", None)
19
+ os.environ.setdefault("TRANSFORMERS_NO_ADVISORY_WARNINGS", "1")
20
+ warnings.filterwarnings("ignore", message=r"You are using the default legacy behaviour.*")
21
+ warnings.filterwarnings("ignore", message=r"Special tokens have been added.*")
22
+
23
+
24
+ def raise_missing_dependency_error(exc: ModuleNotFoundError) -> None:
25
+ raise SystemExit(f"Thiếu thư viện Python: {exc.name}") from exc
26
+
27
+
28
+ try:
29
+ import torch
30
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
31
+ from transformers import logging as transformers_logging
32
+ from transformers.utils import is_torch_available
33
+ except ModuleNotFoundError as exc:
34
+ raise_missing_dependency_error(exc)
35
+
36
+ transformers_logging.set_verbosity_error()
37
+
38
+ if not is_torch_available():
39
+ raise SystemExit("Transformers không nhận PyTorch trong môi trường hiện tại.")
40
+
41
+
42
+ APP_TITLE = "HỆ THỐNG SINH CÂU HỎI"
43
+ TASK_PREFIX = "sinh câu hỏi"
44
+ QUESTION_LIMIT = 100
45
+ TOKENIZER_FILES = (
46
+ "config.json",
47
+ "special_tokens_map.json",
48
+ "spiece.model",
49
+ "tokenizer.json",
50
+ "tokenizer_config.json",
51
+ "added_tokens.json",
52
+ )
53
+ GENERATION_PASSES = (
54
+ (0.9, 0.95, None, 1, 4),
55
+ (1.0, 0.97, 16, 1, 5),
56
+ (1.08, 0.99, 8, 2, 6),
57
+ )
58
+
59
+
60
+ def normalize_text(text: Any) -> str:
61
+ return " ".join(str(text or "").split())
62
+
63
+
64
+ def unique_text(items: list[str]) -> list[str]:
65
+ seen: set[str] = set()
66
+ output: list[str] = []
67
+ for item in items:
68
+ value = normalize_text(item)
69
+ key = value.lower()
70
+ if key and key not in seen:
71
+ seen.add(key)
72
+ output.append(value)
73
+ return output
74
+
75
+
76
+ def parse_question_count(value: Any, default: int = 5) -> int:
77
+ try:
78
+ parsed = int(value)
79
+ except (TypeError, ValueError):
80
+ parsed = default
81
+ return max(1, min(parsed, QUESTION_LIMIT))
82
+
83
+
84
+ def format_questions(items: list[str]) -> str:
85
+ if not items:
86
+ return "Không sinh được câu hỏi phù hợp."
87
+ return "\n".join(f"{index}. {item}" for index, item in enumerate(items, 1))
88
+
89
+
90
+ def as_bool(value: str | None, default: bool = False) -> bool:
91
+ if value is None:
92
+ return default
93
+ return value.strip().lower() in {"1", "true", "yes", "y", "on"}
94
+
95
+
96
+ def resolve_model_dir(model_dir: str | Path, prefer_nested_model: bool = True) -> Path:
97
+ model_root = Path(model_dir).expanduser().resolve()
98
+ nested_candidates = [model_root / "best-model", model_root / "final-model"]
99
+ candidates = [*nested_candidates, model_root] if prefer_nested_model else [model_root, *nested_candidates]
100
+ for candidate in candidates:
101
+ if candidate.is_dir() and (candidate / "config.json").exists():
102
+ return candidate
103
+ raise FileNotFoundError(f"Không tìm thấy thư mục mô hình hợp lệ: {model_root}")
104
+
105
+
106
+ def path_needs_ascii_mirror(path: Path) -> bool:
107
+ try:
108
+ str(path).encode("ascii")
109
+ except UnicodeEncodeError:
110
+ return True
111
+ return False
112
+
113
+
114
+ def resolve_tokenizer_dir(model_dir: Path) -> Path:
115
+ if not path_needs_ascii_mirror(model_dir):
116
+ return model_dir
117
+
118
+ digest = hashlib.sha1(str(model_dir).encode("utf-8")).hexdigest()[:16]
119
+ cache_base = Path(os.getenv("LOCALAPPDATA") or tempfile.gettempdir())
120
+ tokenizer_dir = cache_base / "HVU_QA" / "tokenizer_cache" / digest
121
+ tokenizer_dir.mkdir(parents=True, exist_ok=True)
122
+
123
+ copied = False
124
+ for filename in TOKENIZER_FILES:
125
+ source = model_dir / filename
126
+ if not source.exists():
127
+ continue
128
+ destination = tokenizer_dir / filename
129
+ if destination.exists() and destination.stat().st_size == source.stat().st_size:
130
+ continue
131
+ shutil.copy2(source, destination)
132
+ copied = True
133
+
134
+ if copied:
135
+ marker = tokenizer_dir / "source_model_dir.txt"
136
+ marker.write_text(str(model_dir), encoding="utf-8")
137
+
138
+ return tokenizer_dir
139
+
140
+
141
+ def parse_dtype(value: str) -> torch.dtype:
142
+ normalized = value.strip().lower()
143
+ mapping = {
144
+ "float16": torch.float16,
145
+ "fp16": torch.float16,
146
+ "float32": torch.float32,
147
+ "fp32": torch.float32,
148
+ "bfloat16": torch.bfloat16,
149
+ "bf16": torch.bfloat16,
150
+ }
151
+ if normalized not in mapping:
152
+ raise ValueError(f"Không hỗ trợ gpu_dtype={value}")
153
+ return mapping[normalized]
154
+
155
+
156
+ class QuestionGenerator:
157
+ def __init__(
158
+ self,
159
+ model_dir: str | Path = "t5-viet-qg-finetuned",
160
+ task_prefix: str = TASK_PREFIX,
161
+ max_source_length: int = 512,
162
+ max_new_tokens: int = 64,
163
+ device: str = "auto",
164
+ cpu_threads: int | None = None,
165
+ gpu_dtype: str = "auto",
166
+ prefer_nested_model: bool = True,
167
+ ) -> None:
168
+ self.model_root = Path(model_dir).expanduser().resolve()
169
+ self.model_dir = resolve_model_dir(model_dir, prefer_nested_model=prefer_nested_model)
170
+ self.task_prefix = task_prefix
171
+ self.max_source_length = max_source_length
172
+ self.max_new_tokens = max_new_tokens
173
+ self.requested_device = device
174
+ self.cpu_threads = cpu_threads
175
+ self.gpu_dtype = gpu_dtype
176
+ self.prefer_nested_model = prefer_nested_model
177
+ self.device: torch.device | None = None
178
+ self.dtype: torch.dtype | None = None
179
+ self.tokenizer = None
180
+ self.model = None
181
+ self._load_lock = threading.Lock()
182
+
183
+ def _resolve_device(self) -> torch.device:
184
+ requested = self.requested_device.lower()
185
+ if requested == "cpu":
186
+ return torch.device("cpu")
187
+ if requested == "cuda":
188
+ if not torch.cuda.is_available():
189
+ raise RuntimeError("Bạn đã chọn device=cuda nhưng máy hiện tại không có CUDA.")
190
+ return torch.device("cuda")
191
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
192
+
193
+ def _resolve_dtype(self) -> torch.dtype:
194
+ if self.device is None or self.device.type != "cuda":
195
+ return torch.float32
196
+ if self.gpu_dtype == "auto":
197
+ if hasattr(torch.cuda, "is_bf16_supported") and torch.cuda.is_bf16_supported():
198
+ return torch.bfloat16
199
+ return torch.float16
200
+ return parse_dtype(self.gpu_dtype)
201
+
202
+ def _configure_runtime(self) -> None:
203
+ if self.device is None:
204
+ return
205
+ if self.device.type == "cpu":
206
+ if self.cpu_threads:
207
+ torch.set_num_threads(max(1, int(self.cpu_threads)))
208
+ if hasattr(torch, "set_num_interop_threads"):
209
+ torch.set_num_interop_threads(max(1, min(int(self.cpu_threads), 4)))
210
+ return
211
+
212
+ if hasattr(torch.backends, "cuda") and hasattr(torch.backends.cuda, "matmul"):
213
+ torch.backends.cuda.matmul.allow_tf32 = True
214
+ if hasattr(torch.backends, "cudnn"):
215
+ torch.backends.cudnn.allow_tf32 = True
216
+ torch.backends.cudnn.benchmark = True
217
+
218
+ def _load_tokenizer(self):
219
+ use_fast = as_bool(os.getenv("HVU_USE_FAST_TOKENIZER"), default=False)
220
+ tokenizer_dir = resolve_tokenizer_dir(self.model_dir)
221
+ try:
222
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=use_fast)
223
+ except Exception:
224
+ if use_fast:
225
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False)
226
+ if (tokenizer_dir / "tokenizer.json").exists():
227
+ try:
228
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=True)
229
+ except Exception:
230
+ pass
231
+ return AutoTokenizer.from_pretrained(str(tokenizer_dir), use_fast=False)
232
+
233
+ def load(self) -> None:
234
+ if self.model is not None and self.tokenizer is not None:
235
+ return
236
+
237
+ with self._load_lock:
238
+ if self.model is not None and self.tokenizer is not None:
239
+ return
240
+
241
+ self.device = self._resolve_device()
242
+ self.dtype = self._resolve_dtype()
243
+ self._configure_runtime()
244
+
245
+ model_kwargs: dict[str, Any] = {}
246
+ if self.device.type == "cuda":
247
+ model_kwargs["torch_dtype"] = self.dtype
248
+ model_kwargs["low_cpu_mem_usage"] = True
249
+
250
+ self.tokenizer = self._load_tokenizer()
251
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(str(self.model_dir), **model_kwargs)
252
+ self.model.to(self.device)
253
+ self.model.eval()
254
+
255
+ def metadata(self) -> dict[str, Any]:
256
+ active_device = self.device.type if self.device is not None else None
257
+ predicted_device = "cuda" if torch.cuda.is_available() and self.requested_device != "cpu" else "cpu"
258
+ return {
259
+ "title": APP_TITLE,
260
+ "model_root": str(self.model_root),
261
+ "model_dir": str(self.model_dir),
262
+ "requested_device": self.requested_device,
263
+ "active_device": active_device,
264
+ "predicted_device": predicted_device,
265
+ "loaded": self.model is not None,
266
+ "gpu_available": torch.cuda.is_available(),
267
+ "gpu_dtype": None if self.dtype is None else str(self.dtype).replace("torch.", ""),
268
+ "cpu_threads": torch.get_num_threads(),
269
+ }
270
+
271
+ def _candidate_answers(self, text: str, limit: int) -> list[str]:
272
+ text = normalize_text(text)
273
+ if not text:
274
+ return []
275
+
276
+ candidates: list[str] = []
277
+ split_pattern = r"(?<=[.!?])\s+|\n+"
278
+ for sentence in [normalize_text(part) for part in re.split(split_pattern, text) if normalize_text(part)]:
279
+ if 3 <= len(sentence.split()) <= 30:
280
+ candidates.append(sentence)
281
+ for clause in (normalize_text(part) for part in re.split(r"\s*[,;:]\s*", sentence)):
282
+ if 3 <= len(clause.split()) <= 20:
283
+ candidates.append(clause)
284
+
285
+ if not candidates:
286
+ words = text.split()
287
+ candidates = [" ".join(words[: min(12, len(words))])] if words else [text]
288
+
289
+ ranked = sorted(unique_text(candidates), key=lambda item: (abs(len(item.split()) - 10), len(item)))
290
+ return ranked[:limit]
291
+
292
+ def _build_prompt(self, context: str, answer: str) -> str:
293
+ return f"{self.task_prefix}:\nngữ cảnh: {context}\nđáp án: {answer}"
294
+
295
+ @torch.inference_mode()
296
+ def _sample(self, context: str, answer: str, count: int, temperature: float, top_p: float) -> list[str]:
297
+ if self.tokenizer is None or self.model is None or self.device is None:
298
+ raise RuntimeError("Model chưa được load.")
299
+
300
+ inputs = self.tokenizer(
301
+ self._build_prompt(context, answer),
302
+ return_tensors="pt",
303
+ truncation=True,
304
+ max_length=self.max_source_length,
305
+ ).to(self.device)
306
+ outputs = self.model.generate(
307
+ **inputs,
308
+ max_new_tokens=self.max_new_tokens,
309
+ do_sample=True,
310
+ temperature=temperature,
311
+ top_p=top_p,
312
+ num_return_sequences=count,
313
+ no_repeat_ngram_size=3,
314
+ repetition_penalty=1.1,
315
+ )
316
+ questions: list[str] = []
317
+ for token_ids in outputs:
318
+ question = normalize_text(self.tokenizer.decode(token_ids, skip_special_tokens=True))
319
+ if question:
320
+ questions.append(question if question.endswith("?") else f"{question}?")
321
+ return [question for question in unique_text(questions) if len(question.split()) >= 3]
322
+
323
+ @torch.inference_mode()
324
+ def _beam_search(self, context: str, answer: str, count: int) -> list[str]:
325
+ if self.tokenizer is None or self.model is None or self.device is None:
326
+ raise RuntimeError("Model chưa được load.")
327
+
328
+ inputs = self.tokenizer(
329
+ self._build_prompt(context, answer),
330
+ return_tensors="pt",
331
+ truncation=True,
332
+ max_length=self.max_source_length,
333
+ ).to(self.device)
334
+ outputs = self.model.generate(
335
+ **inputs,
336
+ max_new_tokens=self.max_new_tokens,
337
+ num_beams=max(4, count),
338
+ num_return_sequences=min(count, 4),
339
+ early_stopping=True,
340
+ no_repeat_ngram_size=3,
341
+ repetition_penalty=1.1,
342
+ )
343
+ questions: list[str] = []
344
+ for token_ids in outputs:
345
+ question = normalize_text(self.tokenizer.decode(token_ids, skip_special_tokens=True))
346
+ if question:
347
+ questions.append(question if question.endswith("?") else f"{question}?")
348
+ return [question for question in unique_text(questions) if len(question.split()) >= 3]
349
+
350
+ def generate(self, text: str, count: int = 5) -> list[str]:
351
+ self.load()
352
+ context = normalize_text(text)
353
+ if not context:
354
+ raise ValueError("Vui lòng nhập đoạn văn.")
355
+
356
+ count = parse_question_count(count)
357
+ pool = unique_text(
358
+ self._candidate_answers(context, max(32, count * 5)) + [context[:180], context[:280], context]
359
+ )
360
+ output: list[str] = []
361
+ seen: set[str] = set()
362
+
363
+ for temperature, top_p, limit, rounds, floor in GENERATION_PASSES:
364
+ answers = pool[:limit] if limit else pool
365
+ for _ in range(rounds):
366
+ for answer in answers:
367
+ remaining = count - len(output)
368
+ if remaining <= 0:
369
+ return output[:count]
370
+ sample_count = min(8, max(floor, remaining * 2))
371
+ for question in self._sample(context, answer, sample_count, temperature, top_p):
372
+ key = question.lower()
373
+ if key not in seen:
374
+ seen.add(key)
375
+ output.append(question)
376
+ if len(output) >= count:
377
+ return output[:count]
378
+
379
+ for answer in pool[: min(8, len(pool))]:
380
+ remaining = count - len(output)
381
+ if remaining <= 0:
382
+ break
383
+ for question in self._beam_search(context, answer, remaining):
384
+ key = question.lower()
385
+ if key not in seen:
386
+ seen.add(key)
387
+ output.append(question)
388
+ if len(output) >= count:
389
+ break
390
+
391
+ return output[:count]
392
+
393
+
394
+ def read_input_text(args: argparse.Namespace) -> str:
395
+ if args.text:
396
+ return args.text
397
+ if args.input_file:
398
+ return Path(args.input_file).read_text(encoding="utf-8")
399
+ if sys.stdin.isatty():
400
+ return input("Nhập đoạn văn cần sinh câu hỏi:\n").strip()
401
+ return sys.stdin.read().strip()
402
+
403
+
404
+ def read_question_count(args: argparse.Namespace) -> int:
405
+ if args.num_questions is not None:
406
+ return parse_question_count(args.num_questions)
407
+ if args.text or args.input_file or not sys.stdin.isatty():
408
+ return parse_question_count(None)
409
+
410
+ while True:
411
+ raw_value = input(f"Nhập số lượng câu hỏi cần sinh (1-{QUESTION_LIMIT}): ").strip()
412
+ if not raw_value:
413
+ print("Vui lòng nhập số lượng câu hỏi cần sinh.")
414
+ continue
415
+ try:
416
+ parsed = int(raw_value)
417
+ except ValueError:
418
+ print("Vui lòng nhập một số nguyên.")
419
+ continue
420
+ if 1 <= parsed <= QUESTION_LIMIT:
421
+ return parsed
422
+ print(f"Số lượng câu hỏi phải nằm trong khoảng 1 đến {QUESTION_LIMIT}.")
423
+
424
+
425
+ def build_parser() -> argparse.ArgumentParser:
426
+ parser = argparse.ArgumentParser()
427
+ parser.add_argument("--model_dir", default="t5-viet-qg-finetuned")
428
+ parser.add_argument("--task_prefix", default=TASK_PREFIX)
429
+ parser.add_argument("--max_source_length", type=int, default=512)
430
+ parser.add_argument("--max_new_tokens", type=int, default=64)
431
+ parser.add_argument("--num_questions", type=int, default=None)
432
+ parser.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
433
+ parser.add_argument("--cpu_threads", type=int, default=None)
434
+ parser.add_argument("--gpu_dtype", default="auto")
435
+ parser.add_argument("--text", default=None)
436
+ parser.add_argument("--input_file", default=None)
437
+ parser.add_argument("--output_format", choices=["text", "json"], default="text")
438
+ return parser
439
+
440
+
441
+ def main() -> None:
442
+ if hasattr(sys.stdout, "reconfigure"):
443
+ sys.stdout.reconfigure(encoding="utf-8")
444
+ if hasattr(sys.stderr, "reconfigure"):
445
+ sys.stderr.reconfigure(encoding="utf-8")
446
+ args = build_parser().parse_args()
447
+ generator = QuestionGenerator(
448
+ model_dir=args.model_dir,
449
+ task_prefix=args.task_prefix,
450
+ max_source_length=args.max_source_length,
451
+ max_new_tokens=args.max_new_tokens,
452
+ device=args.device,
453
+ cpu_threads=args.cpu_threads,
454
+ gpu_dtype=args.gpu_dtype,
455
+ prefer_nested_model=True,
456
+ )
457
+ text = read_input_text(args)
458
+ question_count = read_question_count(args)
459
+ questions = generator.generate(text, question_count)
460
+ payload = {
461
+ "text": normalize_text(text),
462
+ "questions": questions,
463
+ "formatted": format_questions(questions),
464
+ "meta": generator.metadata(),
465
+ }
466
+ if args.output_format == "json":
467
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
468
+ return
469
+ print(payload["formatted"])
470
+
471
+
472
+ if __name__ == "__main__":
473
+ main()
QA/main.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ import threading
5
+ import webbrowser
6
+
7
+ from backend import create_app
8
+
9
+ app = create_app()
10
+
11
+
12
+ def _as_bool(value: str | None, default: bool) -> bool:
13
+ if value is None:
14
+ return default
15
+ return value.strip().lower() not in {"0", "false", "no", "off"}
16
+
17
+
18
+ def _open_browser_later(host: str, port: int) -> None:
19
+ if not _as_bool(os.getenv("HVU_OPEN_BROWSER"), True):
20
+ return
21
+ target_host = "127.0.0.1" if host in {"0.0.0.0", "::"} else host
22
+ url = f"http://{target_host}:{port}"
23
+ threading.Timer(1.2, lambda: webbrowser.open(url)).start()
24
+
25
+
26
+ if __name__ == "__main__":
27
+ host = os.getenv("HVU_HOST", "127.0.0.1")
28
+ port = int(os.getenv("HVU_PORT", "5000"))
29
+ debug = _as_bool(os.getenv("HVU_DEBUG"), False)
30
+ _open_browser_later(host, port)
31
+ app.run(host=host, port=port, debug=debug, use_reloader=False)
QA/requirements.txt ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Runtime + training dependencies for HVU_QA.
2
+ # Nếu dùng NVIDIA GPU, hãy cài bản torch đúng với CUDA của máy theo hướng dẫn chính thức của PyTorch.
3
+ accelerate>=1.1.0,<2.0.0
4
+ datasets>=2.19.0,<4.0.0
5
+ Flask>=3.0.0,<4.0.0
6
+ huggingface_hub>=0.23.0,<1.0.0
7
+ numpy>=1.26.0,<2.0.0
8
+ safetensors>=0.4.3,<1.0.0
9
+ sentencepiece>=0.2.0,<1.0.0
10
+ torch>=2.2.0,<3.0.0
11
+ transformers>=4.41.0,<4.42.0