"""T-24 — Hợp nhất các tầng nhãn và xuất tập huấn luyện Model A. Ưu tiên theo từng head: human > planner > llm > rule. Planner chỉ được dùng cho intent/problem_type, hai head đã vượt nguồn nhãn cũ trên tập người soát. Tập TEST chỉ giữ nhãn `human` hoặc `llm` — không lấy nhãn luật thô làm chuẩn chấm điểm, nếu không mọi con số F1 sẽ là ảo. """ from __future__ import annotations import argparse from collections import Counter, defaultdict from typing import Any, Dict, List, Optional from ..common.config import add_config_args, load_config from ..common.io_utils import iter_jsonl, load_json, write_jsonl from ..common.logging_utils import Timer, get_logger from ..common.schema import Slot from .slot_tagger_rules import to_bio from .weak_label import label_routes from .word_segment import commit_cache, init_cache, segment LOG = get_logger("build_nlu_dataset") HEADS = ("domain", "intent", "problem_type", "next_action", "can_answer", "retrieval_routes", "missing_slots") PRIORITY = {"human": 4, "planner": 3, "llm": 2, "rule": 1} PLANNER_HEADS = {"intent", "problem_type"} # Ngưỡng để LOẠI một nguồn nhãn khỏi một head, căn cứ artifacts/label_agreement.json. # Chỉ loại khi có đủ mẫu đối chứng VÀ chênh lệch κ đủ lớn để không phải nhiễu. MIN_N_FOR_DEMOTION = 100 MIN_KAPPA_MARGIN = 0.05 def load_head_blocklist(cfg) -> Dict[str, set]: """Đọc kết luận κ và trả về {head: {nguồn bị loại}}. Đo trên 500 mẫu người soát: κ(Qwen, intent) = 0,209 so với κ(luật) = 0,449. Nhãn `intent` của Qwen chỉ đúng 27,4% — tệ hơn ngẫu nhiên có cấu trúc, nên đưa vào huấn luyện là đầu độc dữ liệu. Ở đây loại hẳn thay vì chỉ hạ ưu tiên. """ agree = load_json(f"{cfg['artifacts']['dir']}/label_agreement.json", default=None) block: Dict[str, set] = {} if not agree: LOG.warning("Chưa có label_agreement.json — dùng ưu tiên mặc định human>llm>rule. " "Chạy `python -m src.preprocessing.build_gold_eval agreement` trước.") return block for head, v in agree.items(): k_r, k_l = v.get("kappa_rule", 0.0), v.get("kappa_llm", 0.0) n_r, n_l = v.get("n_rule", 0), v.get("n_llm", 0) if n_r >= MIN_N_FOR_DEMOTION and (k_r - k_l) >= MIN_KAPPA_MARGIN: block.setdefault(head, set()).add("llm") LOG.warning("LOẠI nhãn LLM khỏi head `%s`: κ(llm)=%.3f < κ(rule)=%.3f (n=%d).", head, k_l, k_r, n_r) elif n_l >= MIN_N_FOR_DEMOTION and (k_l - k_r) >= MIN_KAPPA_MARGIN and n_r >= MIN_N_FOR_DEMOTION: block.setdefault(head, set()).add("rule") LOG.warning("LOẠI nhãn luật khỏi head `%s`: κ(rule)=%.3f < κ(llm)=%.3f (n=%d).", head, k_r, k_l, n_l) return block def _index(path: str, source: str) -> Dict[str, Dict[str, Any]]: out: Dict[str, Dict[str, Any]] = {} try: for row in iter_jsonl(path): row["_source"] = source out[str(row["doc_id"])] = row except FileNotFoundError: LOG.warning("Không có %s — bỏ qua nguồn '%s'.", path, source) return out def merge_row(rule: Optional[Dict[str, Any]], llm: Optional[Dict[str, Any]], human: Optional[Dict[str, Any]], block: Optional[Dict[str, set]] = None, planner: Optional[Dict[str, Any]] = None) -> Dict[str, Any]: """Trộn theo từng head, ghi rõ nguồn của mỗi nhãn. `block` = {head: {nguồn bị loại}} do `load_head_blocklist` tính từ κ thật. """ block = block or {} base = rule or llm or human or {} out: Dict[str, Any] = { "doc_id": base.get("doc_id"), "text": base.get("text", ""), "send_date": base.get("send_date"), "slots": (rule or {}).get("slots", []), "label_source": {}, } for head in HEADS: chosen_val, chosen_src, chosen_prio = None, None, 0 candidates = [("rule", rule), ("llm", llm), ("human", human)] if head in PLANNER_HEADS: candidates.append(("planner", planner)) for src, row in candidates: if not row or src in block.get(head, ()): continue v = row.get(head) if v is None: continue if PRIORITY[src] > chosen_prio: chosen_val, chosen_src, chosen_prio = v, src, PRIORITY[src] out[head] = chosen_val if chosen_src: out["label_source"][head] = chosen_src # `retrieval_routes` là HÀM XÁC ĐỊNH của intent (xem configs/weak_rules.yaml). # Nếu intent đến từ LLM/người mà routes chưa có, suy ra luôn — nếu không head này # sẽ không có nhãn nào trong dev/test và không thể đánh giá được. if out.get("retrieval_routes") is None and out.get("intent") is not None: out["retrieval_routes"] = label_routes(out["intent"]) out["label_source"]["retrieval_routes"] = out["label_source"].get("intent", "rule") return out def build(cfg, args) -> None: init_cache(cfg["artifacts"]["seg_cache"]) sp = cfg["splits"] block = load_head_blocklist(cfg) rule = _index(sp["rule_labels"], "rule") llm = _index(sp["llm_labels"], "llm") planner = _index(sp["planner_labels"], "planner") human = _index(sp["gold_500"], "human") LOG.info("Nguồn nhãn: rule=%d | llm=%d | planner=%d | human=%d", len(rule), len(llm), len(planner), len(human)) if not rule and not llm: raise SystemExit("Chưa có nhãn nào. Chạy: python -m src.preprocessing.weak_label") man = load_json(sp["manifest"], default=None) if not man: raise SystemExit("Chưa có split_manifest.json. Chạy: python -m src.preprocessing.temporal_split") assignment: Dict[str, str] = man["assignment"] all_ids = set(rule) | set(llm) | set(planner) | set(human) buckets: Dict[str, List[Dict[str, Any]]] = defaultdict(list) src_stats: Dict[str, Counter] = {h: Counter() for h in HEADS} cover: Dict[str, Counter] = {s: Counter() for s in ("train", "dev", "test")} n_seg = 0 for doc_id in all_ids: row = merge_row(rule.get(doc_id), llm.get(doc_id), human.get(doc_id), block, planner=planner.get(doc_id)) split = assignment.get(doc_id, "train") # Tập dev/test dùng để CHẤM ĐIỂM -> chỉ chấp nhận nhãn đã qua LLM hoặc người. if split in ("dev", "test") and not args.allow_rule_in_eval: for head in HEADS: if row["label_source"].get(head) == "rule": row[head] = None row["label_source"].pop(head, None) if all(row.get(h) is None for h in ("intent", "next_action", "domain")): continue # không còn nhãn đáng tin -> bỏ khỏi tập đánh giá # Suy lại routes SAU khi đã loại nhãn luật: routes là hàm xác định của # intent, nên nếu intent còn đáng tin thì routes cũng đáng tin. if row.get("retrieval_routes") is None and row.get("intent") is not None: row["retrieval_routes"] = label_routes(row["intent"]) row["label_source"]["retrieval_routes"] = row["label_source"]["intent"] text = row.get("text") or "" if not text: continue row["text_seg"] = segment(text) n_seg += 1 slots = [Slot(**s) if isinstance(s, dict) else s for s in row.get("slots", [])] row["bio"] = to_bio(row["text_seg"], slots) if slots else None row["slots"] = [s.to_dict() if isinstance(s, Slot) else s for s in slots] for head in HEADS: if row.get(head) is not None: src_stats[head][row["label_source"].get(head, "?")] += 1 cover[split][head] += 1 buckets[split].append(row) if n_seg % 20000 == 0: LOG.info("… đã segment %d mẫu", n_seg) commit_cache() commit_cache() for split in ("train", "dev", "test"): out = sp[f"nlu_{split}"] n = write_jsonl(out, buckets[split]) LOG.info("%-5s : %6d mẫu -> %s", split, n, out) # Im lặng ghi 0 dòng là cách chắc chắn nhất để hỏng ngầm ở bước sau. empty = [s_ for s_ in ("dev", "test") if not buckets[s_]] if empty and not args.allow_rule_in_eval: n_llm = len(llm) in_eval = sum(1 for d in llm if assignment.get(d) in ("dev", "test")) LOG.error("=" * 74) LOG.error("TẬP %s RỖNG — không thể đánh giá.", "/".join(empty).upper()) LOG.error("Nguyên nhân: tập dev/test chỉ nhận nhãn đã qua LLM hoặc người soát, " "nhưng mới có %d nhãn LLM và chỉ %d trong số đó rơi vào dev/test.", n_llm, in_eval) LOG.error("Cách xử lý:") LOG.error(" 1) Chạy đủ Tầng 2: make label-llm (24.000 mẫu ≈ 5 giờ, resume được)") LOG.error(" 2) Hoặc soát tay: make gold + build_gold_eval annotate") LOG.error(" 3) CHỈ để thử nhanh, KHÔNG dùng công bố kết quả:") LOG.error(" python -m src.preprocessing.build_nlu_dataset --allow-rule-in-eval") LOG.error("=" * 74) LOG.info("--- NGUỒN NHÃN THEO HEAD ---") for head in HEADS: LOG.info(" %-18s %s", head, dict(src_stats[head])) LOG.info("--- ĐỘ PHỦ THEO TẬP ---") for split in ("train", "dev", "test"): total = len(buckets[split]) or 1 LOG.info(" %-5s (n=%d): %s", split, len(buckets[split]), {h: f"{100*cover[split][h]/total:.0f}%" for h in HEADS}) def main() -> None: ap = argparse.ArgumentParser(description="T-24 hợp nhất nhãn & xuất tập huấn luyện") ap.add_argument("--allow-rule-in-eval", action="store_true", help="CHO PHÉP nhãn luật thô trong dev/test (chỉ dùng để thử nhanh, " "KHÔNG dùng khi công bố kết quả)") add_config_args(ap) args = ap.parse_args() cfg = load_config("paths", args.overrides) with Timer(LOG, "build_nlu_dataset"): build(cfg, args) if __name__ == "__main__": main()