DANGDOCAO commited on
Commit
3f33bda
·
verified ·
1 Parent(s): a11a98b

Update README.md

Browse files
Files changed (1) hide show
  1. HVU_QA/generate_question.py +438 -0
HVU_QA/generate_question.py ADDED
@@ -0,0 +1,438 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import json
5
+ import os
6
+ import re
7
+ import sys
8
+ import threading
9
+ import warnings
10
+ from pathlib import Path
11
+ from typing import Any
12
+
13
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
14
+ if os.environ.get("PYTORCH_CUDA_ALLOC_CONF") == "expandable_segments:True":
15
+ os.environ.pop("PYTORCH_CUDA_ALLOC_CONF", None)
16
+ os.environ.setdefault("TRANSFORMERS_NO_ADVISORY_WARNINGS", "1")
17
+ warnings.filterwarnings("ignore", message=r"You are using the default legacy behaviour.*")
18
+ warnings.filterwarnings("ignore", message=r"Special tokens have been added.*")
19
+
20
+
21
+ def raise_missing_dependency_error(exc: ModuleNotFoundError) -> None:
22
+ root = Path(__file__).resolve().parent
23
+ requirements = root / "requirements.txt"
24
+ message = [
25
+ f"Thiếu thư viện Python: {exc.name}",
26
+ f"Interpreter hiện tại: {sys.executable}",
27
+ ]
28
+ if requirements.exists():
29
+ message.extend(
30
+ [
31
+ "Cài đặt dependencies bằng lệnh:",
32
+ f"{sys.executable} -m pip install -r {requirements}",
33
+ ]
34
+ )
35
+ raise SystemExit("\n".join(message)) from exc
36
+
37
+
38
+ try:
39
+ import torch
40
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
41
+ from transformers import logging as transformers_logging
42
+ from transformers.utils import is_torch_available
43
+ except ModuleNotFoundError as exc:
44
+ raise_missing_dependency_error(exc)
45
+
46
+ transformers_logging.set_verbosity_error()
47
+
48
+ if not is_torch_available():
49
+ raise SystemExit(
50
+ "Transformers không nhận PyTorch trong môi trường hiện tại. "
51
+ "Nếu dùng GPU đời cũ với torch 2.0.1+cu117, hãy dùng transformers>=4.41.0,<4.42.0 "
52
+ "và numpy>=1.26.0,<2.0.0."
53
+ )
54
+
55
+
56
+ APP_TITLE = "Mô hình sinh câu hỏi thường gặp"
57
+ TASK_PREFIX = "sinh câu hỏi"
58
+ QUESTION_LIMIT = 100
59
+ GENERATION_PASSES = (
60
+ (0.9, 0.95, None, 1, 4),
61
+ (1.0, 0.97, 16, 1, 5),
62
+ (1.08, 0.99, 8, 2, 6),
63
+ )
64
+
65
+
66
+ def normalize_text(text: Any) -> str:
67
+ return " ".join(str(text or "").split())
68
+
69
+
70
+ def unique_text(items: list[str]) -> list[str]:
71
+ seen: set[str] = set()
72
+ output: list[str] = []
73
+ for item in items:
74
+ value = normalize_text(item)
75
+ key = value.lower()
76
+ if key and key not in seen:
77
+ seen.add(key)
78
+ output.append(value)
79
+ return output
80
+
81
+
82
+ def parse_question_count(value: Any, default: int = 5) -> int:
83
+ try:
84
+ parsed = int(value)
85
+ except (TypeError, ValueError):
86
+ parsed = default
87
+ return max(1, min(parsed, QUESTION_LIMIT))
88
+
89
+
90
+ def format_questions(items: list[str]) -> str:
91
+ if not items:
92
+ return "Không sinh được câu hỏi phù hợp."
93
+ return "\n".join(f"{index}. {item}" for index, item in enumerate(items, 1))
94
+
95
+
96
+ def as_bool(value: str | None, default: bool = False) -> bool:
97
+ if value is None:
98
+ return default
99
+ return value.strip().lower() in {"1", "true", "yes", "y", "on"}
100
+
101
+
102
+ def resolve_model_dir(model_dir: str | Path, prefer_nested_model: bool = True) -> Path:
103
+ model_root = Path(model_dir).expanduser().resolve()
104
+ nested_candidates = [model_root / "best-model", model_root / "final-model"]
105
+ candidates = [*nested_candidates, model_root] if prefer_nested_model else [model_root, *nested_candidates]
106
+ for candidate in candidates:
107
+ if candidate.is_dir() and (candidate / "config.json").exists():
108
+ return candidate
109
+ raise FileNotFoundError(f"Không tìm thấy thư mục mô hình hợp lệ: {model_root}")
110
+
111
+
112
+ def parse_dtype(value: str) -> torch.dtype:
113
+ normalized = value.strip().lower()
114
+ mapping = {
115
+ "float16": torch.float16,
116
+ "fp16": torch.float16,
117
+ "float32": torch.float32,
118
+ "fp32": torch.float32,
119
+ "bfloat16": torch.bfloat16,
120
+ "bf16": torch.bfloat16,
121
+ }
122
+ if normalized not in mapping:
123
+ raise ValueError(f"Không hỗ trợ gpu_dtype={value}")
124
+ return mapping[normalized]
125
+
126
+
127
+ class QuestionGenerator:
128
+ def __init__(
129
+ self,
130
+ model_dir: str | Path = "t5-viet-qg-finetuned",
131
+ task_prefix: str = TASK_PREFIX,
132
+ max_source_length: int = 512,
133
+ max_new_tokens: int = 64,
134
+ device: str = "auto",
135
+ cpu_threads: int | None = None,
136
+ gpu_dtype: str = "auto",
137
+ prefer_nested_model: bool = True,
138
+ ) -> None:
139
+ self.model_root = Path(model_dir).expanduser().resolve()
140
+ self.model_dir = resolve_model_dir(model_dir, prefer_nested_model=prefer_nested_model)
141
+ self.task_prefix = task_prefix
142
+ self.max_source_length = max_source_length
143
+ self.max_new_tokens = max_new_tokens
144
+ self.requested_device = device
145
+ self.cpu_threads = cpu_threads
146
+ self.gpu_dtype = gpu_dtype
147
+ self.prefer_nested_model = prefer_nested_model
148
+ self.device: torch.device | None = None
149
+ self.dtype: torch.dtype | None = None
150
+ self.tokenizer = None
151
+ self.model = None
152
+ self._load_lock = threading.Lock()
153
+
154
+ def _resolve_device(self) -> torch.device:
155
+ requested = self.requested_device.lower()
156
+ if requested == "cpu":
157
+ return torch.device("cpu")
158
+ if requested == "cuda":
159
+ if not torch.cuda.is_available():
160
+ raise RuntimeError("Bạn đã chọn device=cuda nhưng máy hiện tại không có CUDA.")
161
+ return torch.device("cuda")
162
+ return torch.device("cuda" if torch.cuda.is_available() else "cpu")
163
+
164
+ def _resolve_dtype(self) -> torch.dtype:
165
+ if self.device is None or self.device.type != "cuda":
166
+ return torch.float32
167
+ if self.gpu_dtype == "auto":
168
+ if hasattr(torch.cuda, "is_bf16_supported") and torch.cuda.is_bf16_supported():
169
+ return torch.bfloat16
170
+ return torch.float16
171
+ return parse_dtype(self.gpu_dtype)
172
+
173
+ def _configure_runtime(self) -> None:
174
+ if self.device is None:
175
+ return
176
+ if self.device.type == "cpu":
177
+ if self.cpu_threads:
178
+ torch.set_num_threads(max(1, int(self.cpu_threads)))
179
+ if hasattr(torch, "set_num_interop_threads"):
180
+ torch.set_num_interop_threads(max(1, min(int(self.cpu_threads), 4)))
181
+ return
182
+
183
+ if hasattr(torch.backends, "cuda") and hasattr(torch.backends.cuda, "matmul"):
184
+ torch.backends.cuda.matmul.allow_tf32 = True
185
+ if hasattr(torch.backends, "cudnn"):
186
+ torch.backends.cudnn.allow_tf32 = True
187
+ torch.backends.cudnn.benchmark = True
188
+
189
+ def _load_tokenizer(self):
190
+ use_fast = as_bool(os.getenv("HVU_USE_FAST_TOKENIZER"), default=False)
191
+ try:
192
+ return AutoTokenizer.from_pretrained(str(self.model_dir), use_fast=use_fast)
193
+ except Exception:
194
+ if not use_fast:
195
+ raise
196
+ return AutoTokenizer.from_pretrained(str(self.model_dir), use_fast=False)
197
+
198
+ def load(self) -> None:
199
+ if self.model is not None and self.tokenizer is not None:
200
+ return
201
+
202
+ with self._load_lock:
203
+ if self.model is not None and self.tokenizer is not None:
204
+ return
205
+
206
+ self.device = self._resolve_device()
207
+ self.dtype = self._resolve_dtype()
208
+ self._configure_runtime()
209
+
210
+ model_kwargs: dict[str, Any] = {}
211
+ if self.device.type == "cuda":
212
+ model_kwargs["torch_dtype"] = self.dtype
213
+ model_kwargs["low_cpu_mem_usage"] = True
214
+
215
+ self.tokenizer = self._load_tokenizer()
216
+ self.model = AutoModelForSeq2SeqLM.from_pretrained(str(self.model_dir), **model_kwargs)
217
+ self.model.to(self.device)
218
+ self.model.eval()
219
+
220
+ def metadata(self) -> dict[str, Any]:
221
+ active_device = self.device.type if self.device is not None else None
222
+ predicted_device = "cuda" if torch.cuda.is_available() and self.requested_device != "cpu" else "cpu"
223
+ return {
224
+ "title": APP_TITLE,
225
+ "model_root": str(self.model_root),
226
+ "model_dir": str(self.model_dir),
227
+ "requested_device": self.requested_device,
228
+ "active_device": active_device,
229
+ "predicted_device": predicted_device,
230
+ "loaded": self.model is not None,
231
+ "gpu_available": torch.cuda.is_available(),
232
+ "gpu_dtype": None if self.dtype is None else str(self.dtype).replace("torch.", ""),
233
+ "cpu_threads": torch.get_num_threads(),
234
+ }
235
+
236
+ def _candidate_answers(self, text: str, limit: int) -> list[str]:
237
+ text = normalize_text(text)
238
+ if not text:
239
+ return []
240
+
241
+ candidates: list[str] = []
242
+ split_pattern = r"(?<=[.!?])\s+|\n+"
243
+ for sentence in [normalize_text(part) for part in re.split(split_pattern, text) if normalize_text(part)]:
244
+ if 3 <= len(sentence.split()) <= 30:
245
+ candidates.append(sentence)
246
+ for clause in (normalize_text(part) for part in re.split(r"\s*[,;:]\s*", sentence)):
247
+ if 3 <= len(clause.split()) <= 20:
248
+ candidates.append(clause)
249
+
250
+ if not candidates:
251
+ words = text.split()
252
+ candidates = [" ".join(words[: min(12, len(words))])] if words else [text]
253
+
254
+ ranked = sorted(unique_text(candidates), key=lambda item: (abs(len(item.split()) - 10), len(item)))
255
+ return ranked[:limit]
256
+
257
+ def _build_prompt(self, context: str, answer: str) -> str:
258
+ return f"{self.task_prefix}:\nngữ cảnh: {context}\nđáp án: {answer}"
259
+
260
+ @torch.inference_mode()
261
+ def _sample(self, context: str, answer: str, count: int, temperature: float, top_p: float) -> list[str]:
262
+ if self.tokenizer is None or self.model is None or self.device is None:
263
+ raise RuntimeError("Model chưa được load.")
264
+
265
+ inputs = self.tokenizer(
266
+ self._build_prompt(context, answer),
267
+ return_tensors="pt",
268
+ truncation=True,
269
+ max_length=self.max_source_length,
270
+ ).to(self.device)
271
+ outputs = self.model.generate(
272
+ **inputs,
273
+ max_new_tokens=self.max_new_tokens,
274
+ do_sample=True,
275
+ temperature=temperature,
276
+ top_p=top_p,
277
+ num_return_sequences=count,
278
+ no_repeat_ngram_size=3,
279
+ repetition_penalty=1.1,
280
+ )
281
+ questions: list[str] = []
282
+ for token_ids in outputs:
283
+ question = normalize_text(self.tokenizer.decode(token_ids, skip_special_tokens=True))
284
+ if question:
285
+ questions.append(question if question.endswith("?") else f"{question}?")
286
+ return [question for question in unique_text(questions) if len(question.split()) >= 3]
287
+
288
+ @torch.inference_mode()
289
+ def _beam_search(self, context: str, answer: str, count: int) -> list[str]:
290
+ if self.tokenizer is None or self.model is None or self.device is None:
291
+ raise RuntimeError("Model chưa được load.")
292
+
293
+ inputs = self.tokenizer(
294
+ self._build_prompt(context, answer),
295
+ return_tensors="pt",
296
+ truncation=True,
297
+ max_length=self.max_source_length,
298
+ ).to(self.device)
299
+ outputs = self.model.generate(
300
+ **inputs,
301
+ max_new_tokens=self.max_new_tokens,
302
+ num_beams=max(4, count),
303
+ num_return_sequences=min(count, 4),
304
+ early_stopping=True,
305
+ no_repeat_ngram_size=3,
306
+ repetition_penalty=1.1,
307
+ )
308
+ questions: list[str] = []
309
+ for token_ids in outputs:
310
+ question = normalize_text(self.tokenizer.decode(token_ids, skip_special_tokens=True))
311
+ if question:
312
+ questions.append(question if question.endswith("?") else f"{question}?")
313
+ return [question for question in unique_text(questions) if len(question.split()) >= 3]
314
+
315
+ def generate(self, text: str, count: int = 5) -> list[str]:
316
+ self.load()
317
+ context = normalize_text(text)
318
+ if not context:
319
+ raise ValueError("Vui lòng nhập đoạn văn.")
320
+
321
+ count = parse_question_count(count)
322
+ pool = unique_text(
323
+ self._candidate_answers(context, max(32, count * 5)) + [context[:180], context[:280], context]
324
+ )
325
+ output: list[str] = []
326
+ seen: set[str] = set()
327
+
328
+ for temperature, top_p, limit, rounds, floor in GENERATION_PASSES:
329
+ answers = pool[:limit] if limit else pool
330
+ for _ in range(rounds):
331
+ for answer in answers:
332
+ remaining = count - len(output)
333
+ if remaining <= 0:
334
+ return output[:count]
335
+ sample_count = min(8, max(floor, remaining * 2))
336
+ for question in self._sample(context, answer, sample_count, temperature, top_p):
337
+ key = question.lower()
338
+ if key not in seen:
339
+ seen.add(key)
340
+ output.append(question)
341
+ if len(output) >= count:
342
+ return output[:count]
343
+
344
+ for answer in pool[: min(8, len(pool))]:
345
+ remaining = count - len(output)
346
+ if remaining <= 0:
347
+ break
348
+ for question in self._beam_search(context, answer, remaining):
349
+ key = question.lower()
350
+ if key not in seen:
351
+ seen.add(key)
352
+ output.append(question)
353
+ if len(output) >= count:
354
+ break
355
+
356
+ return output[:count]
357
+
358
+
359
+ def read_input_text(args: argparse.Namespace) -> str:
360
+ if args.text:
361
+ return args.text
362
+ if args.input_file:
363
+ return Path(args.input_file).read_text(encoding="utf-8")
364
+ if sys.stdin.isatty():
365
+ return input("Nhập đoạn văn cần sinh câu hỏi:\n").strip()
366
+ return sys.stdin.read().strip()
367
+
368
+
369
+ def read_question_count(args: argparse.Namespace) -> int:
370
+ if args.num_questions is not None:
371
+ return parse_question_count(args.num_questions)
372
+ if args.text or args.input_file or not sys.stdin.isatty():
373
+ return parse_question_count(None)
374
+
375
+ while True:
376
+ raw_value = input(f"Nhập số lượng câu hỏi cần sinh (1-{QUESTION_LIMIT}): ").strip()
377
+ if not raw_value:
378
+ print("Vui lòng nhập số lượng câu hỏi cần sinh.")
379
+ continue
380
+ try:
381
+ parsed = int(raw_value)
382
+ except ValueError:
383
+ print("Vui lòng nhập một số nguyên.")
384
+ continue
385
+ if 1 <= parsed <= QUESTION_LIMIT:
386
+ return parsed
387
+ print(f"Số lượng câu hỏi phải nằm trong khoảng 1 đến {QUESTION_LIMIT}.")
388
+
389
+
390
+ def build_parser() -> argparse.ArgumentParser:
391
+ parser = argparse.ArgumentParser(description="Sinh câu hỏi từ đoạn văn bằng model T5 fine-tuned.")
392
+ parser.add_argument("--model_dir", default="t5-viet-qg-finetuned")
393
+ parser.add_argument("--task_prefix", default=TASK_PREFIX)
394
+ parser.add_argument("--max_source_length", type=int, default=512)
395
+ parser.add_argument("--max_new_tokens", type=int, default=64)
396
+ parser.add_argument("--num_questions", type=int, default=None)
397
+ parser.add_argument("--device", choices=["auto", "cpu", "cuda"], default="auto")
398
+ parser.add_argument("--cpu_threads", type=int, default=None)
399
+ parser.add_argument("--gpu_dtype", default="auto")
400
+ parser.add_argument("--text", default=None)
401
+ parser.add_argument("--input_file", default=None)
402
+ parser.add_argument("--output_format", choices=["text", "json"], default="text")
403
+ return parser
404
+
405
+
406
+ def main() -> None:
407
+ if hasattr(sys.stdout, "reconfigure"):
408
+ sys.stdout.reconfigure(encoding="utf-8")
409
+ if hasattr(sys.stderr, "reconfigure"):
410
+ sys.stderr.reconfigure(encoding="utf-8")
411
+ args = build_parser().parse_args()
412
+ generator = QuestionGenerator(
413
+ model_dir=args.model_dir,
414
+ task_prefix=args.task_prefix,
415
+ max_source_length=args.max_source_length,
416
+ max_new_tokens=args.max_new_tokens,
417
+ device=args.device,
418
+ cpu_threads=args.cpu_threads,
419
+ gpu_dtype=args.gpu_dtype,
420
+ prefer_nested_model=True,
421
+ )
422
+ text = read_input_text(args)
423
+ question_count = read_question_count(args)
424
+ questions = generator.generate(text, question_count)
425
+ payload = {
426
+ "text": normalize_text(text),
427
+ "questions": questions,
428
+ "formatted": format_questions(questions),
429
+ "meta": generator.metadata(),
430
+ }
431
+ if args.output_format == "json":
432
+ print(json.dumps(payload, ensure_ascii=False, indent=2))
433
+ return
434
+ print(payload["formatted"])
435
+
436
+
437
+ if __name__ == "__main__":
438
+ main()