Chương 18 — Đường ống NLP, Token hóa Dưới từ, Mô hình Chuỗi & Trích xuất Thông tin Document AI (NLP Pipelines, Tokenization & Sequence Models)
Từ Unicode NFC & Byte-BPE Fertility (VI 5.74->2.32, -59.7%), Okapi BM25 (MRR 1.000 vs 0.875) & SGNS Shifted-PMI (r=0.69) đến BPTT Vanishing (7.36e-7 vs LSTM 0.319, 100% vs 49.2% tại T=36), Token IG (Comp 0.565), BiLSTM-CRF (0% lỗi BIO, 96.4% OCR F1) & XY-Cut 2 cột (100% vs 0%).
Đơn vị học phần (
Unit ID):T1-P4-U01(Phần 4: Xử lý Ngôn ngữ Tự nhiên, Mô hình Ngôn ngữ Lớn, Hậu huấn luyện Suy luận & An toàn AI — Mục lục Phần 4)
Phòng thí nghiệm Thực chiến: Lab 10 — Xử lý Văn bản 101, Mô hình Chuỗi & Document AI Trích xuất Hồ sơ Ứng viên (nlp_docai_lab)
Truy xuất nguồn & kế thừa: Chương 02 — Đại số Tuyến tính & Giải tích Ma trận (trị riêng, bán kính phổ, chuẩn \(L_2\)), Chương 07 — Đánh giá Chống Rò rỉ & Hiệu chuẩn (group-aware split), Chương 14 — Mạng Nơ-ron & Nội tại PyTorch 2.x (autograd, cắt chuẩn gradient), Chương 15 — Autoencoder & Đóng gói An toàn (safetensors), Chương 16 — Bền vững & Giải thíchIntegrated Gradients, Chương trình gốc DSAI (R46,R47,R48& LabE46:E49), và Đề cương SOTA 2026 (Chương 18). Chương tiếp theo trong lộ trình làChương 19(Attention & Kiến trúc Transformer hiện đại).
Bốn Ca Thất bại Thực chiến Mở màn: Từ Thuế Fertility Tiếng Việt & Triệt tiêu BPTT đến Vỡ Bố cục CV 2 Cột#
Một đường ống NLP hay hệ thống Document AI trông có vẻ hoạt động tốt trên vài câu tiếng Anh mẫu có thể sụp đổ nặng nề khi bước vào sản xuất doanh nghiệp (hệ thống sàng lọc hồ sơ ATS, trợ lý ngân hàng tiếng Việt, hay truy hồi điều khoản pháp lý) vì bốn cạm bẫy kinh điển sau:
-
Ca 1 — Làm sạch Ngây thơ Phá hủy Tín hiệu & Thuế
Tokenizer FertilityTiếng Việt (Lab 10,Tests 02–04):Chuỗi tiền xử lý cũ kỹ (đổi hết sang chữ thường, xóa dấu câu, xóa số) biến dòng hồ sơ
"Senior ML Engineer | Python 3.12, C++, PyTorch 2.x | F1-score 98.4%"thành"senior ml engineer python c pytorch x f score", xóa sổ10 -> 0tín hiệu kỹ thuật và thực thể NER cốt lõi. Nghiêm trọng hơn, cùng một cụm chữ tiếng Việt có thể tồn tại dưới hai dạng bảng mã Unicode (NFD52ký tự vsNFC43ký tự); và khi dùng bộ Byte-Level BPE huấn luyện thuần tiếng Anh (|V| = 512), Tokenizer Fertility trên tiếng Việt bị đội lên5.74token/từ so với4.00token/từ của tiếng Anh (thuế1.44x, và gấp2.2x–3.0xtrên các mô hình LLM tiếng Anh đời cũ), khiến chi phí API, dung lượngKV Cachevà độ trễ prefill \(O(L^2)\) phình to gấp bội! Chuyển sang từ điển đa ngôn ngữ (|V| = 640) cắt giảm Fertility tiếng Việt xuống2.32token/từ (-59.7%) mà vẫn bảo toàn 100% giải mã không mất mát (lossless UTF-8). -
Ca 2 — Nhồi nhét Từ khóa Đánh lừa
TF-IDFCổ điển (Lab 10,Test 05):Trong bài toán tìm kiếm hồ sơ hoặc điều khoản tuân thủ (
clause iso-20022),TF-IDFtuyến tính không có cơ chế bão hòa tần suất nên một tài liệu rác lặp lại từ"bilstm"18lần có thể đè bẹp tài liệu súc tích chứa đầy đủ cả"bilstm","viterbi"và"xy-cut"(TF-IDF MRR = 0.875, Top-13/4). Áp dụngOkapi BM25(\(k_1 = 1.5, b = 0.75\)) giới hạn phần đóng góp của mỗi từ bởi tiệm cận trên \((k_1 + 1)\) và chuẩn hóa độ dài tài liệu, đạtMRR = 1.000(Top-1 = 4/4, tài liệu đúng3.27> tài liệu nhồi từ khóa2.38, tài liệu ngắn2.62> tài liệu độn dài1.06). -
Ca 3 — Sụp đổ Phụ thuộc Xa của
Vanilla RNNdo Bệnh lý GradientBPTT(Lab 10,Tests 07–09):Trên bài toán ghi nhớ tín hiệu đầu chuỗi xuyên qua \(T = 36\) bước thời gian (
Lab 10), đạo hàm ngược qua tích Jacobian củaVanilla RNN(\(\rho(\mathbf{W}_{hh}) = 0.68\)) suy giảm theo hàm mũ khiến tỷ số \(\|\partial \mathcal{L}_T/\partial \mathbf{h}_1\| / \|\partial \mathcal{L}_T/\partial \mathbf{h}_T\|\) rơi xuống7.36e-07, làm độ chính xác kiểm thử kẹt cứng ở mức đoán mò49.2%! Ngược lại, khi \(\rho = 1.45\text{–}1.60\), chuẩn gradient bùng nổ lên27.75(ratio = 18.38) đòi hỏi Cắt chuẩn Toàn cục (Global L2 Clipping, \(\tau = 1.0\)) kẹp chính xác về1.000vớicosine = 1.0000. Nhờ đường cao tốc ô nhớ cộng tính (LSTMvới \(b_f = 1.5\text{–}2.0\), tỷ số dòng gradient ô nhớ0.319) và cổng cập nhật (GRUvới \(b_z = 1.5\), ít hơn~25%trọng số hồi quy), cảLSTMlẫnGRUđều đạt100.0%trên cùng bài toán \(T = 36\). -
Ca 4 — Vỡ Bố cục CV 2 Cột (
Naive Y-Sort) & Chuyển tiếpBIOBất hợp lệ dưới Nhiễu OCR (Lab 10,Tests 11–15):Trên
24hồ sơ CV thiết kế 2 cột (Lab 10), bộ đọc PDF sắp xếp ngây thơ theo tọa độ dọcy0(Naive Y-Sort) trộn lẫn cột trái (Thông tin cá nhân, Kỹ năng, Học vấn) với cột phải (Chức danh, Công ty), khiến độ chính xác thứ tự tài liệu rơi về0.0%(Pairwise = 71.4%). Đồng thời, khi đưa chuỗi vào bộ gán nhãnBiLSTM-Softmaxđộc lập, mô hình sinh tới90lỗi chuyển tiếpBIObất hợp lệ (4.51%) trên tập sạch và57lỗi (2.86%) dưới25%nhiễu OCR<UNK>(Span F1 = 93.2%). Kết hợp cắt cột đệ quyRecursive XY-Cut(phục hồi100.0%thứ tự đọc) cùngBiLSTM-CRF(hàm phân hoạch Forward khớp duyệt vét cạn tới3.52e-07+ giải mã Viterbi) đẩySpan Exact F1lên99.1%(sạch) và96.4%(dưới25%nhiễu OCR) với đúng0.00%chuyển tiếp BIO bất hợp lệ, đóng gói an toànsafetensors(87,708 B, sai số0.0, độ trễ CPU1.59 ms/CV) và xuất JSON chuẩnPydantic v2đã ẩn danh hóa PII.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn tất Chương 18 và vượt qua trọn vẹn 16/16 bài kiểm thử của Lab 10, học viên đạt năng lực chuẩn thạc sĩ (UCL MSc Distinction) & kỹ sư NLP/Document AI thực chiến:
- Tiền xử lý Bất biến & Kinh tế học Token hóa Dưới từ: Phân biệt chính xác
NFC/NFKC, thiết kế tiền xử lý không phá tín hiệu NER/code; cài đặt từ đầuByte-Level BPE(không mất mát UTF-8, không<UNK>), phân biệt vớiWordPiecevàUnigram LM, và định lượng thuếTokenizer Fertilityđa ngôn ngữ (tác động lên chi phí API,KV Cachevà độ trễ). - Truy hồi Từ vựng Hiện đại & Biểu diễn Từ Dày đặc: Dẫn xuất phương trình bão hòa và chuẩn hóa độ dài của
Okapi BM25so vớiTF-IDF; dẫn xuất gradient giải tích củaWord2Vec SGNS, liên hệ với Định lý Phân rãShifted-PMI(Levy & Goldberg 2014) và cơ chế \(n\)-gram ký tự củaFastText. - Giải tích
BPTT, Bệnh lý Gradient & Kiến trúc Hồi quy Hiện đại: Chứng minh định lý triệt tiêu/bùng nổ gradient qua tích ma trận Jacobian, thiết kế Cắt chuẩn Toàn cục (Global Norm Clipping), dẫn xuất đường cao tốc ô nhớ cộng tính củaLSTM, tối ưu cổng cập nhật củaGRU(bao gồm lưu ý dấu cổngz_ttrong PyTorchnn.GRU), cùng các biến thểBi-RNN,Deep RNN,CNN-LSTMvà cầu nối tớiLinear RNN / SSM (Mamba-2, xLSTM). - Phân loại Văn bản & Giải thích Văn bản Trung thực (
Text XAI): So sánhLIMEvớiToken Integrated Gradientsbằng cầu phương ghép Gauss–Legendre vector hóa; kiểm chứng tiên đề Completeness và hai thước đo trung thựcERASER(Comprehensiveness,Sufficiency) chống ảo giác giải thích. - Trích xuất Thông tin (
IE),BiLSTM-CRF& Document AI Đa phương thức SOTA 2026: Nắm vững quy trìnhPOS/NERvà bất biến ngữ phápBIO/BIOES; dẫn xuất và tự cài đặt thuật toán Forward log-sum-exp \(O(TK^2)\) cùng giải mã Viterbi choLinearChainCRF; nắm vững đánh giáSpan-Level Exact F1(seqeval), kiến trúc zero-shotGLiNER, và giải quyết lỗi bố cục đa cột bằngXY-Cut,LayoutLMv3vàDocling/VLMkết hợpPydantic v2+safetensors.
Truy xuất Nguồn (Syllabus & Raw Curriculum Traceability)#
Thành phần Chương trình Nguồn (R46–R48 & E46:E49) |
Nội dung Chuyên sâu trong Chương 18 | Sơ đồ / Mô phỏng Tương tác | Thực thi trong Lab 10 (nlp_docai_lab) |
|---|---|---|---|
Ngôn ngữ, Đường ống NLP & Làm sạch (R46) |
Hình vị/cú pháp/ngữ nghĩa, chuẩn hóa Unicode NFC/NFKC, bẫy xóa chữ hoa/số/dấu câu phá hủy NER & code |
Mermaid 1 |
tokenization_and_bm25.py: normalize_text_unicode, compare_cleanup_modes (Test 02) |
Token hóa & Số hóa (Numericalization) (R46) |
Byte-Level BPE, WordPiece, Unigram LM (SentencePiece), Tokenizer Fertility & thuế ngữ cảnh tiếng Việt |
Mermaid 1 + Widget 1 (bpe-tokenizer-fertility-lab) |
tokenization_and_bm25.py: ByteLevelBPETokenizer, compute_tokenizer_fertility (Tests 03, 04) |
Không gian Vector & Word Embeddings (R47) |
TF-IDF vs Okapi BM25 (bão hòa \(k_1\), chuẩn hóa độ dài \(b\)), Word2Vec SGNS, Levy–Goldberg Shifted-PMI, FastText |
Mermaid 1 |
tokenization_and_bm25.py: BM25Index, TfidfRetriever, train_word2vec_sgns, compute_shifted_pmi_matrix (Tests 05, 06) |
RNN, BPTT, Vanishing/Exploding & LSTM/GRU (R47) |
Tích Jacobian BPTT, bán kính phổ \(\rho(\mathbf{W}_{hh})\), Global Gradient Clipping, cao tốc ô nhớ LSTM (\(b_f\)), GRU (\(b_z\)), Bi-RNN, CNN-LSTM, Deep RNN |
Mermaid 1 + Widget 2 (bptt-vanishing-lstm-gate-sim) |
sequence_models.py: VanillaRNNClassifier, LSTMClassifier, GRUClassifier, CNNLSTMClassifier, measure_bptt_gradient_flow, demonstrate_gradient_clipping (Tests 07, 08, 09) |
Phân loại Văn bản & Giải thích (Text XAI) (R47) |
BiLSTM & CNN-LSTM routing, LIME vs Token Integrated Gradients (Gauss–Legendre), Completeness, ERASER (Comprehensiveness, Sufficiency) |
Mermaid 2 |
sequence_models.py: BiLSTMTextClassifier, compute_token_integrated_gradients, evaluate_text_xai_faithfulness (Test 10) |
Trích xuất Thông tin (IE), POS, NER & Resume Document AI (R48 + Lab E46:E49) |
Bất biến BIO, BiLSTM-CRF (Forward log-sum-exp + Viterbi), Span Exact F1, zero-shot GLiNER, bố cục 2 cột XY-Cut, LayoutLMv3/Docling, Pydantic v2, PII redaction & safetensors |
Mermaid 2, Mermaid 3 + Widget 3 (bilstm-crf-viterbi-resume-ie) |
resume_dataset.py & bilstm_crf_resume_ie.py: LinearChainCRF, BiLSTMCRF, BiLSTMSoftmaxTagger, xy_cut_reading_order, ResumeProfile, save_bilstm_crf_safetensors (Tests 11–16) |
Bảng Ký hiệu Phi Mơ hồ (Disambiguated Notation Contract)#
| Ký hiệu LaTeX | Miền / Kích thước | Định nghĩa chuẩn trong Chương 18 | Tên biến trong nlp_docai_lab |
|---|---|---|---|
| \(V, \|V\|, M\) | Tập từ điển, \(\mathbb{N}_+\) | Từ điển token dưới từ, kích thước từ điển (256 + M), số phép hợp nhất BPE |
vocab, vocab_size, num_merges |
| \(\mathcal{F}(\text{tok}, \mathcal{D})\) | \(\mathbb{R}_{>0}\) | Tokenizer Fertility — số subword token trung bình trên mỗi từ |
fertility_tokens_per_word |
| \(k_1, b, \operatorname{avgdl}\) | \(\mathbb{R}_{\ge 0}, [0, 1], \mathbb{R}_{>0}\) | Tham số bão hòa tần suất, chuẩn hóa độ dài & độ dài TB của Okapi BM25 |
k1, b, avgdl |
| \(\mathbf{v}_w, \mathbf{u}_c, K_{\text{neg}}\) | \(\mathbb{R}^d, \mathbb{R}^d, \mathbb{N}_+\) | Vector từ trung tâm, vector ngữ cảnh & số mẫu âm Word2Vec SGNS |
w_in, w_out, num_negatives |
| \(\mathbf{h}_t, \mathbf{c}_t, \mathbf{f}_t, \mathbf{i}_t, \mathbf{o}_t\) | \(\mathbb{R}^{d_h}\) | Trạng thái ẩn, ô nhớ, cổng quên, cổng vào và cổng ra của LSTM tại bước \(t\) |
h, c, f_t, i_t, o_t |
| \(\rho(\mathbf{W}_{hh}), \tau_{\text{clip}}\) | \(\mathbb{R}_{>0}\) | Bán kính phổ ma trận hồi quy & ngưỡng cắt chuẩn gradient toàn cục \(L_2\) | spectral_radius, max_grad_norm |
| \(\mathbf{P}, \mathbf{A}, K\) | \(\mathbb{R}^{T\times K}, \mathbb{R}^{K\times K}, \mathbb{N}_+\) | Ma trận điểm phát xạ BiLSTM, ma trận chuyển tiếp CRF & số nhãn BIO (11) |
emissions, transitions, num_tags |
| \(s(\mathbf{x}, \mathbf{y}), \log Z(\mathbf{x})\) | \(\mathbb{R}\) | Tổng điểm đường gán nhãn và log hàm phân hoạch toàn cục của CRF |
score_sequence, forward_log_partition |
| \(\operatorname{IG}_t, \operatorname{Comp}, \operatorname{Suff}\) | \(\mathbb{R}, [-1, 1]\) | Quy gán Token Integrated Gradients, độ toàn diện và độ đầy đủ (ERASER) |
token_attributions, ig_comprehensiveness, ig_sufficiency |
Trụ cột 1 — Nền tảng Toán học & Thuật toán: Token hóa, Truy hồi BM25, BPTT & BiLSTM-CRF#
1.1 Cấu trúc Ngôn ngữ, Chuẩn hóa Unicode, Byte-Level BPE & Kinh tế học Tokenizer Fertility#
Một đường ống NLP sản xuất bắt đầu bằng việc bảo toàn toàn vẹn cấu trúc biểu đạt của văn bản. Trong bộ mã Unicode, cùng một chữ tiếng Việt có dấu như ệ có thể biểu diễn bằng 1 điểm mã dựng sẵn (NFC: U+1EC7) hoặc chuỗi tổ hợp (NFD: e + U+0302 + U+0323). Nếu bỏ qua chuẩn hóa NFC trước khi token hóa, cùng một từ sẽ sinh ra hai chuỗi byte khác nhau, làm phân mảnh từ điển và giảm độ hồi tưởng truy hồi (Lab 10, Test 02: 52 ký tự NFD rút gọn về đúng 43 ký tự NFC). Ngược lại, NFKC (chuẩn hóa tương thích) chuyển các chữ toàn chiều rộng (PyTorch), chữ ghép OCR (fi \(\to\) fi) và chỉ số trên (² \(\to\) 2) về dạng chuẩn ASCII rất hiệu quả cho chỉ mục tìm kiếm, nhưng cần tránh dùng mù quáng khi xử lý công thức toán/hóa học. Quan trọng nhất: tuyệt đối không dùng làm sạch phá hủy (xóa chữ hoa, dấu câu, chữ số) cho các tác vụ NER, phân tích CV hay mã nguồn.
Để khắc phục đồng thời vấn đề từ ngoài từ điển (OOV) của token hóa cấp từ và chiều dài chuỗi bùng nổ của token hóa cấp ký tự, toàn bộ các hệ thống NLP & LLM hiện đại (2019–2026) sử dụng Token hóa Dưới từ (Subword Tokenization):
Byte-Level BPE(Radford et al. 2019 — chuẩn củaGPT-4o,Llama 3,Qwen2.5): Khởi tạo từ điển cơ sở gồm đúng256byte UTF-8 (0x00..0xFF), đảm bảo không bao giờ tồn tại<UNK>và mọi phép mã hóa/giải mã đều 100% không mất mát (decode(encode(s)) == s) trên mọi chuỗi Unicode hợp lệ. Ở mỗi bước hợp nhất \(m = 1, \dots, M\), thuật toán tìm cặp kề nhau phổ biến nhất trong các mảnh tiền token hóa (pre-tokens, không hợp nhất băng qua ranh giới khoảng trắng):\[(a^*, b^*) = \arg\max_{(a, b)} \sum_{w \in \mathcal{C}} \operatorname{freq}(w)\,\operatorname{count}_{(a, b)}(w),\]gán mã mới \(\text{id} = 256 + m - 1\) và lưu thứ tự ưu tiên (merge rank). Khi suy luận, chuỗi đầu vào được tách thành byte và lặp lại việc gộp cặp có rank nhỏ nhất trước cho đến khi hội tụ. Độ phức tạp mã hóa một pre-token dài \(L\) byte là \(O(L^2)\) ngây thơ hoặc \(O(L \log L)\) với hàng đợi ưu tiên.WordPiece(BERT,DistilBERT): Thay tần suất thô bằng tiêu chí tối đa hóa độ hợp lý tương hỗ:\[\operatorname{score}_{\text{WP}}(a, b) = \frac{\operatorname{count}(ab)}{\operatorname{count}(a)\,\operatorname{count}(b)},\]nhờ vậy ưu tiên gộp những cụm ít xuất hiện rời rạc nhưng gắn bó chặt (ví dụ các tiền tố/hậu tố chuyên ngành).Unigram LM(SentencePiece, Kudo 2018 —T5,XLM-R,Gemma 2/3): Bắt đầu từ tập ứng viên lớn rồi cắt tỉa dần những token làm giảm ít nhất hàm log-likelihood biên (tính bằng thuật toán Forward–Backward / EM và giải mã bằng Viterbi):\[\mathcal{L}(V) = \sum_{s \in \mathcal{D}} \log \sum_{\mathbf{x} \in S(s)} \prod_{i=1}^{|\mathbf{x}|} P(x_i).\]
Định nghĩa 1.1 (Tokenizer Fertility & Thuế Chi phí Đa ngôn ngữ):
Độ phân mảnh (Fertility) của bộ tokenizer trên tập ngữ liệu \(\mathcal{D}\) là số subword token trung bình cần thiết để mã hóa một từ ngôn ngữ tự nhiên:
Nếu tiếng Việt có tỷ số thuế \(\kappa = \mathcal{F}_{\text{VI}} / \mathcal{F}_{\text{EN}} > 1\), cùng một tài liệu ngữ nghĩa tiếng Việt sẽ làm tăng \(\kappa\times\) chi phí token & dung lượng KV Cache, cắt giảm cửa sổ ngữ cảnh hiệu dụng còn \(1/\kappa\), và đẩy chi phí Self-Attention prefill \(O(L^2)\) tăng xấp xỉ \(\kappa^2\times\)! Trong Lab 10 (Test 04), bộ Byte-Level BPE thuần Anh (|V| = 512) gây thuế 1.44x trên tiếng Việt (5.74 vs 4.00 tok/từ; mỗi ký tự dấu tiếng Việt chiếm 2–3 byte UTF-8 bị xé lẻ); mở rộng huấn luyện đa ngôn ngữ (|V| = 640) hạ ngay Fertility tiếng Việt xuống 2.32 tok/từ (-59.7%) trong khi vẫn giữ giải mã 100% không mất mát.
1.2 Không gian Vector (TF-IDF vs Okapi BM25) & Nhúng Từ Dày đặc (Word2Vec SGNS, FastText)#
Trong truy hồi thông tin (IR) và nhánh tìm kiếm thưa của Hybrid RAG (Chương 23), biểu diễn túi từ TF-IDF chuẩn bộc lộ hai điểm yếu chí mạng: tần suất từ tăng tuyến tính không giới hạn (dễ bị tấn công nhồi từ khóa keyword stuffing) và thiếu chuẩn hóa độ dài tài liệu hợp lý. Okapi BM25 (Robertson & Zaragoza 2009) khắc phục triệt để bằng công thức xác suất 2-Poisson:
- Bão hòa tần suất (\(k_1 \in [1.2, 2.0]\)): Khi \(f(t, d) \to \infty\), thừa số tần suất hội tụ về giới hạn trên hữu hạn \((k_1 + 1) = 2.5\) (với \(k_1 = 1.5\)). Do đó, nhồi
18lần một từ"bilstm"chỉ mang lại điểm tối đa \(2.5 \times \operatorname{IDF}(\text{bilstm})\), không thể vượt qua tài liệu khớp đúng cả 2 từ"bilstm"và"viterbi"(Lab 10,Test 05:3.27 > 2.38,BM25 MRR = 1.000vsTF-IDF 0.875). - Chuẩn hóa độ dài (\(b \in [0, 1]\), mặc định \(b = 0.75\)): Phạt tài liệu dài \(|d| > \operatorname{avgdl}\) có cùng tần suất xuất hiện từ khóa (
Lab 10: tài liệu súc tích2.62> tài liệu độn dài1.06).
Để vượt qua hạn chế đồng nghĩa không chia sẻ từ vựng của không gian thưa, các kỹ thuật nhúng từ dày đặc (Word Embeddings) ánh xạ mỗi từ vào không gian liên tục \(\mathbb{R}^d\) dựa trên Giả thuyết Phân bố (Firth 1957). Trong Word2Vec Skip-Gram với Lấy mẫu Âm (SGNS, Mikolov et al. 2013), hàm mất mát cho cặp từ trung tâm–ngữ cảnh \((w, c)\) với \(K_{\text{neg}}\) mẫu âm rút từ phân phối làm phẳng \(P_n(w) \propto U(w)^{3/4}\) là:
có đạo hàm giải tích cực gọn (chỉ tốn \(O(K_{\text{neg}} d)\) thay vì \(O(|V|d)\) của softmax đầy đủ):
Định lý 1.2 (Tương đương Phân rã Ma trận Shifted-PMI — Levy & Goldberg, NeurIPS 2014):
Khi kích thước nhúng \(d\) đủ lớn, nghiệm tối ưu toàn cục của hàm mục tiêu Word2Vec SGNS phân rã ngầm ma trận Thông tin Tương hỗ Điểm dịch chuyển:
Trong Lab 10 (Test 06), bộ huấn luyện SGNS thuần NumPy giảm mất mát từ 2.874 -> 1.022, tách rõ cụm ngữ nghĩa (cos(bilstm, crf) = 0.51, cos(kafka, spark) = 0.56 so với cos(bilstm, basel) = 0.35) và tích vô hướng \(\mathbf{W}_{\text{in}}\mathbf{W}_{\text{out}}^\top\) đạt tương quan r = 0.69 trực tiếp với ma trận Shifted-PMI giải tích! Để khắc phục hạn chế không sinh được vector cho từ OOV của Word2Vec, FastText (Bojanowski et al. 2017) cộng thêm tổng các vector \(n\)-gram ký tự (\(3 \le n \le 6\)) của mỗi từ, nắm bắt tốt hình thái học và lỗi chính tả OCR.
1.3 Mạng Hồi quy (RNN), Giải tích BPTT, Bệnh lý Gradient & LSTM / GRU / Biến thể#
Một Vanilla RNN cập nhật trạng thái ẩn \(\mathbf{h}_t \in \mathbb{R}^{d_h}\) theo phương trình hồi quy chia sẻ trọng số qua thời gian:
Mệnh đề 1.3 (Định lý Bệnh lý Gradient BPTT — Bengio et al. 1994; Pascanu et al. 2013):
Xét đạo hàm ngược của mất mát \(\mathcal{L}_T\) tại bước cuối \(T\) về trạng thái ẩn \(\mathbf{h}_k\) cách đó \(\Delta = T - k\) bước:
Đặt \(\lambda_{\max} = \sigma_{\max}(\mathbf{W}_{hh})\) và chú ý \(0 \le 1 - h_{t,i}^2 \le 1\):
- Triệt tiêu Gradient (
Vanishing Gradient): Nếu \(\lambda_{\max} < 1\), ta có cận trên \(\left\lVert \frac{\partial \mathbf{h}_t}{\partial \mathbf{h}_{t-1}} \right\rVert_2 \le \gamma < 1\), suy ra \(\left\lVert \frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_k} \right\rVert_2 \le \gamma^{T-k}\left\lVert \frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_T} \right\rVert_2 \xrightarrow{T-k\to\infty} 0\). TrongLab 10(Test 07, \(T = 36, \rho = 0.68\)), tỷ số \(\|\mathbf{g}_1\|/\|\mathbf{g}_{36}\|\) sụp xuống7.36e-07, làmVanilla RNNthất bại hoàn toàn ở49.2%trên bài toán nhớ phụ thuộc xa! - Bùng nổ Gradient (
Exploding Gradient): Nếu \(\rho(\mathbf{W}_{hh}) > 1\) trong vùng tuyến tính của \(\tanh\), tích Jacobian phình theo hàm mũ (Lab 10, \(\rho = 1.45\): tỷ số vọt lên18.38; \(\rho = 1.60\): chuẩn gradient tổng nhảy lên27.75), đẩy tham số văng khỏi vùng lồi gây trànNaN. - Cắt chuẩn Toàn cục (
Global L2 Gradient Clipping): Để chặn bùng nổ mà bảo toàn chính xác hướng hạ gradient (cosine = 1.0000), ta đồng tỷ lệ toàn bộ vector gradient \(\mathbf{g}\) khi \(\lVert \mathbf{g} \rVert_2 > \tau_{\text{clip}}\):\[\tilde{\mathbf{g}} = \min\!\left(1,\; \frac{\tau_{\text{clip}}}{\lVert \mathbf{g} \rVert_2 + \varepsilon}\right)\mathbf{g}.\]Lưu ý bản chất: Cắt chuẩn gradient chữa dứt điểm bùng nổ (27.75 -> 1.000trongTest 08), nhưng không thể chữa triệt tiêu gradient!
Để giải quyết tận gốc bài toán triệt tiêu gradient, LSTM (Hochreiter & Schmidhuber 1997; Gers et al. 2000) tách riêng một đường cao tốc trạng thái ô nhớ cộng tính \(\mathbf{c}_t\):
Đạo hàm dọc đường ô nhớ có số hạng trực tiếp \(\frac{\partial \mathbf{c}_t}{\partial \mathbf{c}_{t-1}} = \operatorname{diag}(\mathbf{f}_t) + \cdots\) không bị nhân lặp lại với ma trận trọng số \(\mathbf{W}_{hh}\). Khi khởi tạo thiên vị cổng quên \(b_f \in [1.5, 2.0]\) (Jozefowicz et al. 2015), \(\mathbf{f}_t = \sigma(b_f) \approx 0.82\text{–}0.88\), giữ tỷ số gradient ô nhớ ở mức 0.319 sau 36 bước (cao hơn Vanilla RNN gấp 430,000x!) và đưa độ chính xác bài toán \(T = 36\) lên 100.0%.
GRU (Cho et al. 2014) gộp trạng thái ô nhớ vào \(\mathbf{h}_t\) với chỉ 2 cổng (đặt lại \(\mathbf{r}_t\), cập nhật \(\mathbf{z}_t\)), cắt giảm ~25% tham số hồi quy (5,122 vs 6,722 tham số trong Lab 10). Cạm bẫy cài đặt PyTorch quan trọng: Khác với một số giáo trình cũ viết \((1 - \mathbf{z}_t)\odot \mathbf{h}_{t-1}\), cài đặt chính thức torch.nn.GRU tính \(\mathbf{h}_t = (1 - \mathbf{z}_t)\odot \mathbf{n}_t + \mathbf{z}_t \odot \mathbf{h}_{t-1}\), do đó khởi tạo thiên vị cổng cập nhật dương (\(b_z = +1.5\)) mới kích hoạt đường cao tốc bảo toàn \(\mathbf{h}_{t-1}\) và giúp GRU đạt 100.0% trên Lab 10 (Test 09)!
Bên cạnh đó, ba biến thể thực chiến mở rộng sức mạnh của họ mạng hồi quy:
Bi-RNN/BiLSTM: Kết hợp nhánh xuôi \(\overrightarrow{\mathbf{h}}_t\) và nhánh ngược \(\overleftarrow{\mathbf{h}}_t\) thành \([\overrightarrow{\mathbf{h}}_t;\overleftarrow{\mathbf{h}}_t] \in \mathbb{R}^{2d_h}\), cho phép nhìn đồng thời ngữ cảnh trái và phải — điều kiện bắt buộc choPOS TaggingvàNER.Deep Stacked RNN: Xếp nhiều tầng hồi quy có kết nối tắt (residual) và inter-layer dropout (tránh đặt dropout trực tiếp trên đường hồi quy ô nhớ).CNN-LSTM: Đặt tầngConv1d(\(k=3\)) trích xuất nhanh các cụm \(n\)-gram cục bộ trước khi đưa quaLSTMtổng hợp toàn chuỗi (100.0%trên tập phân loại miềnLab 10).- Tầm nhìn 2026 (
xLSTM,Mamba-2 / SSM,MinLSTM): Nhược điểm lớn nhất củaLSTM/GRUcổ điển là tính tuần tự \(O(T)\) không song song hóa được theo thời gian khi huấn luyện (dù suy luận tốn bộ nhớ hằng số \(O(1)\), ưu thế hơnKV Cache\(O(T)\) của Transformer). Các hậu duệ tuyến tính 2024–2026 (xLSTMBeck et al.,Mamba-2,MinLSTMFeng et al.) loại bỏ liên kết phi tuyến \(\mathbf{h}_{t-1}\) bên trong cổng để song song hóa huấn luyện trong \(O(\log T)\) bằng thuật toán Parallel Prefix Scan.
1.4 Phân loại Văn bản & Giải thích Văn bản Trung thực (Text XAI: LIME vs Token Integrated Gradients)#
Trong ứng dụng tuyển dụng, y tế hoặc tài chính, phân loại văn bản đạt 100% độ chính xác chưa đủ — hệ thống phải chứng minh mô hình ra quyết định dựa trên bằng chứng đúng (kỹ năng kỹ thuật như bilstm, kafka, basel) chứ không dựa trên từ khóa đường tắt mang tính thiên kiến.
- Hạn chế của
LIMEvà Attention thô:LIMEnhiễu loạn cục bộ bằng cách xóa ngẫu nhiên từng cụm từ rồi khớp hồi quy tuyến tính; tuy không cần gradient nhưng có phương sai cao và dễ sinh câu phi tự nhiên ngoài phân phối. Tương tự, Jain & Wallace (NAACL 2019) chứng minh trọng số attention thô không đồng nhất với đóng góp nhân quả. Token Integrated Gradientstrên Không gian Nhúng (Sundararajan et al. 2017): Cho ma trận nhúng câu \(\mathbf{E} \in \mathbb{R}^{T\times d_e}\) và nền chuẩn \(\mathbf{E}' = \mathbf{0}\), quy gán của token \(t\) cho logit đích \(F_c\) được tính bằng tích phân đường dọc \(\alpha \in [0, 1]\):\[\operatorname{IG}_t(\mathbf{E}; \mathbf{E}') = \sum_{j=1}^{d_e} (E_{t,j} - E'_{t,j}) \int_{0}^{1} \frac{\partial F_c\big(\mathbf{E}' + \alpha(\mathbf{E} - \mathbf{E}')\big)}{\partial E_{t,j}}\, d\alpha.\]Để đảm bảo tiên đề Completeness \(\sum_{t=1}^{T}\operatorname{IG}_t = F_c(\mathbf{E}) - F_c(\mathbf{E}')\) với độ chính xác cao ngay cả khi các cổngBiLSTMchuyển trạng thái sắc nét,Lab 10cài đặt cầu phương ghép Gauss–Legendre 8 đoạn (8-panel Composite Gauss–Legendre) vector hóa trong một lần chạy batch duy nhất(M, T, E), đạt sai số Completeness trung bình chỉ8.76e-03(< 0.9%)!- Kiểm định Trung thực Can thiệp
ERASER(DeYoung et al., ACL 2020):Comprehensiveness(càng cao càng trung thực): \(\operatorname{Comp} = P(\hat{y}\mid \mathbf{x}) - P(\hat{y}\mid \mathbf{x}_{\setminus R_k})\) — xóa top-\(k\) token có điểmIGcao nhất phải làm xác suất sụt mạnh (Lab 10:0.565vs xóa ngẫu nhiên0.085).Sufficiency(càng thấp càng trung thực): \(\operatorname{Suff} = P(\hat{y}\mid \mathbf{x}) - P(\hat{y}\mid \mathbf{x}_{R_k})\) — chỉ giữ lại top-\(k\) token quan trọng nhất vẫn gần như giữ nguyên dự đoán (Lab 10:-0.001vs giữ ngẫu nhiên0.179, kèmTop-3 Rationale Hit-Rate = 83.3%).
1.5 Trích xuất Thông tin (IE), POS, NER, BiLSTM-CRF, GLiNER & Document AI Đa cột#
Đường ống Trích xuất Thông tin (Information Extraction — IE) biến văn bản phi cấu trúc thành tri thức có lược đồ (JSON/đồ thị) qua chuỗi tác vụ: phân tách câu/token \(\to\) gán nhãn từ loại (POS Tagging) \(\to\) nhận diện thực thể có tên (NER) \(\to\) trích xuất quan hệ và chuẩn hóa thực thể.
Trong NER, các thực thể nhiều từ (Senior ML Engineer, VinAI Research, MSc Quantitative Finance NTU) được mã hóa theo chuẩn biên BIO (B-TYPE, I-TYPE, O) hoặc BIOES. Chuẩn BIO chứa bất biến ngữ pháp cấu trúc tuyệt đối: không bao giờ tồn tại chuyển tiếp START -> I-X, O -> I-X, hay B-X -> I-Y / I-X -> I-Y (\(X \ne Y\)).
- Vì sao
BiLSTM-Softmaxđộc lập thất bại: Dự đoán \(\hat{y}_t = \arg\max_k P_{t,k}\) độc lập tại từng bước không hề biết nhãn vừa chọn ở bước \(t-1\), dẫn tới hàng loạt chuỗi gãy vụn (O -> I-ORG,B-ROLE -> I-SKILL) đặc biệt khi gặp nhiễu OCR hoặc tên riêng mới (Lab 10:90lỗi sạch,57lỗi nhiễu OCR). -
Lý thuyết & Giải thuật Chính xác của
BiLSTM-CRF(Lample et al., NAACL 2016):
Kết hợp ma trận điểm phát xạ \(\mathbf{P} \in \mathbb{R}^{T\times K}\) từBiLSTMvới ma trận điểm chuyển tiếp học được \(\mathbf{A} \in \mathbb{R}^{K\times K}\) (và vector khởi đầu/kết thúc \(\mathbf{a}_{\text{START}}, \mathbf{a}_{\text{END}}\), áp dụng mặt nạ phạt \(-10^4\) lên mọi chuyển tiếpBIOphi pháp), điểm toàn cục của chuỗi nhãn \(\mathbf{y} = (y_1, \dots, y_T)\) là:\[s(\mathbf{x}, \mathbf{y}) = a_{\text{START}, y_1} + \sum_{t=1}^{T} P_{t, y_t} + \sum_{t=1}^{T-1} A_{y_t, y_{t+1}} + a_{y_T, \text{END}}.\]Xác suất có điều kiện toàn chuỗi tuân theo phân phối Gibbs/Boltzmann:
\[P(\mathbf{y} \mid \mathbf{x}) = \frac{\exp\!\big(s(\mathbf{x}, \mathbf{y})\big)}{Z(\mathbf{x})}, \qquad \mathcal{L}_{\text{CRF}} = -\log P(\mathbf{y}^* \mid \mathbf{x}) = \log Z(\mathbf{x}) - s(\mathbf{x}, \mathbf{y}^*).\]- Thuật toán Forward log-sum-exp (\(O(TK^2)\) thay vì duyệt vét cạn \(O(K^T)\)): Khởi tạo \(\alpha_1(j) = a_{\text{START}, j} + P_{1, j}\), cập nhật đệ quy ổn định số học:
\[\alpha_t(j) = P_{t, j} + \operatorname{logsumexp}_{i \in \{1..K\}}\!\big(\alpha_{t-1}(i) + A_{i, j}\big), \qquad \log Z(\mathbf{x}) = \operatorname{logsumexp}_{i}\!\big(\alpha_T(i) + a_{i, \text{END}}\big).\]Trong
Lab 10(Test 11), sai số giữaforward_log_partitionvà duyệt vét cạn \(11^4 = 14,641\) đường đi chỉ là3.52e-07! - Thuật toán Giải mã Viterbi (\(O(TK^2)\)): Thay
logsumexpbằngmaxvà lưu con trỏ ngược (backpointer) để tìm chuỗi tối ưu toàn cục \(\hat{\mathbf{y}} = \arg\max_{\mathbf{y}} s(\mathbf{x}, \mathbf{y})\), đảm bảo toán học0.00%chuyển tiếp BIO bất hợp lệ ngay cả dưới phát xạ đối kháng hay25%nhiễu OCR (Tests 12, 13). - Đánh giá
Span-Level Exact F1(seqeval) & Word Dropout<UNK>: Không bao giờ dùng token accuracy cho NER vì~75–85%token làO; chỉ tínhTPkhi khớp trọn vẹn bộ ba(start, end, entity_type). Đồng thời, áp dụng kỹ thuật word dropout12%sang<UNK>trong lúc huấn luyện (Lample et al. 2016) buộcBiLSTM-CRFhọc suy luận thực thểPERSONmới hoàn toàn từ ngữ cảnh xung quanh — giúpLab 10đạt99.1%Span F1 trên nhóm ứng viên tách biệt (group-aware split, chưa từng xuất hiện tên trong tập train!) và96.4%dưới25%nhiễu OCR!
- Thuật toán Forward log-sum-exp (\(O(TK^2)\) thay vì duyệt vét cạn \(O(K^T)\)): Khởi tạo \(\alpha_1(j) = a_{\text{START}, j} + P_{1, j}\), cập nhật đệ quy ổn định số học:
Tiến hóa Document AI & NER SOTA 2024–2026:
- Zero-Shot Open NER —
GLiNER(Zaratiana et al., NAACL 2024): Thay bộ phân loại nhãn cố định bằng bộ mã hóa hai chiều (DeBERTa-v3/mDeBERTa) đọc đồng thời danh sách loại thực thể tùy biến và văn bản, chấm điểm khớp span–nhãn \(\phi(i, j, c) = \sigma(\mathbf{s}_{i,j}^\top \mathbf{e}_c)\). Hỗ trợ thực thể lồng nhau, thêm trường mới không cần huấn luyện lại, nhanh hơn10x–30xso với LLM sinh JSON. - Khắc phục Hiểm họa Thứ tự Đọc Đa cột (
Multi-Column Reading-Order Hazard): Trên CV 2 cột, sắp xếp theo tọa độ \(y_0\) ngây thơ (Naive Y-Sort) cắt vụn từng câu ngang qua khe cột (Lab 10,Test 14:0.0%tài liệu đúng thứ tự!). Tầng hình họcRecursive XY-Cuttìm khe chiếu rỗng dọc (vertical gutter) tách đệ quy các cột trước khi đọc từ trên xuống dưới, phục hồi100.0%thứ tự đọc trong< 0.5 ms/trangtrên CPU; với PDF scan nhiễu, bảng lồng phức tạp hoặc tài liệu viết tay, hệ thống định tuyến sang mô hình đa phương thứcLayoutLMv3(nhúng chữ + tọa độ 2D + mảng ảnh) hoặcDocling/Qwen2.5-VL, sau đó luôn khóa đầu ra bằng lược đồPydantic v2(extra="forbid").
Trụ cột 2 — Kiến trúc Hệ thống NLP & Document AI Sản xuất#
2.1 Kiến trúc Đường ống Phân tích Hồ sơ Doanh nghiệp (Enterprise ATS Resume Document AI)#
2.2 Biểu đồ Tuần tự Vòng Suy luận & Kiểm toán BiLSTM-CRF#
2.3 Ngân sách SLA, Bảng Quyết định Kiến trúc & Cổng Kiểm toán CI/CD#
| Hạng mục / Ràng buộc | Ngân sách Mục tiêu Sản xuất | Kết quả Đo Thực tế (Lab 10) |
Chiến lược An toàn & Dự phòng |
|---|---|---|---|
| Chuẩn hóa & Fertility Tiếng Việt | Lossless UTF-8, giảm >= 40% Fertility VI |
Lossless = True; VI 5.74 -> 2.32 (-59.7%) |
Bắt buộc NFC tại API Ingress; theo dõi Fertility như KPI chi phí |
| Truy hồi Từ vựng Chính xác | MRR >= 0.95 trên truy vấn mã điều khoản |
BM25 MRR = 1.000 vs TF-IDF 0.875 |
Luôn ghép BM25 (\(k_1=1.5, b=0.75\)) cùng Dense trong Hybrid RAG |
Độ trễ Trích xuất CPU (CV) |
< 10 ms/CV (p99), 0 pickle |
1.59 ms/CV (safetensors = 87,708 B, diff = 0.0) |
Cấm .pt/.pkl bằng AST CI gate; định tuyến <12% scan sang VLM |
Toàn vẹn Bố cục & Ngữ pháp BIO |
0.00% BIO lỗi; XY-Cut >= 99% thứ tự |
0.00% lỗi BIO (vs 2.86% Softmax); XY-Cut = 100% |
Khóa cứng mặt nạ BIO trong LinearChainCRF; tách tập test theo ứng viên |
Kiểm toán Minh bạch (Text XAI) |
Comp > Rand + 0.20, Suff < Rand - 0.10 |
Comp = 0.565 (Rand 0.085), Suff = -0.001 (0.179) |
Chặn mô hình nếu Top-3 IG bám vào tên riêng/trường học thay vì kỹ năng |
Trụ cột 3 — Hệ sinh thái 2026 & Mã nguồn Thực thi Độc lập#
Đoạn mã độc lập dưới đây chạy hoàn toàn ngoại tuyến trong môi trường .venv (Python 3.12, torch 2.15.0+cpu, numpy, pydantic v2, safetensors), tái lập trọn vẹn ba kiểm chứng toán học cốt lõi của Chương 18: (1) giải mã Byte-Level BPE không mất mát trên tiếng Việt & mã nguồn, (2) chứng minh tỷ số gradient BPTT giữa Vanilla RNN và đường cao tốc ô nhớ LSTM, và (3) đối chiếu hàm phân hoạch Forward log-sum-exp của LinearChainCRF với duyệt vét cạn \(K^T\) cùng giải mã Viterbi 0 lỗi BIO:
"""Pillar 3 Executable Specimen: Byte-Level BPE Lossless, BPTT Gradient Flow & Exact CRF Parity."""
from __future__ import annotations
import itertools
import json
import unicodedata
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
def run_ch18_specimen(seed: int = 42) -> dict[str, float | bool]:
"""Verify UTF-8 byte round-trip, BPTT vanishing vs LSTM highway, and exact CRF log Z parity."""
torch.manual_seed(seed)
# 1. Lossless UTF-8 Byte-level normalization & round-trip check
sample_vi = "Ứng viên Nguyễn Minh Anh — Senior NLP Engineer (Python 3.12, C++, F1=0.99)"
nfc = unicodedata.normalize("NFC", sample_vi)
byte_ids = list(nfc.encode("utf-8"))
decoded = bytes(byte_ids).decode("utf-8", errors="strict")
lossless_ok = decoded == nfc
# 2. BPTT gradient ratio ||dL/dh_1|| / ||dL/dh_T|| over T=36 steps (RNN rho=0.68 vs LSTM b_f=2.0)
seq_len, hdim = 36, 32
x = torch.randn(4, seq_len, 16) * 0.25
target = torch.zeros(4, dtype=torch.long)
rnn = nn.RNNCell(16, hdim, nonlinearity="tanh")
head_r = nn.Linear(hdim, 2)
with torch.no_grad():
nn.init.orthogonal_(rnn.weight_hh)
rnn.weight_hh.mul_(0.68)
rnn.bias_hh.zero_()
rnn.bias_ih.zero_()
h = torch.zeros(4, hdim)
r_states: list[torch.Tensor] = []
for t in range(seq_len):
h = rnn(x[:, t, :], h)
h.retain_grad()
r_states.append(h)
F.cross_entropy(head_r(r_states[-1]), target).backward()
rnn_ratio = float(r_states[0].grad.norm() / max(float(r_states[-1].grad.norm()), 1e-12))
lstm = nn.LSTMCell(16, hdim)
head_l = nn.Linear(hdim, 2)
with torch.no_grad():
lstm.bias_hh[hdim : 2 * hdim].fill_(2.0)
lstm.bias_ih[hdim : 2 * hdim].fill_(0.0)
h_l, c_l = torch.zeros(4, hdim), torch.zeros(4, hdim)
c_states: list[torch.Tensor] = []
for t in range(seq_len):
h_l, c_l = lstm(x[:, t, :], (h_l, c_l))
c_l.retain_grad()
c_states.append(c_l)
F.cross_entropy(head_l(h_l), target).backward()
lstm_c_ratio = float(c_states[0].grad.norm() / max(float(c_states[-1].grad.norm()), 1e-12))
# 3. Exact Linear-Chain CRF Forward log-sum-exp vs Brute-Force K^T partition parity
t_len, k_tags = 4, 5
emit = torch.randn(t_len, k_tags)
trans = torch.randn(k_tags, k_tags) * 0.3
start_t = torch.randn(k_tags) * 0.2
end_t = torch.randn(k_tags) * 0.2
alpha = start_t + emit[0]
for t in range(1, t_len):
alpha = emit[t] + torch.logsumexp(alpha.unsqueeze(1) + trans, dim=0)
log_z_forward = float(torch.logsumexp(alpha + end_t, dim=0).item())
scores_all = []
for path in itertools.product(range(k_tags), repeat=t_len):
sc = float(start_t[path[0]] + emit[0, path[0]] + end_t[path[-1]])
for t in range(1, t_len):
sc += float(trans[path[t - 1], path[t]] + emit[t, path[t]])
scores_all.append(sc)
arr = np.asarray(scores_all, dtype=np.float64)
m_sc = float(arr.max())
log_z_brute = m_sc + float(np.log(np.sum(np.exp(arr - m_sc))))
return {
"utf8_lossless_roundtrip": lossless_ok,
"bptt_rnn_ratio_t1_t36": round(rnn_ratio, 9),
"bptt_lstm_cell_ratio_t1_t36": round(lstm_c_ratio, 4),
"crf_log_z_abs_err": float(f"{abs(log_z_forward - log_z_brute):.2e}"),
}
if __name__ == "__main__":
print(json.dumps(run_ch18_specimen(seed=42), indent=2))
Trụ cột 4 — Phòng thí nghiệm Thực chiến (Lab 10: nlp_docai_lab) & Rubric Đánh giá#
4.1 Kiến trúc Hai Tầng (Two-Tier) của Lab 10#
Toàn bộ mã nguồn thực nghiệm được đóng gói chuẩn hóa tại labs/lab-10-text-processing-and-resume-document-ai/README.md dưới gói nlp_docai_lab (100% ngoại tuyến, tất định seed=42, khóa phiên bản với uv.lock, không dùng tiktoken/spacy, cấm pickle):
- Tầng 1 (
Reference Corethuần Python /NumPy/SciPy/scikit-learn):tokenization_and_bm25.py: Chuẩn hóaUnicode NFC/NFKC, đối chứng làm sạch bảo toàn vs phá hủy, bộByteLevelBPETokenizerhuấn luyện từ đầu (không mất mát trên Anh/Việt/Code), đoTokenizer Fertility,BM25Index(\(k_1, b\)) vsTfidfRetriever, vàWord2Vec SGNSthuần NumPy kèm ma trậnShifted-PMI.resume_dataset.py: Trình sinh dữ liệuResume NERtách nhóm ứng viên (BIO_TAGS11nhãn:PERSON,ROLE,SKILL,ORG,EDU), tập24CV bố cục 2 cột với hộp bao 2D đối chứngNaive Y-SortvsRecursive XY-Cut, và tập phân loại3miền kỹ thuật có từ khóa căn cứ (ground-truth rationales).
- Tầng 2 (
PyTorch 2.15.0+cpu,Pydantic v2,safetensors):sequence_models.py:VanillaRNNClassifier,LSTMClassifier(\(b_f=1.5\)),GRUClassifier(\(b_z=1.5\)),BiLSTMTextClassifier,CNNLSTMClassifier, công cụ đo dòng gradientBPTTtừng bước, cắt chuẩn toàn cụcclip_grad_norm_, vàToken Integrated Gradientsvector hóa (Gauss–Legendre 8 đoạn) + kiểm toánERASER(Comprehensiveness/Sufficiency).bilstm_crf_resume_ie.py:LinearChainCRFchuẩn xác (Forward log-sum-exp, đối chứng duyệt vét cạn \(K^T\), giải mã Viterbi ràng buộc BIO), đối chứngBiLSTMSoftmaxTaggervsBiLSTMCRF(sạch +25%nhiễu OCR),ResumeProfile(Pydantic v2,extra="forbid", ẩn danh[REDACTED_PERSON]), và đóng góisafetensorskhôngpickle.
4.2 Bảng Kết quả Thực nghiệm Chuẩn hóa (seed=42, artifacts/ch18_lab10_results.json)#
| Phân hệ Thực nghiệm | Cấu hình / Đối chứng | Chỉ số Đo được (seed=42) |
Kết luận Nghiệm thu |
|---|---|---|---|
Unicode & Byte-Level BPE |
EN-BPE (512) vs Multi-BPE (640) |
Lossless = True; VI Fertility 5.74 -> 2.32 (-59.7%, thuế gốc 1.44x vs EN 4.00, Code 7.78) |
Cắt mạnh thuế token tiếng Việt, 0 <UNK> |
Okapi BM25 & SGNS |
BM25 (k1=1.5, b=0.75) vs TF-IDF; SGNS (d=20, K=4) |
BM25 MRR = 1.000 (vs TF-IDF 0.875); True 3.27 > Spam 2.38; SGNS Loss 2.874 -> 1.022, SPMI r = 0.69 |
Khớp định lý bão hòa & Levy–Goldberg Shifted-PMI |
BPTT & Phụ thuộc Xa (T=36) |
Vanilla RNN (\(\rho=0.68 / 1.45\)) vs LSTM / GRU |
Grad ratio: RNN 7.36e-07 vs LSTM c_t 0.319; Clip 27.75 -> 1.000 (cos=1.0000); Acc: RNN 49.2% vs LSTM 100% / GRU 100% |
Xác nhận thực nghiệm bệnh lý BPTT & cao tốc ô nhớ |
Phân loại & Token IG XAI |
BiLSTM (100%), CNN-LSTM (100%), IG (M=96) |
Comp = 0.565 (Rand 0.085), Suff = -0.001 (Rand 0.179), Top-3 Hit = 83.3%, Mean Comp Err 8.76e-03 |
Trung thực vượt trội mặt nạ ngẫu nhiên (ERASER) |
BiLSTM-CRF vs Softmax |
Resume NER (260 train / 90 test tách ứng viên) |
log Z err 3.52e-07; CRF 99.1% sạch / 96.4% nhiễu OCR (0.00% BIO lỗi) vs Softmax 93.2% (2.86% / 57 lỗi) |
Tuyệt đối 0.00% chuyển tiếp BIO phi pháp |
| CV 2 Cột & Chuỗi cung ứng | 24 CV 2 cột (XY-Cut vs Y-Sort), Pydantic v2, safetensors |
XY-Cut 100.0% vs Y-Sort 0.0% (Pairwise 100% vs 71.4%); sf = 87,708 B (diff = 0.0), 1.59 ms/CV |
0 pickle, ẩn danh PII đầy đủ, đạt SLA biên |
4.3 Hợp đồng 16 Bài kiểm thử Tự động (tests/test_nlp_docai_lab.py)#
| STT | Tên Hàm Kiểm thử Pytest |
Bất biến & Ngưỡng Nghiệm thu Bắt buộc |
|---|---|---|
1 |
test_01_ast_no_unsafe_deserializers |
Quét AST toàn bộ src/ và scripts/, cấm pickle, joblib, cloudpickle, dill, shelve, marshal |
2 |
test_02_unicode_nfc_nfkc_and_safe_cleanup_preserves_ner_code |
NFC rút gọn tổ hợp tiếng Việt, NFKC chuẩn hóa chữ ghép OCR, làm sạch an toàn bảo toàn tín hiệu NER/code |
3 |
test_03_byte_level_bpe_lossless_roundtrip_en_vi_code |
ByteLevelBPETokenizer huấn luyện từ đầu đạt giải mã khít 100% trên Anh, Việt có dấu, code và ký tự hiếm |
4 |
test_04_tokenizer_fertility_disparity_and_vocab_tradeoff |
Chứng minh thuế fertility tiếng Việt trên BPE thuần Anh (> 1.4x) và mức giảm mạnh (> 25%) ở BPE đa ngôn ngữ |
5 |
test_05_bm25_saturation_length_norm_and_tfidf_benchmark |
Okapi BM25 đánh bại tài liệu nhồi từ khóa, phạt tài liệu độn dài và tuân thủ cận bão hòa \((k_1 + 1)\) |
6 |
test_06_word2vec_sgns_loss_decrease_and_semantic_cosine |
Word2Vec SGNS thuần NumPy giảm mất mát >= 20% và phân tách rõ độ tương đồng cosine giữa các cụm chủ đề |
7 |
test_07_bptt_gradient_vanishing_vanilla_rnn_vs_lstm_highway |
Tỷ số gradient Vanilla RNN < 1e-3, đường cao tốc ô nhớ LSTM > 0.10 và lớn hơn RNN gấp > 100x |
8 |
test_08_bptt_gradient_explosion_and_norm_clipping_cap |
clip_grad_norm_ kẹp chuẩn nổ > 5.0 xuống <= 1.0 mà giữ nguyên hướng (cosine > 0.9999) |
9 |
test_09_long_range_sequence_benchmark_lstm_gru_vs_vanilla_rnn |
Trên chuỗi phụ thuộc xa, cả LSTM và GRU đạt >= 90% và vượt Vanilla RNN ít nhất +25 điểm % |
10 |
test_10_token_integrated_gradients_completeness_and_faithfulness |
Token IG thỏa Completeness (mean < 0.01, max < 0.03), vượt trội Random trên Comp/Suff & Top-3 Hit >= 70% |
11 |
test_11_crf_forward_log_partition_matches_exact_bruteforce |
Hàm phân hoạch Forward log-sum-exp khớp duyệt vét cạn \(K^T\) tới sai số < 1e-4 (có & không khóa BIO) |
12 |
test_12_crf_viterbi_optimality_and_zero_illegal_bio_transitions |
Viterbi khớp điểm chuỗi tối ưu toàn cục và giữ đúng 0 chuyển tiếp BIO phi pháp dưới phát xạ đối kháng |
13 |
test_13_bilstm_crf_vs_softmax_resume_ner_span_f1_and_legality |
BiLSTM-CRF đạt Span F1 >= 92% (sạch) / >= 90% (nhiễu OCR) và 0.00% lỗi BIO (vs > 0% của Softmax) |
14 |
test_14_two_column_resume_xy_cut_fixes_naive_y_sort_bug |
Naive Y-Sort đạt 0% thứ tự tài liệu đúng trên CV 2 cột, trong khi Recursive XY-Cut khôi phục 100% |
15 |
test_15_pydantic_resume_profile_and_safetensors_zero_pickle_roundtrip |
Xác thực header safetensors (diff == 0.0), ẩn danh [REDACTED_PERSON] và Pydantic v2 chặn trường lạ |
16 |
test_16_cli_artifact_and_workbench_panels_schema |
CLI --quick xuất JSON hợp lệ chứa đúng 6 KPI, 4 biểu đồ cột và 4 bảng workbench_panels |
Trụ cột 5 — Văn liệu Nền tảng, Ôn tập Nhanh & Hệ thống Bài tập Chuyên sâu#
5.1 Sáu Công trình Học thuật Nền tảng & SOTA (1997–2026)#
- Sennrich, R. et al. (ACL 2016), Kudo, T. (ACL 2018) & Petrov, A. et al. (NeurIPS 2023). Neural Machine Translation of Rare Words with Subword Units (
BPE), Subword Regularization (Unigram LM) & Language Model Tokenizers Introduce Unfairness Between Languages (Tokenizer Fertility) — nền tảng toán học và kinh tế học của token hóa hiện đại. - Robertson, S. & Zaragoza, H. (FnTIR 2009), Mikolov, T. et al. (NeurIPS 2013) & Levy, O. & Goldberg, Y. (NeurIPS 2014). The Probabilistic Relevance Framework:
BM25and Beyond, Distributed Representations of Words and Phrases (Word2Vec SGNS) & Neural Word Embedding as Implicit Matrix Factorization (Shifted-PMI). - Hochreiter, S. & Schmidhuber, J. (1997), Pascanu, R. et al. (ICML 2013), Cho, K. et al. (EMNLP 2014) & Beck, M. et al. (NeurIPS 2024). Long Short-Term Memory (
LSTM), On the Difficulty of Training Recurrent Neural Networks (Gradient Clipping), Learning Phrase Representations using RNN Encoder–Decoder (GRU) &xLSTM: Extended Long Short-Term Memory. - Sundararajan, M. et al. (ICML 2017), Jain, S. & Wallace, B. (NAACL 2019) & DeYoung, J. et al. (ACL 2020). Axiomatic Attribution for Deep Networks (
Integrated Gradients), Attention is not Explanation &ERASER: A Benchmark to Evaluate Rationalized NLP Models (Comprehensiveness/Sufficiency). - Lample, G. et al. (NAACL 2016) & Zaratiana, U. et al. (NAACL 2024). Neural Architectures for Named Entity Recognition (
BiLSTM-CRF) &GLiNER: Generalist Model for Named Entity Recognition using Bidirectional Transformer (zero-shot NER SOTA 2024–2026). - Huang, Y. et al. (ACM MM 2022) & IBM Research (2024–2025).
LayoutLMv3: Pre-training for Document AI with Unified Text and Image Masking &DoclingTechnical Report (phân tích bố cục đa cột và bảng cho Document AI sản xuất).
5.2 Tám Câu hỏi Trắc nghiệm Kiểm tra Nhanh (Q1..Q8 — Khớp quiz_and_hints.json)#
Q1(Chuẩn hóa Unicode & Bẫy Tiền xử lý): Chuẩn hóaNFChợp nhất dấu tổ hợp tiếng Việt (52 -> 43ký tự trongLab 10), còn làm sạch ngây thơ (xóa chữ hoa, số, dấu câu) phá hủy10 -> 0tín hiệu NER/kỹ thuật (Python 3.12,C++,F1-score).Q2(Byte-Level BPE& ThuếTokenizer Fertility): Khởi tạo từ256byte UTF-8 đảm bảo giải mã100%không mất mát (0<UNK>);BPEthuần Anh đánh thuế1.44xtrên tiếng Việt (5.74vs4.00tok/từ), làm tăng \(\kappa\times\)KV Cachevà \(\kappa^2\times\) prefill \(O(L^2)\), trong khiMulti-BPEcắt giảm-59.7%xuống2.32tok/từ.Q3(Okapi BM25vsTF-IDF&Word2Vec SGNS):BM25dùng bão hòa \(k_1\) (tiệm cận trên \(k_1 + 1\)) chống nhồi từ khóa và chuẩn hóa độ dài \(b\) đạtMRR = 1.000vsTF-IDF 0.875;Word2Vec SGNSphân rã ngầm ma trậnShifted-PMI\(\operatorname{PMI}(w,c) - \log K\) (r = 0.69trongLab 10).Q4(BPTTGradient Pathology & Cắt chuẩn Toàn cục): Tích Jacobian \(\prod \operatorname{diag}(1-h_t^2)\mathbf{W}_{hh}\) gây triệt tiêu (7.36e-07ở \(\rho = 0.68\)) hoặc bùng nổ (18.38ở \(\rho = 1.45\)); cắt chuẩn toàn cục (\(\tau = 1.0\)) kẹp chính xác27.75 -> 1.000giữ hướngcosine = 1.0000, nhưng chỉ chữa bùng nổ chứ không chữa triệt tiêu.Q5(LSTM,GRU&CNN-LSTMtrên Phụ thuộc XaT=36): Nhờ đường cao tốc ô nhớ cộng tính \(\mathbf{c}_t = \mathbf{f}_t\odot \mathbf{c}_{t-1} + \mathbf{i}_t\odot \tilde{\mathbf{c}}_t\) (với \(b_f > 0\), tỷ số0.319) và cổng cập nhật dương \(b_z > 0\) trongtorch.nn.GRU(ít hơn~25%trọng số hồi quy),LSTMvàGRUcùng đạt100.0%trên chuỗi \(T = 36\) so với49.2%củaVanilla RNN.Q6(Giải thích Văn bản Trung thựcToken IG&ERASER): Cầu phương ghép Gauss–Legendre giúpToken IGthỏa tiên đề Completeness (mean err = 8.76e-03) và vượt xa xóa/giữ ngẫu nhiên trênComprehensiveness(0.565vs0.085),Sufficiency(-0.001vs0.179) cùngTop-3 Hit = 83.3%.Q7(BiLSTM-CRF: Forward Partition, Viterbi &Span Exact F1): Thuật toán Forward log-sum-exp tính chính xác \(\log Z(\mathbf{x})\) trong \(O(TK^2)\) (khớp duyệt vét cạn tới3.52e-07), giải mã Viterbi triệt tiêu tuyệt đối lỗi chuyển tiếp BIO (0.00%vs2.86%/57lỗi của Softmax dưới25%nhiễu OCR), đạt99.1%sạch /96.4%nhiễu OCRSpan Exact F1khi kết hợp word dropout<UNK>.Q8(Document AI Đa cộtXY-Cut,GLiNER,Pydantic v2&safetensors):Naive Y-Sorttrộn hai cột CV khiến độ chính xác thứ tự tài liệu bằng0.0%(Pairwise = 71.4%), trong khiRecursive XY-Cutkhôi phục100.0%; kết hợpGLiNERcho trường zero-shot,Pydantic v2(extra="forbid") + ẩn danh PII vàsafetensors(0pickle,diff = 0.0,1.59 ms/CV) đạt chuẩn triển khai sản xuất.
5.3 Sáu Bài tập Chuyên sâu & Thang chấm Rubric (ex1..ex6)#
- Bài tập 1 (
15%) — Chuẩn hóa Unicode,Byte-Level BPE& Kinh tế họcTokenizer Fertility: Chứng minh vì saoByte-Level BPEtrên256byte UTF-8 luôn bảo toàn giải mã100%không<UNK>, phân tích định lượng ảnh hưởng của hệ số thuế Fertility \(\kappa = \mathcal{F}_{\text{VI}}/\mathcal{F}_{\text{EN}}\) lên chi phí API,KV Cachevà độ phức tạp prefill \(O(L^2)\), và tái lập kết quả giảm-59.7%Fertility tiếng Việt trênTests 02–04. - Bài tập 2 (
15%) — Bão hòaOkapi BM25& Định lý Phân rãShifted-PMIcủaWord2Vec SGNS: Chứng minh cận trên bão hòa \((k_1 + 1)\operatorname{IDF}(t)\) củaBM25khi \(f(t, d) \to \infty\), dẫn xuất gradient giải tích của \(\mathcal{L}_{\text{SGNS}}\) và chứng minh tại điểm dừng \(\mathbf{v}_w^\top \mathbf{u}_c = \operatorname{PMI}(w,c) - \log K_{\text{neg}}\) (đối chiếu tương quanr = 0.69trênTests 05–06). - Bài tập 3 (
15%) — Giải phẫuBPTT, Cắt chuẩn Gradient & Cao tốc Ô nhớLSTM/GRU: Chứng minh cận suy giảm hàm mũ \(\gamma^{T-k}\) củaVanilla RNN, giải thích vì saoGlobal L2 Clippingbảo toàn hướng (cosine = 1.0000) nhưng không chữa được triệt tiêu gradient, phân tích quy ước dấu cổng cập nhậtz_ttrongtorch.nn.GRU, và kiểm chứngRNN 49.2%vsLSTM/GRU 100.0%ở \(T = 36\) (Tests 07–09). - Bài tập 4 (
15%) — Kiểm toán Trung thực Giải thích Văn bản (Token IG&ERASER): Chứng minh tiên đề Completeness \(\sum_t \operatorname{IG}_t = F_c(\mathbf{E}) - F_c(\mathbf{E}')\), giải thích lợi thế hội tụ của cầu phương ghép Gauss–Legendre vector hóa so với tổng Riemann thô trên hàmBiLSTMsắc nét, và phân tích đối chứngComprehensiveness(0.565vs0.085) &Sufficiency(-0.001vs0.179) (Test 10). - Bài tập 5 (
20%) — Thuật toán Forward log-sum-exp, Giải mã Viterbi & Word Dropout choBiLSTM-CRF: Dẫn xuất đệ quy Forward và Viterbi trong \(O(TK^2)\), chứng minh bất biến ngữ phápBIObằng mặt nạ phạt \(-10^4\), phân tích vai trò của word dropout<UNK>giúp khái quát hóa thực thểPERSONmới trên tập tách nhóm ứng viên, và kiểm chứng sai số3.52e-07cùng0.00%lỗi BIO (Tests 11–13). - Bài tập 6 (
20%) — Hệ thống Resume Document AI Đa cột (XY-Cut,Pydantic v2,safetensors) & Chạy Toàn trìnhLab 10: Giải thích nguyên lý chiếu hình học tìm khe cột dọc củaRecursive XY-Cut(phục hồi0% -> 100%trên CV 2 cột), thiết kế kiến trúc phối hợpBiLSTM-CRF+GLiNER+Doclingfallback kèm ẩn danh PII tuân thủ EU AI Act, và chạy trọn bộruff,mypy,16/16 pytestcùngscripts/run_lab_demo.py(Tests 14–16).
| Tiêu chí Rubric | Đạt (Pass, 60–74%) |
Khá (Merit, 75–84%) |
Xuất sắc (Distinction, 85–100%) |
|---|---|---|---|
Chứng minh Toán học (ex1, ex2, ex3, ex5) |
Viết đúng công thức BM25, SGNS, BPTT, CRF |
Chứng minh đầy đủ bước biến đổi Shifted-PMI, Jacobian BPTT và đệ quy Forward/Viterbi |
Phân tích sắc sảo thuế Fertility \(O(L^2)\), lưu ý nn.GRU và độ hội tụ Gauss–Legendre cho Token IG |
Thực nghiệm & Kiểm thử (Lab 10) |
Vượt qua 16/16 pytest, xuất đúng JSON |
Đạt 0 lỗi ruff/mypy, kiểm toán đủ BPE, BPTT, CRF, XY-Cut, safetensors |
Phân tích sâu ảnh hưởng word dropout <UNK>, so sánh Clean vs 25% OCR Noise và đề xuất mở rộng GLiNER |
| Kiến trúc Sản xuất Document AI | Mô tả được luồng PDF \(\to\) NER \(\to\) JSON | Định lượng được SLA CPU < 2 ms, ẩn danh PII và kiểm toán ERASER |
Thiết kế hoàn chỉnh kiến trúc phân tầng XY-Cut + Docling fallback + cổng CI/CD cấm pickle và chặn rò rỉ nhóm |
Byte-Level BPE Fertility: English vs Vietnamese vs Code (Tokens / Word)
Long-Range Dependency Benchmark (T=36): Vanilla RNN vs LSTM vs GRU (%)
Resume NER Span Exact F1 (%): BiLSTM-Softmax vs BiLSTM-CRF
Token Integrated Gradients Faithfulness (ERASER): Comp & Suff
Tier 1 NLP: Unicode NFC, Byte-Level BPE, Okapi BM25 & Word2Vec SGNS
| Component | Configuration | Measured Metric | Status |
|---|---|---|---|
| Unicode NFC & Safe Cleanup | NFC vs Destructive Strip | Safe keeps 10 NER/code signals vs 0 destructive | PASS |
| Byte-Level BPE (EN vs Multi) | |V|=512 vs 640 | Lossless=True | VI Fertility 5.74 -> 2.32 (-59.7%) | PASS |
| Okapi BM25 vs TF-IDF Retrieval | k1=1.5, b=0.75 (4 queries) | BM25 MRR=1.000 vs TF-IDF=0.875; True 3.27 > Spam 2.38 | PASS |
| Word2Vec SGNS (Pure NumPy) | d=20, K=4 | Loss 2.874 -> 1.022 | cos(bilstm,crf)=0.51 vs basel=0.35 | PASS |
Tier 2 Sequence Models: BPTT Gradient Pathology, Clipping & Recall (T=36)
| Model / Regime | Grad Ratio ||g_1||/||g_T|| | T=36 Test Acc | Notes |
|---|---|---|---|
| Vanilla RNN (Vanishing rho=0.68) | 7.36e-07 | 49.2% | Exponential Jacobian decay blocks long-range recall |
| Vanilla RNN (Exploding rho=1.45/1.60) | 1.84e+01 | Unstable unclipped | Clip(tau=1.0): 27.75 -> 1.000 (cos=1.0000) |
| LSTM (Forget Bias b_f=1.5/2.0) | c_t=0.319 | h_t=0.035 | 100.0% | Additive cell highway (6,722 params) |
| GRU & Hybrid CNN-LSTM | Gated update (1-z_t) | GRU 100.0% | CNN-LSTM 100.0% | GRU params=5,122 (~25% fewer weights) |
Resume Document AI: BiLSTM-CRF, XY-Cut Layout & Zero-Pickle Deployment
| Pipeline Component | Clean Metric | Stress Metric | Production Invariant |
|---|---|---|---|
| BiLSTM-Softmax (Independent) | Span F1=100.0% | Noisy F1=93.2% | Illegal BIO=2.86% (57 errs) |
| BiLSTM-CRF (Forward + Viterbi) | Span F1=99.1% | Noisy F1=96.4% | 0.00% illegal BIO | log Z parity err=3.52e-07 |
| 2-Column Resume Reading Order | XY-Cut Exact=100.0% | Naive Y-Sort=0.0% | Pairwise: XY-Cut 100.0% vs Y-Sort 71.4% |
| Pydantic v2 + Safetensors CPU | Valid JSON (3 skills) | CPU Viterbi=1.63 ms/CV | safetensors=87,708 B | max diff=0.0e+00 | PII redacted |
Text Classification XAI: Token Integrated Gradients & ERASER Faithfulness
| Method | Comprehensiveness | Sufficiency | Axiom / Rationale Check |
|---|---|---|---|
| Token Integrated Gradients (M=96) | 0.5650 | -0.0006 | Completeness err=8.09e-02 | Top-3 Hit=83.3% |
| Random Token Masking Baseline | 0.0845 | 0.1795 | Uninformative baseline reference |
| BiLSTM Domain Router (3-Class) | Test Acc=100.0% | Evaluated=24 docs | Direct embedding interpolation from E'=0 |
| Hybrid CNN-LSTM Domain Router | Test Acc=100.0% | Conv1d(k=3) + LSTM | Local n-gram filter + sequential pooling |
02-track-1-data-science-and-ai/part-04-nlp-llm-post-training-and-safety/labs/lab-10-text-processing-and-resume-document-ai
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "nlp-docai-lab"
version = "0.1.0"
description = "Lab 10: Text Processing & Analysis 101 (Byte-Level BPE, Fertility, Okapi BM25, Word2Vec SGNS), Sequence Models (BPTT Vanishing/Exploding Gradients, LSTM/GRU/CNN-LSTM, Token Integrated Gradients), and Resume Document AI (XY-Cut Layout, BiLSTM-CRF, Pydantic v2, Safetensors) for T1-P4-U01."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pydantic>=2.0",
"safetensors>=0.4",
"scikit-learn>=1.5",
"scipy>=1.12",
"torch>=2.5",
]
[project.optional-dependencies]
dev = [
"hypothesis>=6.100",
"mypy>=1.11",
"pytest>=8.0",
"ruff>=0.6",
]
[[tool.uv.index]]
name = "pytorch-cpu"
url = "https://download.pytorch.org/whl/cpu"
explicit = true
[tool.uv.sources]
torch = { index = "pytorch-cpu" }
[tool.setuptools]
package-dir = {"" = "src"}
[tool.setuptools.packages.find]
where = ["src"]
[tool.pytest.ini_options]
pythonpath = ["src"]
testpaths = ["tests"]
addopts = "-v"
[tool.ruff]
line-length = 110
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
[tool.mypy]
python_version = "3.12"
ignore_missing_imports = true
warn_unused_ignores = true
"""Lab 10 (`T1-P4-U01`): NLP Pipelines, Byte-Level BPE, BM25, Sequence Models & Resume Document AI."""
from __future__ import annotations
from nlp_docai_lab.bilstm_crf_resume_ie import (
BiLSTMCRF,
BiLSTMSoftmaxTagger,
CRFTrainConfig,
LinearChainCRF,
ResumeProfile,
compute_bio_span_f1,
compute_illegal_bio_rate,
load_bilstm_crf_safetensors,
parse_resume_layout_to_profile,
save_bilstm_crf_safetensors,
train_resume_ner_models,
)
from nlp_docai_lab.resume_dataset import (
BIO_TAGS,
ENTITY_TYPES,
TAG_TO_ID,
LayoutBox,
ResumeNERTokenExample,
build_token_vocab,
generate_domain_classification_corpus,
generate_resume_ner_dataset,
generate_two_column_layout_resumes,
naive_y_sort_reading_order,
xy_cut_reading_order,
)
from nlp_docai_lab.sequence_models import (
BiLSTMTextClassifier,
CNNLSTMClassifier,
GRUClassifier,
LongRangeConfig,
LSTMClassifier,
VanillaRNNClassifier,
compute_token_integrated_gradients,
demonstrate_gradient_clipping,
evaluate_text_xai_faithfulness,
measure_bptt_gradient_flow,
train_domain_text_classifier,
train_long_range_benchmark,
)
from nlp_docai_lab.tokenization_and_bm25 import (
BM25Index,
ByteLevelBPETokenizer,
SGNSConfig,
TfidfRetriever,
compare_cleanup_modes,
compute_shifted_pmi_matrix,
compute_tokenizer_fertility,
normalize_text_unicode,
train_word2vec_sgns,
)
__all__ = [
"BIO_TAGS",
"BM25Index",
"BiLSTMCRF",
"BiLSTMSoftmaxTagger",
"BiLSTMTextClassifier",
"ByteLevelBPETokenizer",
"CNNLSTMClassifier",
"CRFTrainConfig",
"ENTITY_TYPES",
"GRUClassifier",
"LSTMClassifier",
"LayoutBox",
"LinearChainCRF",
"LongRangeConfig",
"ResumeNERTokenExample",
"ResumeProfile",
"SGNSConfig",
"TAG_TO_ID",
"TfidfRetriever",
"VanillaRNNClassifier",
"build_token_vocab",
"compare_cleanup_modes",
"compute_bio_span_f1",
"compute_illegal_bio_rate",
"compute_shifted_pmi_matrix",
"compute_token_integrated_gradients",
"compute_tokenizer_fertility",
"demonstrate_gradient_clipping",
"evaluate_text_xai_faithfulness",
"generate_domain_classification_corpus",
"generate_resume_ner_dataset",
"generate_two_column_layout_resumes",
"load_bilstm_crf_safetensors",
"measure_bptt_gradient_flow",
"naive_y_sort_reading_order",
"normalize_text_unicode",
"parse_resume_layout_to_profile",
"save_bilstm_crf_safetensors",
"train_domain_text_classifier",
"train_long_range_benchmark",
"train_resume_ner_models",
"train_word2vec_sgns",
"xy_cut_reading_order",
]
"""Tier 1 NLP Core: Unicode Normalization, Byte-Level BPE, Fertility, Okapi BM25 & Word2Vec SGNS."""
from __future__ import annotations
import math
import re
import unicodedata
from collections import Counter
from typing import Literal
import numpy as np
from pydantic import BaseModel, ConfigDict, Field
from sklearn.feature_extraction.text import TfidfVectorizer
_CONTROL_WS_RE = re.compile(r"[\t\r\n]+")
_MULTI_SPACE_RE = re.compile(r" {2,}")
_PRETOKEN_RE = re.compile(r"\s+|\w+|[^\w\s]", re.UNICODE)
_WORD_RE = re.compile(r"\w+(?:[+#.-]\w+)*", re.UNICODE)
def normalize_text_unicode(text: str, form: Literal["NFC", "NFKC"] = "NFC") -> str:
"""Normalize Unicode canonical/compatibility form and collapse erratic control whitespace."""
norm = unicodedata.normalize(form, text)
norm = _CONTROL_WS_RE.sub(" ", norm)
return _MULTI_SPACE_RE.sub(" ", norm).strip()
def compare_cleanup_modes(text: str) -> dict[str, str | int]:
"""Contrast structure-preserving NFC cleanup against naive destructive NLP cleanup."""
safe = normalize_text_unicode(text, form="NFC")
# Naive destructive cleanup strips case, punctuation, and digits -> destroys C++, Python 3.12, NER cues.
destructive = re.sub(r"[^a-z\s]", " ", safe.lower())
destructive = _MULTI_SPACE_RE.sub(" ", destructive).strip()
safe_tokens = re.findall(r"[A-Za-z0-9_+#.-]+", safe)
destructive_tokens = destructive.split()
preserved_tech = sum(
1 for tok in safe_tokens if any(ch.isupper() or ch.isdigit() or ch in "+#.-" for ch in tok)
)
survived_tech = sum(
1 for tok in destructive_tokens if any(ch.isupper() or ch.isdigit() or ch in "+#.-" for ch in tok)
)
return {
"safe_text": safe,
"destructive_text": destructive,
"safe_special_signal_count": preserved_tech,
"destructive_special_signal_count": survived_tech,
}
def _merge_pair_in_seq(seq: list[int], pair: tuple[int, int], new_id: int) -> list[int]:
"""Merge all non-overlapping adjacent occurrences of pair -> new_id in one pass."""
a, b = pair
out: list[int] = []
i = 0
n = len(seq)
while i < n:
if i + 1 < n and seq[i] == a and seq[i + 1] == b:
out.append(new_id)
i += 2
else:
out.append(seq[i])
i += 1
return out
class ByteLevelBPETokenizer:
"""Lossless Byte-Level BPE tokenizer initialized over all 256 UTF-8 bytes (zero <UNK>)."""
def __init__(self) -> None:
self.merges: dict[tuple[int, int], int] = {}
self.merge_order: list[tuple[tuple[int, int], int]] = []
self.id_to_bytes: dict[int, bytes] = {i: bytes([i]) for i in range(256)}
self.vocab_size: int = 256
def train(self, texts: list[str], vocab_size: int = 512, min_freq: int = 2) -> dict[str, int]:
"""Train BPE merge rules greedily over UTF-8 byte chunks without crossing pre-token boundaries."""
if vocab_size < 256:
raise ValueError("vocab_size must be >= 256 for Byte-Level BPE")
self.merges = {}
self.merge_order = []
self.id_to_bytes = {i: bytes([i]) for i in range(256)}
# Count unique pre-token chunks so training is fast and deterministic.
chunk_counts: Counter[tuple[int, ...]] = Counter()
for raw in texts:
norm = unicodedata.normalize("NFC", raw)
for piece in _PRETOKEN_RE.findall(norm):
chunk_counts[tuple(piece.encode("utf-8"))] += 1
seqs: list[list[int]] = [list(k) for k in chunk_counts]
freqs: list[int] = [chunk_counts[tuple(s)] for s in seqs]
next_id = 256
target_merges = vocab_size - 256
for _ in range(target_merges):
pair_counts: Counter[tuple[int, int]] = Counter()
for seq, freq in zip(seqs, freqs, strict=True):
if len(seq) < 2:
continue
for j in range(len(seq) - 1):
pair_counts[(seq[j], seq[j + 1])] += freq
if not pair_counts:
break
# Deterministic tie-breaking: highest frequency first, then lexicographically smallest pair.
best_pair, best_freq = min(pair_counts.items(), key=lambda kv: (-kv[1], kv[0]))
if best_freq < min_freq:
break
self.merges[best_pair] = next_id
self.merge_order.append((best_pair, next_id))
self.id_to_bytes[next_id] = self.id_to_bytes[best_pair[0]] + self.id_to_bytes[best_pair[1]]
for idx, seq in enumerate(seqs):
if len(seq) >= 2:
seqs[idx] = _merge_pair_in_seq(seq, best_pair, next_id)
next_id += 1
self.vocab_size = next_id
return {
"base_bytes": 256,
"num_merges": len(self.merge_order),
"vocab_size": self.vocab_size,
}
def _encode_piece(self, piece: str) -> list[int]:
ids = list(piece.encode("utf-8"))
if len(ids) < 2 or not self.merges:
return ids
while len(ids) >= 2:
best_rank: int | None = None
best_pair: tuple[int, int] | None = None
for j in range(len(ids) - 1):
pair = (ids[j], ids[j + 1])
rank = self.merges.get(pair)
if rank is not None and (best_rank is None or rank < best_rank):
best_rank = rank
best_pair = pair
if best_pair is None or best_rank is None:
break
ids = _merge_pair_in_seq(ids, best_pair, best_rank)
return ids
def encode(self, text: str, normalize_nfc: bool = False) -> list[int]:
"""Encode arbitrary Unicode string into lossless byte-level BPE token IDs."""
src = unicodedata.normalize("NFC", text) if normalize_nfc else text
out: list[int] = []
for piece in _PRETOKEN_RE.findall(src):
out.extend(self._encode_piece(piece))
return out
def decode(self, token_ids: list[int]) -> str:
"""Decode token IDs back to exact UTF-8 string (lossless on valid sequences)."""
raw = b"".join(self.id_to_bytes[tid] for tid in token_ids)
return raw.decode("utf-8", errors="strict")
def compute_tokenizer_fertility(tokenizer: ByteLevelBPETokenizer, texts: list[str]) -> dict[str, float]:
"""Measure Tokenizer Fertility (tokens/word), bytes/token compression, and word count."""
total_tokens = 0
total_words = 0
total_bytes = 0
for text in texts:
ids = tokenizer.encode(text, normalize_nfc=False)
words = _WORD_RE.findall(text)
total_tokens += len(ids)
total_words += max(1, len(words))
total_bytes += len(text.encode("utf-8"))
fertility = float(total_tokens) / float(max(1, total_words))
bytes_per_token = float(total_bytes) / float(max(1, total_tokens))
return {
"total_tokens": float(total_tokens),
"total_words": float(total_words),
"fertility_tokens_per_word": fertility,
"bytes_per_token": bytes_per_token,
}
def _lexical_tokenize(text: str) -> list[str]:
"""Simple case-folded lexical tokenizer keeping technical tokens like c++, python3, iso-20022."""
norm = normalize_text_unicode(text, form="NFKC").lower()
return re.findall(r"[a-z0-9_+#-]+", norm)
class BM25Index:
"""Exact Okapi BM25 retriever with term saturation k1 and length normalization b."""
def __init__(self, documents: list[str], k1: float = 1.5, b: float = 0.75) -> None:
if k1 < 0.0 or not (0.0 <= b <= 1.0):
raise ValueError("BM25 requires k1 >= 0 and 0 <= b <= 1")
self.k1 = float(k1)
self.b = float(b)
self.documents = list(documents)
self.tokenized_docs: list[list[str]] = [_lexical_tokenize(d) for d in self.documents]
self.doc_lens: list[int] = [len(toks) for toks in self.tokenized_docs]
self.n_docs: int = len(self.documents)
self.avgdl: float = float(sum(self.doc_lens)) / float(max(1, self.n_docs))
self.term_freqs: list[Counter[str]] = [Counter(toks) for toks in self.tokenized_docs]
self.doc_freqs: Counter[str] = Counter()
for tf in self.term_freqs:
for term in tf:
self.doc_freqs[term] += 1
self.idf: dict[str, float] = {
term: math.log(1.0 + (self.n_docs - df + 0.5) / (df + 0.5))
for term, df in self.doc_freqs.items()
}
def score_document(self, query: str, doc_idx: int) -> float:
"""Compute exact Okapi BM25 score for (query, documents[doc_idx])."""
q_terms = _lexical_tokenize(query)
tf_map = self.term_freqs[doc_idx]
dl = float(self.doc_lens[doc_idx])
denom_norm = self.k1 * (1.0 - self.b + self.b * (dl / max(self.avgdl, 1e-9)))
score = 0.0
for term in q_terms:
f = float(tf_map.get(term, 0))
if f <= 0.0:
continue
idf = self.idf.get(term, 0.0)
score += idf * (f * (self.k1 + 1.0)) / (f + denom_norm)
return score
def rank(self, query: str, top_k: int = 5) -> list[tuple[int, float]]:
"""Rank all documents by descending Okapi BM25 score (deterministic tie-break)."""
scored = [(idx, self.score_document(query, idx)) for idx in range(self.n_docs)]
scored.sort(key=lambda pair: (-pair[1], pair[0]))
return scored[:top_k]
class TfidfRetriever:
"""Classical TF-IDF cosine retriever (without BM25 saturation) for controlled comparison."""
def __init__(self, documents: list[str]) -> None:
self.documents = list(documents)
self.vectorizer = TfidfVectorizer(
tokenizer=_lexical_tokenize,
token_pattern=None,
lowercase=False,
sublinear_tf=False,
)
self.doc_matrix = self.vectorizer.fit_transform(self.documents)
def rank(self, query: str, top_k: int = 5) -> list[tuple[int, float]]:
q_vec = self.vectorizer.transform([query])
scores = np.asarray((self.doc_matrix @ q_vec.T).toarray()).ravel()
order = sorted(range(len(self.documents)), key=lambda i: (-float(scores[i]), i))
return [(idx, float(scores[idx])) for idx in order[:top_k]]
class SGNSConfig(BaseModel):
"""Strict configuration for Pure-NumPy Word2Vec Skip-Gram with Negative Sampling."""
model_config = ConfigDict(extra="forbid")
embedding_dim: int = Field(default=24, ge=4, le=256)
window_size: int = Field(default=2, ge=1, le=8)
num_negatives: int = Field(default=5, ge=1, le=20)
epochs: int = Field(default=45, ge=5, le=300)
learning_rate: float = Field(default=0.08, gt=0.0, le=1.0)
min_count: int = Field(default=1, ge=1)
seed: int = 42
def _sigmoid_np(x: np.ndarray) -> np.ndarray:
x_clip = np.clip(x, -15.0, 15.0)
return 1.0 / (1.0 + np.exp(-x_clip))
def train_word2vec_sgns(
sentences: list[list[str]],
config: SGNSConfig | None = None,
) -> dict[str, object]:
"""Train Word2Vec Skip-Gram with Negative Sampling (SGNS) analytically in pure NumPy."""
cfg = config or SGNSConfig()
rng = np.random.default_rng(cfg.seed)
counts: Counter[str] = Counter(tok for sent in sentences for tok in sent)
vocab_words = sorted(w for w, c in counts.items() if c >= cfg.min_count)
word_to_id = {w: i for i, w in enumerate(vocab_words)}
vocab_size = len(vocab_words)
if vocab_size < 4:
raise ValueError("Vocabulary too small for Word2Vec SGNS")
# Unigram^{3/4} negative sampling distribution (Mikolov et al. 2013)
raw_freq = np.array([counts[w] for w in vocab_words], dtype=np.float64)
neg_probs = np.power(raw_freq, 0.75)
neg_probs = neg_probs / neg_probs.sum()
pairs: list[tuple[int, int]] = []
for sent in sentences:
ids = [word_to_id[w] for w in sent if w in word_to_id]
for pos, center in enumerate(ids):
lo = max(0, pos - cfg.window_size)
hi = min(len(ids), pos + cfg.window_size + 1)
for ctx_pos in range(lo, hi):
if ctx_pos != pos:
pairs.append((center, ids[ctx_pos]))
w_in = rng.normal(0.0, 0.15, size=(vocab_size, cfg.embedding_dim)).astype(np.float64)
w_out = rng.normal(0.0, 0.15, size=(vocab_size, cfg.embedding_dim)).astype(np.float64)
loss_history: list[float] = []
pair_arr = np.array(pairs, dtype=np.int64)
n_pairs = len(pair_arr)
for epoch in range(cfg.epochs):
order = rng.permutation(n_pairs)
lr = cfg.learning_rate * max(0.15, 1.0 - epoch / float(cfg.epochs))
epoch_loss = 0.0
for idx in order:
center_id = int(pair_arr[idx, 0])
pos_id = int(pair_arr[idx, 1])
neg_ids = rng.choice(vocab_size, size=cfg.num_negatives, replace=True, p=neg_probs)
v_c = w_in[center_id]
u_pos = w_out[pos_id]
u_neg = w_out[neg_ids]
pos_dot = float(np.dot(u_pos, v_c))
pos_sig = float(_sigmoid_np(np.array([pos_dot]))[0])
neg_dots = u_neg @ v_c
neg_sigs = _sigmoid_np(neg_dots)
epoch_loss += -math.log(max(pos_sig, 1e-12)) - float(
np.sum(np.log(np.maximum(1.0 - neg_sigs, 1e-12)))
)
# Exact gradients of L = -log(sig(u_pos . v_c)) - sum log(sig(-u_neg . v_c))
grad_pos = pos_sig - 1.0
grad_neg = neg_sigs # shape (K,)
grad_vc = grad_pos * u_pos + (grad_neg[:, None] * u_neg).sum(axis=0)
w_out[pos_id] -= lr * (grad_pos * v_c)
for k_idx, nid in enumerate(neg_ids):
w_out[int(nid)] -= lr * (float(grad_neg[k_idx]) * v_c)
w_in[center_id] -= lr * grad_vc
loss_history.append(epoch_loss / float(max(1, n_pairs)))
# L2-normalized embeddings for cosine similarity queries
norms = np.linalg.norm(w_in, axis=1, keepdims=True)
emb_norm = w_in / np.maximum(norms, 1e-12)
return {
"word_to_id": word_to_id,
"w_in": w_in,
"w_out": w_out,
"embeddings_norm": emb_norm,
"loss_history": loss_history,
"initial_loss": float(loss_history[0]),
"final_loss": float(loss_history[-1]),
"num_pairs": n_pairs,
}
def compute_shifted_pmi_matrix(
sentences: list[list[str]],
word_to_id: dict[str, int],
window_size: int = 2,
num_negatives: int = 5,
) -> np.ndarray:
"""Compute Levy & Goldberg (2014) Shifted-PMI matrix log(P(w,c)/(P(w)P(c))) - log(K)."""
vocab_size = len(word_to_id)
cooc = np.zeros((vocab_size, vocab_size), dtype=np.float64)
for sent in sentences:
ids = [word_to_id[w] for w in sent if w in word_to_id]
for pos, center in enumerate(ids):
lo = max(0, pos - window_size)
hi = min(len(ids), pos + window_size + 1)
for ctx_pos in range(lo, hi):
if ctx_pos != pos:
cooc[center, ids[ctx_pos]] += 1.0
total = max(float(cooc.sum()), 1.0)
row_sum = cooc.sum(axis=1, keepdims=True)
col_sum = cooc.sum(axis=0, keepdims=True)
with np.errstate(divide="ignore", invalid="ignore"):
ratio = (cooc * total) / np.maximum(row_sum * col_sum, 1e-12)
spmi = np.where(cooc > 0.0, np.log(np.maximum(ratio, 1e-12)) - math.log(num_negatives), 0.0)
return spmi.astype(np.float64)
"""Deterministic Synthetic Resume NER, 2-Column Layout Document AI & Domain Classification Corpora."""
from __future__ import annotations
from dataclasses import dataclass
import numpy as np
ENTITY_TYPES: tuple[str, ...] = ("PERSON", "ROLE", "SKILL", "ORG", "EDU")
BIO_TAGS: tuple[str, ...] = (
"O",
"B-PERSON",
"I-PERSON",
"B-ROLE",
"I-ROLE",
"B-SKILL",
"I-SKILL",
"B-ORG",
"I-ORG",
"B-EDU",
"I-EDU",
)
TAG_TO_ID: dict[str, int] = {tag: idx for idx, tag in enumerate(BIO_TAGS)}
ID_TO_TAG: dict[int, str] = {idx: tag for idx, tag in enumerate(BIO_TAGS)}
_PERSONS: list[list[str]] = [
["Nguyen", "Minh", "Anh"],
["Tran", "Quoc", "Bao"],
["Le", "Thu", "Ha"],
["Pham", "Duc", "Huy"],
["Hoang", "Lan", "Phuong"],
["Vo", "Tuan", "Kiet"],
["Dang", "Ngoc", "Linh"],
["Bui", "Gia", "Huy"],
["Elena", "Vance"],
["Marcus", "Chen"],
["Priya", "Nair"],
["David", "Kowalski"],
]
_ROLES: list[list[str]] = [
["Senior", "ML", "Engineer"],
["Staff", "NLP", "Scientist"],
["Lead", "Data", "Engineer"],
["Document", "AI", "Architect"],
["Principal", "AI", "Engineer"],
["Applied", "Research", "Scientist"],
["Machine", "Learning", "Specialist"],
["Quantitative", "Risk", "Engineer"],
]
_SKILLS: list[list[str]] = [
["PyTorch", "2.x"],
["BiLSTM", "CRF"],
["Byte-Level", "BPE"],
["Okapi", "BM25"],
["Apache", "Kafka"],
["Delta", "Lake"],
["Python", "3.12"],
["C++", "CUDA"],
["LayoutLMv3", "OCR"],
["Pydantic", "v2"],
["SQL", "DuckDB"],
["FastAPI", "Docker"],
]
_ORGS: list[list[str]] = [
["VNG", "Cloud"],
["TechBank", "Vietnam"],
["FPT", "AI", "Lab"],
["VinAI", "Research"],
["MoMo", "Fintech"],
["Grab", "Engineering"],
["Shopee", "Data", "Platform"],
["Viettel", "AI", "Center"],
]
_EDUS: list[list[str]] = [
["MSc", "Computer", "Science", "UCL"],
["BSc", "Data", "Science", "HUST"],
["MSc", "Artificial", "Intelligence", "HCMUS"],
["BEng", "Software", "Engineering", "UIT"],
["PhD", "Machine", "Learning", "NUS"],
["MSc", "Quantitative", "Finance", "NTU"],
]
@dataclass(frozen=True, slots=True)
class ResumeNERTokenExample:
"""One BIO-tagged resume token sequence with deterministic candidate group ID."""
candidate_id: int
tokens: list[str]
tags: list[str]
@dataclass(frozen=True, slots=True)
class LayoutBox:
"""2D PDF bounding box representing one line or span on a resume page."""
x0: float
y0: float
x1: float
y1: float
text: str
column_id: int
true_order: int
entity_hint: str
def _append_entity(tokens: list[str], tags: list[str], span: list[str], ent_type: str) -> None:
for idx, tok in enumerate(span):
tokens.append(tok)
tags.append(f"B-{ent_type}" if idx == 0 else f"I-{ent_type}")
def _append_outside(tokens: list[str], tags: list[str], words: list[str]) -> None:
for tok in words:
tokens.append(tok)
tags.append("O")
def generate_resume_ner_dataset(
n_train: int = 240,
n_test: int = 80,
seed: int = 42,
) -> dict[str, list[ResumeNERTokenExample]]:
"""Generate deterministic group-separated Resume NER train/test sequences with BIO tags."""
rng = np.random.default_rng(seed)
# Disjoint candidate pools prevent entity memorization leakage between train and test splits.
train_persons = _PERSONS[:8]
test_persons = _PERSONS[8:]
templates: list[int] = [0, 1, 2, 3]
def _build_split(count: int, person_pool: list[list[str]], id_offset: int) -> list[ResumeNERTokenExample]:
examples: list[ResumeNERTokenExample] = []
for idx in range(count):
person = person_pool[int(rng.integers(0, len(person_pool)))]
role = _ROLES[int(rng.integers(0, len(_ROLES)))]
skill_indices = rng.choice(len(_SKILLS), size=2, replace=False)
skill1 = _SKILLS[int(skill_indices[0])]
skill2 = _SKILLS[int(skill_indices[1])]
org = _ORGS[int(rng.integers(0, len(_ORGS)))]
edu = _EDUS[int(rng.integers(0, len(_EDUS)))]
tpl = templates[int(rng.integers(0, len(templates)))]
tokens: list[str] = []
tags: list[str] = []
if tpl == 0:
_append_outside(tokens, tags, ["Candidate"])
_append_entity(tokens, tags, person, "PERSON")
_append_outside(tokens, tags, ["worked", "as"])
_append_entity(tokens, tags, role, "ROLE")
_append_outside(tokens, tags, ["at"])
_append_entity(tokens, tags, org, "ORG")
_append_outside(tokens, tags, ["using"])
_append_entity(tokens, tags, skill1, "SKILL")
_append_outside(tokens, tags, ["and"])
_append_entity(tokens, tags, skill2, "SKILL")
_append_outside(tokens, tags, ["with"])
_append_entity(tokens, tags, edu, "EDU")
elif tpl == 1:
_append_outside(tokens, tags, ["Profile"])
_append_entity(tokens, tags, person, "PERSON")
_append_outside(tokens, tags, ["|"])
_append_entity(tokens, tags, role, "ROLE")
_append_outside(tokens, tags, ["|"])
_append_entity(tokens, tags, org, "ORG")
_append_outside(tokens, tags, ["Skills"])
_append_entity(tokens, tags, skill1, "SKILL")
_append_outside(tokens, tags, [","])
_append_entity(tokens, tags, skill2, "SKILL")
_append_outside(tokens, tags, ["Education"])
_append_entity(tokens, tags, edu, "EDU")
elif tpl == 2:
_append_entity(tokens, tags, person, "PERSON")
_append_outside(tokens, tags, ["graduated", "from"])
_append_entity(tokens, tags, edu, "EDU")
_append_outside(tokens, tags, ["and", "joined"])
_append_entity(tokens, tags, org, "ORG")
_append_outside(tokens, tags, ["as"])
_append_entity(tokens, tags, role, "ROLE")
_append_outside(tokens, tags, ["building"])
_append_entity(tokens, tags, skill1, "SKILL")
_append_outside(tokens, tags, ["with"])
_append_entity(tokens, tags, skill2, "SKILL")
else:
_append_outside(tokens, tags, ["Resume"])
_append_entity(tokens, tags, person, "PERSON")
_append_outside(tokens, tags, ["specializes", "in"])
_append_entity(tokens, tags, skill1, "SKILL")
_append_outside(tokens, tags, ["and"])
_append_entity(tokens, tags, skill2, "SKILL")
_append_outside(tokens, tags, ["as"])
_append_entity(tokens, tags, role, "ROLE")
_append_outside(tokens, tags, ["at"])
_append_entity(tokens, tags, org, "ORG")
_append_outside(tokens, tags, ["holding"])
_append_entity(tokens, tags, edu, "EDU")
examples.append(
ResumeNERTokenExample(
candidate_id=id_offset + idx,
tokens=tokens,
tags=tags,
)
)
return examples
return {
"train": _build_split(n_train, train_persons, id_offset=1000),
"test": _build_split(n_test, test_persons, id_offset=5000),
}
def build_token_vocab(examples: list[ResumeNERTokenExample], min_freq: int = 1) -> dict[str, int]:
"""Build deterministic token vocabulary with <PAD>=0 and <UNK>=1."""
counts: dict[str, int] = {}
for ex in examples:
for tok in ex.tokens:
counts[tok] = counts.get(tok, 0) + 1
vocab = {"<PAD>": 0, "<UNK>": 1}
for tok in sorted(counts):
if counts[tok] >= min_freq:
vocab[tok] = len(vocab)
return vocab
def generate_two_column_layout_resumes(n_docs: int = 24, seed: int = 42) -> list[list[LayoutBox]]:
"""Generate realistic 2-column PDF resumes with a clear vertical gutter (x in [430, 480])."""
rng = np.random.default_rng(seed)
docs: list[list[LayoutBox]] = []
for idx in range(n_docs):
person = " ".join(_PERSONS[idx % len(_PERSONS)])
role = " ".join(_ROLES[int(rng.integers(0, len(_ROLES)))])
skill_idx = rng.choice(len(_SKILLS), size=2, replace=False)
skill1 = " ".join(_SKILLS[int(skill_idx[0])])
skill2 = " ".join(_SKILLS[int(skill_idx[1])])
org = " ".join(_ORGS[int(rng.integers(0, len(_ORGS)))])
edu = " ".join(_EDUS[int(rng.integers(0, len(_EDUS)))])
# Left column: x in [40, 410]; Right column: x in [500, 960] -> clear vertical gutter [410, 500].
# Overlapping y coordinates intentionally expose the naive y-sort interleaving failure mode!
boxes = [
# Left column (true reading order 0..3)
LayoutBox(40.0, 60.0, 400.0, 92.0, f"Candidate {person}", 0, 0, "PERSON"),
LayoutBox(40.0, 120.0, 400.0, 152.0, f"Skills {skill1}", 0, 1, "SKILL"),
LayoutBox(40.0, 178.0, 400.0, 210.0, f"and {skill2}", 0, 2, "SKILL"),
LayoutBox(40.0, 240.0, 400.0, 272.0, f"Education {edu}", 0, 3, "EDU"),
# Right column (true reading order 4..6) — y values overlap left column!
LayoutBox(500.0, 68.0, 950.0, 100.0, f"worked as {role}", 1, 4, "ROLE"),
LayoutBox(500.0, 128.0, 950.0, 160.0, f"at {org}", 1, 5, "ORG"),
LayoutBox(500.0, 188.0, 950.0, 220.0, "with production deployment", 1, 6, "O"),
]
# Shuffle storage order as raw PDF stream objects often appear out-of-order.
perm = rng.permutation(len(boxes))
docs.append([boxes[int(p)] for p in perm])
return docs
def naive_y_sort_reading_order(boxes: list[LayoutBox]) -> list[LayoutBox]:
"""Naive PDF text extractor sorting solely by (y0, x0) — interleaves multi-column resumes."""
return sorted(boxes, key=lambda b: (b.y0, b.x0))
def _find_gutter_split(
boxes: list[LayoutBox],
axis: str,
min_gap: float = 35.0,
) -> float | None:
"""Find largest empty projection gap along axis ('x' or 'y') separating disjoint intervals."""
if len(boxes) <= 1:
return None
intervals = sorted((b.x0, b.x1) if axis == "x" else (b.y0, b.y1) for b in boxes)
merged_end = intervals[0][1]
best_gap = 0.0
best_cut: float | None = None
for start, end in intervals[1:]:
gap = start - merged_end
if gap >= min_gap and gap > best_gap:
best_gap = gap
best_cut = 0.5 * (merged_end + start)
if end > merged_end:
merged_end = end
return best_cut
def xy_cut_reading_order(boxes: list[LayoutBox], min_x_gap: float = 35.0) -> list[LayoutBox]:
"""Recursive XY-Cut layout algorithm separating vertical columns before top-down reading."""
if len(boxes) <= 1:
return list(boxes)
# First attempt vertical gutter split (multi-column detection).
x_cut = _find_gutter_split(boxes, axis="x", min_gap=min_x_gap)
if x_cut is not None:
left = [b for b in boxes if 0.5 * (b.x0 + b.x1) < x_cut]
right = [b for b in boxes if 0.5 * (b.x0 + b.x1) >= x_cut]
if left and right:
return xy_cut_reading_order(left, min_x_gap=min_x_gap) + xy_cut_reading_order(
right, min_x_gap=min_x_gap
)
# Inside a single column, sort strictly top-to-bottom then left-to-right.
return sorted(boxes, key=lambda b: (b.y0, b.x0))
def generate_domain_classification_corpus(
n_per_class: int = 60,
seed: int = 42,
) -> dict[str, object]:
"""Generate 3-class technical document routing corpus with ground-truth rationale keywords."""
rng = np.random.default_rng(seed)
class_names = ["NLP_LLM_AI", "Data_Engineering", "Quant_Risk_Finance"]
class_keywords: dict[int, list[str]] = {
0: ["bpe", "bilstm", "crf", "viterbi", "transformer", "tokenization", "ner", "pytorch"],
1: ["kafka", "spark", "iceberg", "trino", "duckdb", "airflow", "warehouse", "pipeline"],
2: ["var", "basel", "sharpe", "hedging", "credit", "volatility", "derivatives", "liquidity"],
}
neutral_fillers = [
"candidate",
"built",
"scalable",
"production",
"system",
"team",
"deployed",
"cloud",
"monitoring",
"report",
"metrics",
"quarterly",
"latency",
"platform",
"review",
"service",
]
texts: list[list[str]] = []
labels: list[int] = []
rationale_sets: list[set[str]] = []
for cls_id in range(3):
kw_pool = class_keywords[cls_id]
for _ in range(n_per_class):
chosen_kw = [str(kw_pool[int(i)]) for i in rng.choice(len(kw_pool), size=3, replace=False)]
chosen_fill = [
str(neutral_fillers[int(i)]) for i in rng.choice(len(neutral_fillers), size=7, replace=False)
]
toks = chosen_fill[:3] + [chosen_kw[0]] + chosen_fill[3:5] + chosen_kw[1:] + chosen_fill[5:]
texts.append(toks)
labels.append(cls_id)
rationale_sets.append(set(chosen_kw))
perm = rng.permutation(len(texts))
texts = [texts[int(i)] for i in perm]
labels = [labels[int(i)] for i in perm]
rationale_sets = [rationale_sets[int(i)] for i in perm]
split = int(0.75 * len(texts))
return {
"class_names": class_names,
"train_tokens": texts[:split],
"train_labels": labels[:split],
"train_rationales": rationale_sets[:split],
"test_tokens": texts[split:],
"test_labels": labels[split:],
"test_rationales": rationale_sets[split:],
}
"""Tier 2 PyTorch Sequence Models: BPTT Pathology, Clipping, LSTM/GRU/CNN-LSTM & Token IG XAI."""
from __future__ import annotations
import math
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, Field
class LongRangeConfig(BaseModel):
"""Strict configuration for the BPTT long-range dependency benchmark."""
model_config = ConfigDict(extra="forbid")
seq_len: int = Field(default=36, ge=12, le=64)
vocab_size: int = Field(default=16, ge=8, le=64)
n_train: int = Field(default=360, ge=60, le=2000)
n_test: int = Field(default=120, ge=20, le=1000)
embed_dim: int = Field(default=16, ge=8, le=64)
hidden_dim: int = Field(default=32, ge=8, le=128)
epochs: int = Field(default=26, ge=5, le=100)
batch_size: int = Field(default=32, ge=8, le=128)
learning_rate: float = Field(default=6e-3, gt=0.0, le=0.2)
max_grad_norm: float = Field(default=1.0, gt=0.0, le=20.0)
seed: int = 42
def generate_long_range_dependency_data(
seq_len: int = 36,
vocab_size: int = 16,
n_samples: int = 480,
seed: int = 42,
) -> tuple[np.ndarray, np.ndarray]:
"""Generate T-step sequences where label depends strictly on early cue x_0 across T-1 distractors."""
rng = np.random.default_rng(seed)
x = rng.integers(4, vocab_size, size=(n_samples, seq_len), dtype=np.int64)
# Single signal cue at t=0 from disjoint cue tokens {2, 3}; t=1..T-1 are pure random distractors.
cues_start = rng.integers(2, 4, size=n_samples, dtype=np.int64)
x[:, 0] = cues_start
y = (cues_start - 2).astype(np.int64)
return x, y
class VanillaRNNClassifier(nn.Module):
"""Unrolled tanh Vanilla RNN classifier with controllable recurrent spectral radius."""
def __init__(
self,
vocab_size: int,
embed_dim: int = 16,
hidden_dim: int = 32,
num_classes: int = 2,
spectral_radius: float = 0.78,
) -> None:
super().__init__()
self.hidden_dim = hidden_dim
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.rnn = nn.RNN(embed_dim, hidden_dim, batch_first=True, nonlinearity="tanh")
self.head = nn.Linear(hidden_dim, num_classes)
self._init_spectral_radius(spectral_radius)
def _init_spectral_radius(self, target_rho: float) -> None:
with torch.no_grad():
w_hh = self.rnn.weight_hh_l0
if isinstance(w_hh, torch.Tensor):
nn.init.orthogonal_(w_hh)
w_hh.mul_(target_rho)
def forward(self, x: torch.Tensor) -> torch.Tensor:
emb = self.embedding(x)
out, _ = self.rnn(emb)
return self.head(out[:, -1, :])
class LSTMClassifier(nn.Module):
"""LSTM classifier with positive forget-gate bias initialization for gradient highway preservation."""
def __init__(
self,
vocab_size: int,
embed_dim: int = 16,
hidden_dim: int = 32,
num_classes: int = 2,
forget_bias: float = 1.5,
) -> None:
super().__init__()
self.hidden_dim = hidden_dim
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.lstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True)
self.head = nn.Linear(hidden_dim, num_classes)
# PyTorch LSTM gate bias layout is [input, forget, cell, output].
with torch.no_grad():
b_hh = self.lstm.bias_hh_l0
b_ih = self.lstm.bias_ih_l0
if isinstance(b_hh, torch.Tensor) and isinstance(b_ih, torch.Tensor):
b_hh[hidden_dim : 2 * hidden_dim].fill_(forget_bias)
b_ih[hidden_dim : 2 * hidden_dim].fill_(0.0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
emb = self.embedding(x)
out, _ = self.lstm(emb)
return self.head(out[:, -1, :])
class GRUClassifier(nn.Module):
"""GRU classifier with positive update-gate bias (PyTorch z_t * h_{t-1} highway, ~25% fewer weights)."""
def __init__(
self,
vocab_size: int,
embed_dim: int = 16,
hidden_dim: int = 32,
num_classes: int = 2,
update_bias: float = 1.5,
) -> None:
super().__init__()
self.hidden_dim = hidden_dim
self.embedding = nn.Embedding(vocab_size, embed_dim)
self.gru = nn.GRU(embed_dim, hidden_dim, batch_first=True)
self.head = nn.Linear(hidden_dim, num_classes)
# PyTorch nn.GRU computes h_t = (1 - z_t) * n_t + z_t * h_{t-1}; positive z bias preserves h_{t-1}.
with torch.no_grad():
b_hh = self.gru.bias_hh_l0
b_ih = self.gru.bias_ih_l0
if isinstance(b_hh, torch.Tensor) and isinstance(b_ih, torch.Tensor):
b_hh[hidden_dim : 2 * hidden_dim].fill_(update_bias)
b_ih[hidden_dim : 2 * hidden_dim].fill_(0.0)
def forward(self, x: torch.Tensor) -> torch.Tensor:
emb = self.embedding(x)
out, _ = self.gru(emb)
return self.head(out[:, -1, :])
class BiLSTMTextClassifier(nn.Module):
"""Bidirectional LSTM text classifier supporting direct embedding input for Token IG XAI."""
def __init__(
self,
vocab_size: int,
embed_dim: int = 32,
hidden_dim: int = 32,
num_classes: int = 3,
pad_idx: int = 0,
) -> None:
super().__init__()
self.pad_idx = pad_idx
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_idx)
self.bilstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
self.head = nn.Linear(hidden_dim * 2, num_classes)
def forward_from_embeddings(
self,
emb: torch.Tensor,
mask: torch.Tensor | None = None,
) -> torch.Tensor:
out, _ = self.bilstm(emb)
if mask is not None:
m = mask.unsqueeze(-1).float()
pooled = (out * m).sum(dim=1) / torch.clamp(m.sum(dim=1), min=1.0)
else:
pooled = out.mean(dim=1)
return self.head(pooled)
def forward(self, x: torch.Tensor) -> torch.Tensor:
mask = x.ne(self.pad_idx)
emb = self.embedding(x)
return self.forward_from_embeddings(emb, mask=mask)
class CNNLSTMClassifier(nn.Module):
"""Hybrid CNN-LSTM architecture: Conv1d local n-gram extractor followed by LSTM sequence encoder."""
def __init__(
self,
vocab_size: int,
embed_dim: int = 32,
conv_channels: int = 32,
hidden_dim: int = 32,
num_classes: int = 3,
pad_idx: int = 0,
) -> None:
super().__init__()
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_idx)
self.conv = nn.Conv1d(embed_dim, conv_channels, kernel_size=3, padding=1)
self.lstm = nn.LSTM(conv_channels, hidden_dim, batch_first=True)
self.head = nn.Linear(hidden_dim, num_classes)
def forward(self, x: torch.Tensor) -> torch.Tensor:
emb = self.embedding(x).transpose(1, 2) # (B, E, T)
feat = F.relu(self.conv(emb)).transpose(1, 2) # (B, T, C)
out, _ = self.lstm(feat)
return self.head(out.mean(dim=1))
def measure_bptt_gradient_flow(
seq_len: int = 32,
hidden_dim: int = 32,
vanishing_rho: float = 0.72,
exploding_rho: float = 1.45,
lstm_forget_bias: float = 2.0,
seed: int = 42,
) -> dict[str, Any]:
"""Measure exact per-timestep BPTT gradient norms ||dL/dh_t||_2 for Vanilla RNN vs LSTM."""
torch.manual_seed(seed)
batch_size = 8
input_dim = 16
x = torch.randn(batch_size, seq_len, input_dim) * 0.25
target = torch.zeros(batch_size, dtype=torch.long)
def _run_rnn(rho: float) -> list[float]:
torch.manual_seed(seed)
cell = nn.RNNCell(input_dim, hidden_dim, nonlinearity="tanh")
head = nn.Linear(hidden_dim, 2)
with torch.no_grad():
nn.init.orthogonal_(cell.weight_hh)
cell.weight_hh.mul_(rho)
cell.bias_hh.zero_()
cell.bias_ih.zero_()
h = torch.zeros(batch_size, hidden_dim)
states: list[torch.Tensor] = []
for t in range(seq_len):
h = cell(x[:, t, :], h)
h.retain_grad()
states.append(h)
loss = F.cross_entropy(head(states[-1]), target)
loss.backward()
return [float(st.grad.norm().item()) if st.grad is not None else 0.0 for st in states]
def _run_lstm(f_bias: float) -> tuple[list[float], list[float]]:
torch.manual_seed(seed)
cell = nn.LSTMCell(input_dim, hidden_dim)
head = nn.Linear(hidden_dim, 2)
with torch.no_grad():
cell.bias_hh[hidden_dim : 2 * hidden_dim].fill_(f_bias)
cell.bias_ih[hidden_dim : 2 * hidden_dim].fill_(0.0)
h = torch.zeros(batch_size, hidden_dim)
c = torch.zeros(batch_size, hidden_dim)
h_states: list[torch.Tensor] = []
c_states: list[torch.Tensor] = []
for t in range(seq_len):
h, c = cell(x[:, t, :], (h, c))
h.retain_grad()
c.retain_grad()
h_states.append(h)
c_states.append(c)
loss = F.cross_entropy(head(h_states[-1]), target)
loss.backward()
h_norms = [float(st.grad.norm().item()) if st.grad is not None else 0.0 for st in h_states]
c_norms = [float(st.grad.norm().item()) if st.grad is not None else 0.0 for st in c_states]
return h_norms, c_norms
rnn_vanish = _run_rnn(vanishing_rho)
rnn_explode = _run_rnn(exploding_rho)
lstm_h, lstm_c = _run_lstm(lstm_forget_bias)
eps = 1e-12
return {
"seq_len": seq_len,
"vanishing_rho": vanishing_rho,
"exploding_rho": exploding_rho,
"lstm_forget_bias": lstm_forget_bias,
"vanilla_rnn_vanishing_norms": rnn_vanish,
"vanilla_rnn_vanishing_ratio_t1_to_tT": float(rnn_vanish[0] / max(rnn_vanish[-1], eps)),
"vanilla_rnn_exploding_norms": rnn_explode,
"vanilla_rnn_exploding_ratio_t1_to_tT": float(rnn_explode[0] / max(rnn_explode[-1], eps)),
"lstm_h_norms": lstm_h,
"lstm_c_norms": lstm_c,
"lstm_h_ratio_t1_to_tT": float(lstm_h[0] / max(lstm_h[-1], eps)),
"lstm_c_ratio_t1_to_tT": float(lstm_c[0] / max(lstm_c[-1], eps)),
}
def demonstrate_gradient_clipping(
seq_len: int = 32,
hidden_dim: int = 32,
exploding_rho: float = 1.60,
max_norm: float = 1.0,
seed: int = 42,
) -> dict[str, float]:
"""Verify global L2 gradient clipping caps exploding RNN gradient norm while preserving direction."""
torch.manual_seed(seed)
x = torch.randn(8, seq_len, 16) * 0.15
target = torch.zeros(8, dtype=torch.long)
cell = nn.RNNCell(16, hidden_dim, nonlinearity="tanh")
head = nn.Linear(hidden_dim, 2)
with torch.no_grad():
nn.init.orthogonal_(cell.weight_hh)
cell.weight_hh.mul_(exploding_rho)
cell.bias_hh.zero_()
cell.bias_ih.zero_()
h = torch.zeros(8, hidden_dim)
for t in range(seq_len):
h = cell(x[:, t, :], h)
loss = F.cross_entropy(head(h), target)
loss.backward()
params = list(cell.parameters()) + list(head.parameters())
flat_before = torch.cat([p.grad.detach().reshape(-1) for p in params if p.grad is not None])
norm_before = float(flat_before.norm(2).item())
returned_norm = float(torch.nn.utils.clip_grad_norm_(params, max_norm=max_norm).item())
flat_after = torch.cat([p.grad.detach().reshape(-1) for p in params if p.grad is not None])
norm_after = float(flat_after.norm(2).item())
cos_dir = float(
F.cosine_similarity(flat_before.unsqueeze(0), flat_after.unsqueeze(0)).item()
)
return {
"max_norm": float(max_norm),
"raw_grad_norm": norm_before,
"returned_preclip_norm": returned_norm,
"clipped_grad_norm": norm_after,
"direction_cosine_similarity": cos_dir,
}
def _train_one_seq_model(
model: nn.Module,
x_train: np.ndarray,
y_train: np.ndarray,
x_test: np.ndarray,
y_test: np.ndarray,
cfg: LongRangeConfig,
) -> dict[str, float]:
torch.manual_seed(cfg.seed)
opt = torch.optim.Adam(model.parameters(), lr=cfg.learning_rate)
xt = torch.as_tensor(x_train, dtype=torch.long)
yt = torch.as_tensor(y_train, dtype=torch.long)
xv = torch.as_tensor(x_test, dtype=torch.long)
yv = torch.as_tensor(y_test, dtype=torch.long)
n = xt.shape[0]
final_loss = 0.0
model.train()
for _ in range(cfg.epochs):
perm = torch.randperm(n)
epoch_loss = 0.0
batches = 0
for start in range(0, n, cfg.batch_size):
idx = perm[start : start + cfg.batch_size]
opt.zero_grad()
logits = model(xt[idx])
loss = F.cross_entropy(logits, yt[idx])
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=cfg.max_grad_norm)
opt.step()
epoch_loss += float(loss.item())
batches += 1
final_loss = epoch_loss / float(max(1, batches))
model.eval()
with torch.no_grad():
train_acc = float((model(xt).argmax(dim=1) == yt).float().mean().item())
test_acc = float((model(xv).argmax(dim=1) == yv).float().mean().item())
n_params = sum(p.numel() for p in model.parameters())
return {
"train_accuracy": train_acc,
"test_accuracy": test_acc,
"final_train_loss": final_loss,
"num_params": float(n_params),
}
def train_long_range_benchmark(config: LongRangeConfig | None = None) -> dict[str, Any]:
"""Train VanillaRNN, LSTM, and GRU on controlled T=32 long-range dependency recall."""
cfg = config or LongRangeConfig()
x_all, y_all = generate_long_range_dependency_data(
seq_len=cfg.seq_len,
vocab_size=cfg.vocab_size,
n_samples=cfg.n_train + cfg.n_test,
seed=cfg.seed,
)
x_train, y_train = x_all[: cfg.n_train], y_all[: cfg.n_train]
x_test, y_test = x_all[cfg.n_train :], y_all[cfg.n_train :]
torch.manual_seed(cfg.seed)
vanilla_rnn = VanillaRNNClassifier(
vocab_size=cfg.vocab_size,
embed_dim=cfg.embed_dim,
hidden_dim=cfg.hidden_dim,
num_classes=2,
spectral_radius=0.45,
)
rnn_metrics = _train_one_seq_model(vanilla_rnn, x_train, y_train, x_test, y_test, cfg)
torch.manual_seed(cfg.seed)
lstm = LSTMClassifier(
vocab_size=cfg.vocab_size,
embed_dim=cfg.embed_dim,
hidden_dim=cfg.hidden_dim,
num_classes=2,
forget_bias=1.5,
)
lstm_metrics = _train_one_seq_model(lstm, x_train, y_train, x_test, y_test, cfg)
torch.manual_seed(cfg.seed)
gru = GRUClassifier(
vocab_size=cfg.vocab_size,
embed_dim=cfg.embed_dim,
hidden_dim=cfg.hidden_dim,
num_classes=2,
)
gru_metrics = _train_one_seq_model(gru, x_train, y_train, x_test, y_test, cfg)
return {
"seq_len": cfg.seq_len,
"vanilla_rnn": rnn_metrics,
"lstm": lstm_metrics,
"gru": gru_metrics,
}
def _encode_padded_docs(
docs: list[list[str]],
vocab: dict[str, int],
) -> torch.Tensor:
max_len = max(len(d) for d in docs)
arr = np.zeros((len(docs), max_len), dtype=np.int64)
for i, doc in enumerate(docs):
for j, tok in enumerate(doc):
arr[i, j] = vocab.get(tok, 1)
return torch.as_tensor(arr, dtype=torch.long)
def train_domain_text_classifier(
corpus: dict[str, Any],
epochs: int = 12,
seed: int = 42,
) -> dict[str, Any]:
"""Train BiLSTMTextClassifier and CNNLSTMClassifier on the 3-class domain routing corpus."""
train_tokens: list[list[str]] = corpus["train_tokens"]
train_labels: list[int] = corpus["train_labels"]
test_tokens: list[list[str]] = corpus["test_tokens"]
test_labels: list[int] = corpus["test_labels"]
vocab: dict[str, int] = {"<PAD>": 0, "<UNK>": 1}
for doc in train_tokens:
for tok in sorted(set(doc)):
if tok not in vocab:
vocab[tok] = len(vocab)
x_tr = _encode_padded_docs(train_tokens, vocab)
y_tr = torch.as_tensor(train_labels, dtype=torch.long)
x_te = _encode_padded_docs(test_tokens, vocab)
y_te = torch.as_tensor(test_labels, dtype=torch.long)
def _fit(model: nn.Module) -> float:
torch.manual_seed(seed)
opt = torch.optim.AdamW(model.parameters(), lr=5e-3, weight_decay=2e-2)
model.train()
for _ in range(epochs):
perm = torch.randperm(x_tr.shape[0])
for start in range(0, x_tr.shape[0], 24):
idx = perm[start : start + 24]
opt.zero_grad()
loss = F.cross_entropy(model(x_tr[idx]), y_tr[idx])
loss.backward()
opt.step()
model.eval()
with torch.no_grad():
return float((model(x_te).argmax(dim=1) == y_te).float().mean().item())
torch.manual_seed(seed)
bilstm = BiLSTMTextClassifier(vocab_size=len(vocab), embed_dim=32, hidden_dim=24, num_classes=3)
bilstm_acc = _fit(bilstm)
torch.manual_seed(seed)
cnn_lstm = CNNLSTMClassifier(
vocab_size=len(vocab), embed_dim=32, conv_channels=24, hidden_dim=24, num_classes=3
)
cnn_lstm_acc = _fit(cnn_lstm)
return {
"vocab": vocab,
"bilstm_model": bilstm,
"cnn_lstm_model": cnn_lstm,
"bilstm_test_accuracy": bilstm_acc,
"cnn_lstm_test_accuracy": cnn_lstm_acc,
"x_test": x_te,
"y_test": y_te,
}
def compute_token_integrated_gradients(
model: BiLSTMTextClassifier,
token_ids: torch.Tensor,
target_class: int | None = None,
steps: int = 64,
) -> dict[str, Any]:
"""Compute vectorized Token Integrated Gradients via Composite Gauss-Legendre quadrature."""
model.eval()
if token_ids.dim() == 1:
x = token_ids.unsqueeze(0)
else:
x = token_ids[:1]
mask = x.ne(model.pad_idx)
with torch.no_grad():
emb_input = model.embedding(x)
emb_baseline = torch.zeros_like(emb_input)
logits_in = model.forward_from_embeddings(emb_input, mask=mask)
probs_in = F.softmax(logits_in, dim=-1)
pred_cls = int(logits_in.argmax(dim=-1).item()) if target_class is None else int(target_class)
p_input = float(probs_in[0, pred_cls].item())
f_input = float(logits_in[0, pred_cls].item())
logits_base = model.forward_from_embeddings(emb_baseline, mask=mask)
f_baseline = float(logits_base[0, pred_cls].item())
diff = emb_input - emb_baseline
# 8-panel composite Gauss-Legendre on [0, 1], batched in one vectorized LSTM pass.
n_panels = 8 if steps >= 32 else 4
nodes_per_panel = max(4, steps // n_panels)
base_nodes, base_weights = np.polynomial.legendre.leggauss(nodes_per_panel)
panel_w = 1.0 / float(n_panels)
alphas_list: list[float] = []
weights_list: list[float] = []
for p in range(n_panels):
lo = p * panel_w
hi = (p + 1) * panel_w
mid = 0.5 * (lo + hi)
half = 0.5 * (hi - lo)
for nd, wt in zip(base_nodes, base_weights, strict=True):
alphas_list.append(float(mid + half * nd))
weights_list.append(float(half * wt))
n_pts = len(alphas_list)
alphas_t = torch.tensor(alphas_list, dtype=emb_input.dtype, device=emb_input.device).view(n_pts, 1, 1)
weights_t = torch.tensor(weights_list, dtype=emb_input.dtype, device=emb_input.device).view(n_pts, 1, 1)
interp_batch = (emb_baseline + alphas_t * diff).detach().requires_grad_(True)
mask_batch = mask.expand(n_pts, -1)
logits_batch = model.forward_from_embeddings(interp_batch, mask=mask_batch)
target_sum = logits_batch[:, pred_cls].sum()
grads_batch = torch.autograd.grad(target_sum, interp_batch)[0]
weighted_grad = (grads_batch * weights_t).sum(dim=0, keepdim=True) # (1, T, E)
ig_embed = diff * weighted_grad
token_scores = ig_embed.sum(dim=-1).squeeze(0).detach().cpu().numpy().astype(np.float64)
total_ig = float(token_scores.sum())
delta_f = f_input - f_baseline
completeness_error = abs(total_ig - delta_f) / max(abs(delta_f), 1.0)
return {
"target_class": pred_cls,
"p_input": p_input,
"f_input": f_input,
"f_baseline": f_baseline,
"delta_f": delta_f,
"sum_ig": total_ig,
"completeness_error": completeness_error,
"token_attributions": token_scores,
}
def _eval_masked_prob(
model: BiLSTMTextClassifier,
token_ids: torch.Tensor,
seq_len: int,
cls_id: int,
keep_positions: set[int],
) -> float:
masked = token_ids.clone()
for pos in range(seq_len):
if pos not in keep_positions:
masked[pos] = model.pad_idx
with torch.no_grad():
emb = model.embedding(masked.unsqueeze(0))
for pos in range(seq_len):
if pos not in keep_positions:
emb[0, pos, :].zero_()
logits = model.forward_from_embeddings(
emb, mask=torch.ones((1, seq_len), dtype=torch.bool)
)
return float(F.softmax(logits, dim=-1)[0, cls_id].item())
def evaluate_text_xai_faithfulness(
model: BiLSTMTextClassifier,
test_tokens: list[list[str]],
test_rationales: list[set[str]],
vocab: dict[str, int],
n_eval: int = 20,
top_k: int = 3,
ig_steps: int = 64,
seed: int = 42,
) -> dict[str, float]:
"""Audit Token IG via ERASER Comprehensiveness, Sufficiency, Completeness & Rationale Hit-Rate."""
rng = np.random.default_rng(seed)
n_samples = min(n_eval, len(test_tokens))
ig_comps: list[float] = []
rand_comps: list[float] = []
ig_suffs: list[float] = []
rand_suffs: list[float] = []
comp_errs: list[float] = []
hit_rates: list[float] = []
model.eval()
for idx in range(n_samples):
doc = test_tokens[idx]
rat = test_rationales[idx]
ids = torch.tensor([vocab.get(tok, 1) for tok in doc], dtype=torch.long)
ig_res = compute_token_integrated_gradients(model, ids, steps=ig_steps)
scores = ig_res["token_attributions"]
cls_id = int(ig_res["target_class"])
p_full = float(ig_res["p_input"])
comp_errs.append(float(ig_res["completeness_error"]))
k = min(top_k, len(doc))
top_indices = np.argsort(-scores)[:k]
rand_indices = rng.choice(len(doc), size=k, replace=False)
hit = sum(1 for pos in top_indices if doc[int(pos)] in rat) / float(max(1, k))
hit_rates.append(hit)
all_pos = set(range(len(doc)))
ig_set = {int(p) for p in top_indices}
rand_set = {int(p) for p in rand_indices}
p_ig_removed = _eval_masked_prob(model, ids, len(doc), cls_id, all_pos - ig_set)
p_rand_removed = _eval_masked_prob(model, ids, len(doc), cls_id, all_pos - rand_set)
p_ig_only = _eval_masked_prob(model, ids, len(doc), cls_id, ig_set)
p_rand_only = _eval_masked_prob(model, ids, len(doc), cls_id, rand_set)
ig_comps.append(p_full - p_ig_removed)
rand_comps.append(p_full - p_rand_removed)
ig_suffs.append(p_full - p_ig_only)
rand_suffs.append(p_full - p_rand_only)
return {
"n_evaluated": float(n_samples),
"ig_mean_completeness_error": float(np.mean(comp_errs)),
"ig_max_completeness_error": float(np.max(comp_errs)),
"ig_comprehensiveness": float(np.mean(ig_comps)),
"random_comprehensiveness": float(np.mean(rand_comps)),
"ig_sufficiency": float(np.mean(ig_suffs)),
"random_sufficiency": float(np.mean(rand_suffs)),
"rationale_top3_hit_rate": float(np.mean(hit_rates)),
}
def compute_bptt_theoretical_curve(
seq_len: int,
spectral_radius: float,
forget_gate: float = 0.94,
) -> dict[str, list[float]]:
"""Closed-form upper-bound illustration curves for RNN vs LSTM gradient flow."""
steps = list(range(1, seq_len + 1))
rnn_curve = [math.pow(spectral_radius, seq_len - t) for t in steps]
lstm_curve = [math.pow(forget_gate, seq_len - t) for t in steps]
return {"rnn": rnn_curve, "lstm": lstm_curve}
"""Tier 2 Resume Document AI: Exact Linear-Chain CRF, BiLSTM-CRF vs Softmax, Pydantic v2 & Safetensors."""
from __future__ import annotations
import itertools
from typing import Any
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from pydantic import BaseModel, ConfigDict, Field
from safetensors.torch import load as sf_load
from safetensors.torch import save as sf_save
from nlp_docai_lab.resume_dataset import (
BIO_TAGS,
ID_TO_TAG,
TAG_TO_ID,
LayoutBox,
ResumeNERTokenExample,
build_token_vocab,
naive_y_sort_reading_order,
xy_cut_reading_order,
)
_IMPOSSIBLE_PENALTY = -1e4
def is_legal_bio_transition(prev_tag: str | None, next_tag: str) -> bool:
"""Check strict BIO structural transition invariant (forbids START/O -> I-* and cross-type I-*)."""
if prev_tag is None:
return not next_tag.startswith("I-")
if next_tag == "O" or next_tag.startswith("B-"):
return True
if next_tag.startswith("I-"):
ent_next = next_tag[2:]
if prev_tag.startswith("B-") or prev_tag.startswith("I-"):
return prev_tag[2:] == ent_next
return False
return True
def build_bio_constraint_masks(
tags: tuple[str, ...] = BIO_TAGS,
) -> tuple[torch.Tensor, torch.Tensor]:
"""Return boolean legal masks (start_legal [K], trans_legal [K, K]) for BIO grammar."""
k = len(tags)
start_legal = torch.tensor([is_legal_bio_transition(None, t) for t in tags], dtype=torch.bool)
trans_legal = torch.zeros((k, k), dtype=torch.bool)
for i, prev_t in enumerate(tags):
for j, next_t in enumerate(tags):
trans_legal[i, j] = is_legal_bio_transition(prev_t, next_t)
return start_legal, trans_legal
class LinearChainCRF(nn.Module):
"""Exact Linear-Chain Conditional Random Field with log-sum-exp Forward & Viterbi decoding."""
def __init__(
self,
num_tags: int = len(BIO_TAGS),
enforce_bio_constraints: bool = True,
tags: tuple[str, ...] = BIO_TAGS,
) -> None:
super().__init__()
self.num_tags = num_tags
self.enforce_bio_constraints = enforce_bio_constraints
self.start_transitions = nn.Parameter(torch.empty(num_tags))
self.end_transitions = nn.Parameter(torch.empty(num_tags))
self.transitions = nn.Parameter(torch.empty(num_tags, num_tags))
nn.init.uniform_(self.start_transitions, -0.1, 0.1)
nn.init.uniform_(self.end_transitions, -0.1, 0.1)
nn.init.uniform_(self.transitions, -0.1, 0.1)
start_legal, trans_legal = build_bio_constraint_masks(tags)
self.register_buffer("start_legal_mask", start_legal)
self.register_buffer("trans_legal_mask", trans_legal)
def effective_parameters(self) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
"""Return (start_trans, transitions, end_trans) with structural BIO masks applied if enabled."""
if not self.enforce_bio_constraints:
return self.start_transitions, self.transitions, self.end_transitions
start_mask = torch.as_tensor(self.start_legal_mask, dtype=torch.bool, device=self.transitions.device)
trans_mask = torch.as_tensor(self.trans_legal_mask, dtype=torch.bool, device=self.transitions.device)
start_t = torch.where(
start_mask,
self.start_transitions,
torch.full_like(self.start_transitions, _IMPOSSIBLE_PENALTY),
)
trans_t = torch.where(
trans_mask,
self.transitions,
torch.full_like(self.transitions, _IMPOSSIBLE_PENALTY),
)
return start_t, trans_t, self.end_transitions
def score_sequence(
self,
emissions: torch.Tensor,
tags: torch.Tensor,
mask: torch.Tensor,
) -> torch.Tensor:
"""Compute exact path score s(x, y) for each sequence in batch: shape (B,)."""
batch_size, seq_len, _ = emissions.shape
start_t, trans_t, end_t = self.effective_parameters()
batch_idx = torch.arange(batch_size, device=emissions.device)
score = start_t[tags[:, 0]] + emissions[batch_idx, 0, tags[:, 0]]
for t in range(1, seq_len):
m = mask[:, t].float()
emit_t = emissions[batch_idx, t, tags[:, t]]
step_trans = trans_t[tags[:, t - 1], tags[:, t]]
score = score + (emit_t + step_trans) * m
last_idx = mask.long().sum(dim=1) - 1
last_tags = tags[batch_idx, last_idx]
score = score + end_t[last_tags]
return score
def forward_log_partition(
self,
emissions: torch.Tensor,
mask: torch.Tensor,
) -> torch.Tensor:
"""Exact log Z(x) = log sum_y exp(s(x, y)) via vectorized log-sum-exp Forward DP in O(T K^2)."""
_, seq_len, _ = emissions.shape
start_t, trans_t, end_t = self.effective_parameters()
alpha = start_t.unsqueeze(0) + emissions[:, 0, :] # (B, K)
for t in range(1, seq_len):
# alpha_prev: (B, K, 1), trans_t: (1, K, K), emit_t: (B, 1, K)
scores = alpha.unsqueeze(2) + trans_t.unsqueeze(0) + emissions[:, t, :].unsqueeze(1)
next_alpha = torch.logsumexp(scores, dim=1) # (B, K)
m = mask[:, t].unsqueeze(1)
alpha = torch.where(m, next_alpha, alpha)
alpha = alpha + end_t.unsqueeze(0)
return torch.logsumexp(alpha, dim=1)
def bruteforce_log_partition(self, emissions_single: torch.Tensor) -> float:
"""Exact brute-force log Z(x) over all K^T paths (for unit-testing short sequences T <= 5)."""
seq_len, num_tags = emissions_single.shape
if num_tags**seq_len > 200_000:
raise ValueError("Sequence too long for brute-force enumeration; use T <= 5")
start_t, trans_t, end_t = self.effective_parameters()
e_np = emissions_single.detach().cpu().numpy().astype(np.float64)
st_np = start_t.detach().cpu().numpy().astype(np.float64)
tr_np = trans_t.detach().cpu().numpy().astype(np.float64)
en_np = end_t.detach().cpu().numpy().astype(np.float64)
all_scores: list[float] = []
for path in itertools.product(range(num_tags), repeat=seq_len):
sc = float(st_np[path[0]] + e_np[0, path[0]])
for t in range(1, seq_len):
sc += float(tr_np[path[t - 1], path[t]] + e_np[t, path[t]])
sc += float(en_np[path[-1]])
all_scores.append(sc)
arr = np.asarray(all_scores, dtype=np.float64)
max_sc = float(arr.max())
return max_sc + float(np.log(np.sum(np.exp(arr - max_sc))))
def neg_log_likelihood(
self,
emissions: torch.Tensor,
tags: torch.Tensor,
mask: torch.Tensor,
) -> torch.Tensor:
"""Exact mean negative log-likelihood: mean(log Z(x) - s(x, y))."""
log_z = self.forward_log_partition(emissions, mask)
gold_score = self.score_sequence(emissions, tags, mask)
return (log_z - gold_score).mean()
def viterbi_decode(
self,
emissions: torch.Tensor,
mask: torch.Tensor,
) -> tuple[list[list[int]], list[float]]:
"""Exact Viterbi dynamic programming returning globally optimal paths and path scores."""
batch_size, seq_len, _ = emissions.shape
start_t, trans_t, end_t = self.effective_parameters()
viterbi = start_t.unsqueeze(0) + emissions[:, 0, :] # (B, K)
backpointers: list[torch.Tensor] = []
for t in range(1, seq_len):
scores = viterbi.unsqueeze(2) + trans_t.unsqueeze(0) # (B, K_prev, K_next)
best_prev_scores, best_prev_tags = scores.max(dim=1) # (B, K_next)
next_viterbi = best_prev_scores + emissions[:, t, :]
m = mask[:, t].unsqueeze(1)
viterbi = torch.where(m, next_viterbi, viterbi)
backpointers.append(best_prev_tags)
viterbi = viterbi + end_t.unsqueeze(0)
lengths = mask.long().sum(dim=1).tolist()
best_paths: list[list[int]] = []
best_scores: list[float] = []
for b in range(batch_size):
seq_l = int(lengths[b])
last_score, last_tag = viterbi[b].max(dim=0)
best_scores.append(float(last_score.item()))
path = [int(last_tag.item())]
for t in range(seq_l - 2, -1, -1):
prev_tag = int(backpointers[t][b, path[-1]].item())
path.append(prev_tag)
path.reverse()
best_paths.append(path)
return best_paths, best_scores
class BiLSTMSoftmaxTagger(nn.Module):
"""Independent per-token BiLSTM + Softmax baseline (no sequence transition layer)."""
def __init__(
self,
vocab_size: int,
num_tags: int = len(BIO_TAGS),
embed_dim: int = 32,
hidden_dim: int = 32,
pad_idx: int = 0,
) -> None:
super().__init__()
self.pad_idx = pad_idx
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_idx)
self.bilstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
self.emission = nn.Linear(hidden_dim * 2, num_tags)
def forward(self, x: torch.Tensor) -> torch.Tensor:
out, _ = self.bilstm(self.embedding(x))
return self.emission(out)
def decode(self, x: torch.Tensor, mask: torch.Tensor) -> list[list[int]]:
with torch.no_grad():
logits = self.forward(x)
preds = logits.argmax(dim=-1)
lengths = mask.long().sum(dim=1).tolist()
return [preds[b, : int(lengths[b])].tolist() for b in range(x.shape[0])]
class BiLSTMCRF(nn.Module):
"""BiLSTM encoder coupled with an exact Linear-Chain CRF layer for Resume NER."""
def __init__(
self,
vocab_size: int,
num_tags: int = len(BIO_TAGS),
embed_dim: int = 32,
hidden_dim: int = 32,
pad_idx: int = 0,
enforce_bio_constraints: bool = True,
) -> None:
super().__init__()
self.pad_idx = pad_idx
self.embedding = nn.Embedding(vocab_size, embed_dim, padding_idx=pad_idx)
self.bilstm = nn.LSTM(embed_dim, hidden_dim, batch_first=True, bidirectional=True)
self.emission = nn.Linear(hidden_dim * 2, num_tags)
self.crf = LinearChainCRF(num_tags=num_tags, enforce_bio_constraints=enforce_bio_constraints)
def emissions(self, x: torch.Tensor) -> torch.Tensor:
out, _ = self.bilstm(self.embedding(x))
return self.emission(out)
def loss(self, x: torch.Tensor, tags: torch.Tensor, mask: torch.Tensor) -> torch.Tensor:
return self.crf.neg_log_likelihood(self.emissions(x), tags, mask)
def decode(self, x: torch.Tensor, mask: torch.Tensor) -> tuple[list[list[int]], list[float]]:
with torch.no_grad():
return self.crf.viterbi_decode(self.emissions(x), mask)
def extract_bio_spans(tag_seq: list[str]) -> set[tuple[int, int, str]]:
"""Extract exact (start_idx, end_idx_exclusive, entity_type) spans from a BIO tag sequence."""
spans: set[tuple[int, int, str]] = set()
active_type: str | None = None
active_start: int = -1
for idx, tag in enumerate(tag_seq):
if tag.startswith("B-"):
if active_type is not None:
spans.add((active_start, idx, active_type))
active_type = tag[2:]
active_start = idx
elif tag.startswith("I-"):
ent = tag[2:]
if active_type != ent:
# Close any previous span and mark malformed orphan I-* as standalone span so it penalizes F1.
if active_type is not None:
spans.add((active_start, idx, active_type))
active_type = ent
active_start = idx
else:
if active_type is not None:
spans.add((active_start, idx, active_type))
active_type = None
active_start = -1
if active_type is not None:
spans.add((active_start, len(tag_seq), active_type))
return spans
def compute_bio_span_f1(
gold_seqs: list[list[str]],
pred_seqs: list[list[str]],
) -> dict[str, Any]:
"""Compute seqeval-style strict span-level micro Precision, Recall, F1 and per-type F1."""
tp = 0
fp = 0
fn = 0
per_type: dict[str, dict[str, int]] = {}
for gold, pred in zip(gold_seqs, pred_seqs, strict=True):
g_spans = extract_bio_spans(gold)
p_spans = extract_bio_spans(pred)
tp += len(g_spans & p_spans)
fp += len(p_spans - g_spans)
fn += len(g_spans - p_spans)
for sp in g_spans | p_spans:
et = sp[2]
if et not in per_type:
per_type[et] = {"tp": 0, "fp": 0, "fn": 0}
if sp in g_spans and sp in p_spans:
per_type[et]["tp"] += 1
elif sp in p_spans:
per_type[et]["fp"] += 1
else:
per_type[et]["fn"] += 1
precision = float(tp) / float(max(1, tp + fp))
recall = float(tp) / float(max(1, tp + fn))
f1 = (2.0 * precision * recall) / max(precision + recall, 1e-12)
per_type_f1: dict[str, float] = {}
for et, c in sorted(per_type.items()):
p_e = float(c["tp"]) / float(max(1, c["tp"] + c["fp"]))
r_e = float(c["tp"]) / float(max(1, c["tp"] + c["fn"]))
per_type_f1[et] = (2.0 * p_e * r_e) / max(p_e + r_e, 1e-12)
return {
"precision": precision,
"recall": recall,
"span_f1": f1,
"tp": tp,
"fp": fp,
"fn": fn,
"per_entity_f1": per_type_f1,
}
def compute_illegal_bio_rate(pred_seqs: list[list[str]]) -> dict[str, float]:
"""Count illegal BIO transitions (START -> I-*, O -> I-*, cross-type I-*) across predicted sequences."""
total_transitions = 0
illegal_transitions = 0
for seq in pred_seqs:
prev: str | None = None
for tag in seq:
total_transitions += 1
if not is_legal_bio_transition(prev, tag):
illegal_transitions += 1
prev = tag
return {
"illegal_transitions": float(illegal_transitions),
"total_transitions": float(total_transitions),
"illegal_bio_rate": float(illegal_transitions) / float(max(1, total_transitions)),
}
class CRFTrainConfig(BaseModel):
"""Strict training configuration for Resume NER BiLSTM-Softmax vs BiLSTM-CRF."""
model_config = ConfigDict(extra="forbid")
embed_dim: int = Field(default=32, ge=8, le=128)
hidden_dim: int = Field(default=32, ge=8, le=128)
epochs_softmax: int = Field(default=18, ge=4, le=80)
epochs_crf: int = Field(default=22, ge=4, le=80)
batch_size: int = Field(default=24, ge=4, le=128)
learning_rate: float = Field(default=8e-3, gt=0.0, le=0.1)
seed: int = 42
def _batch_encode_ner(
examples: list[ResumeNERTokenExample],
vocab: dict[str, int],
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
max_len = max(len(ex.tokens) for ex in examples)
n = len(examples)
x = torch.zeros((n, max_len), dtype=torch.long)
y = torch.zeros((n, max_len), dtype=torch.long)
mask = torch.zeros((n, max_len), dtype=torch.bool)
for i, ex in enumerate(examples):
for j, (tok, tag) in enumerate(zip(ex.tokens, ex.tags, strict=True)):
x[i, j] = vocab.get(tok, 1)
y[i, j] = TAG_TO_ID[tag]
mask[i, j] = True
return x, y, mask
def train_resume_ner_models(
train_examples: list[ResumeNERTokenExample],
test_examples: list[ResumeNERTokenExample],
config: CRFTrainConfig | None = None,
) -> dict[str, Any]:
"""Train BiLSTMSoftmaxTagger and BiLSTMCRF on group-split Resume NER and compare Span F1 & legality."""
cfg = config or CRFTrainConfig()
vocab = build_token_vocab(train_examples, min_freq=1)
x_tr, y_tr, m_tr = _batch_encode_ner(train_examples, vocab)
x_te, _, m_te = _batch_encode_ner(test_examples, vocab)
gold_test_tags = [ex.tags for ex in test_examples]
def _apply_unk_dropout(batch_x: torch.Tensor, batch_mask: torch.Tensor, p: float = 0.12) -> torch.Tensor:
"""Word dropout to <UNK>=1 (Lample et al. 2016) so context learns unseen names & OCR noise."""
drop = (torch.rand_like(batch_x.float()) < p) & batch_mask
return torch.where(drop, torch.ones_like(batch_x), batch_x)
# 1. Independent BiLSTM-Softmax baseline
torch.manual_seed(cfg.seed)
softmax_model = BiLSTMSoftmaxTagger(
vocab_size=len(vocab),
num_tags=len(BIO_TAGS),
embed_dim=cfg.embed_dim,
hidden_dim=cfg.hidden_dim,
)
opt_s = torch.optim.Adam(softmax_model.parameters(), lr=cfg.learning_rate)
softmax_model.train()
for _ in range(cfg.epochs_softmax):
perm = torch.randperm(x_tr.shape[0])
for start in range(0, x_tr.shape[0], cfg.batch_size):
idx = perm[start : start + cfg.batch_size]
opt_s.zero_grad()
bx = _apply_unk_dropout(x_tr[idx], m_tr[idx], p=0.12)
logits = softmax_model(bx)
flat_mask = m_tr[idx].reshape(-1)
loss = F.cross_entropy(
logits.reshape(-1, len(BIO_TAGS))[flat_mask],
y_tr[idx].reshape(-1)[flat_mask],
)
loss.backward()
opt_s.step()
softmax_model.eval()
sm_pred_ids = softmax_model.decode(x_te, m_te)
sm_pred_tags = [[ID_TO_TAG[i] for i in seq] for seq in sm_pred_ids]
sm_f1 = compute_bio_span_f1(gold_test_tags, sm_pred_tags)
sm_illegal = compute_illegal_bio_rate(sm_pred_tags)
# Also test under realistic OCR token corruption (unknown/noisy tokens) where Softmax breaks BIO!
x_te_noisy = x_te.clone()
rng_noise = np.random.default_rng(cfg.seed + 99)
for b in range(x_te_noisy.shape[0]):
seq_l = int(m_te[b].sum().item())
for t in range(seq_l):
if rng_noise.random() < 0.25:
x_te_noisy[b, t] = 1 # <UNK> simulating OCR noise / unseen rare names
sm_noisy_tags = [[ID_TO_TAG[i] for i in seq] for seq in softmax_model.decode(x_te_noisy, m_te)]
sm_noisy_f1 = compute_bio_span_f1(gold_test_tags, sm_noisy_tags)
sm_noisy_illegal = compute_illegal_bio_rate(sm_noisy_tags)
# 2. Exact BiLSTM-CRF
torch.manual_seed(cfg.seed)
crf_model = BiLSTMCRF(
vocab_size=len(vocab),
num_tags=len(BIO_TAGS),
embed_dim=cfg.embed_dim,
hidden_dim=cfg.hidden_dim,
enforce_bio_constraints=True,
)
opt_c = torch.optim.Adam(crf_model.parameters(), lr=cfg.learning_rate * 1.25)
crf_model.train()
for _ in range(cfg.epochs_crf):
perm = torch.randperm(x_tr.shape[0])
for start in range(0, x_tr.shape[0], cfg.batch_size):
idx = perm[start : start + cfg.batch_size]
opt_c.zero_grad()
bx = _apply_unk_dropout(x_tr[idx], m_tr[idx], p=0.12)
loss = crf_model.loss(bx, y_tr[idx], m_tr[idx])
loss.backward()
torch.nn.utils.clip_grad_norm_(crf_model.parameters(), max_norm=3.0)
opt_c.step()
crf_model.eval()
crf_pred_ids, _ = crf_model.decode(x_te, m_te)
crf_pred_tags = [[ID_TO_TAG[i] for i in seq] for seq in crf_pred_ids]
crf_f1 = compute_bio_span_f1(gold_test_tags, crf_pred_tags)
crf_illegal = compute_illegal_bio_rate(crf_pred_tags)
crf_noisy_ids, _ = crf_model.decode(x_te_noisy, m_te)
crf_noisy_tags = [[ID_TO_TAG[i] for i in seq] for seq in crf_noisy_ids]
crf_noisy_f1 = compute_bio_span_f1(gold_test_tags, crf_noisy_tags)
crf_noisy_illegal = compute_illegal_bio_rate(crf_noisy_tags)
return {
"vocab": vocab,
"softmax_model": softmax_model,
"crf_model": crf_model,
"softmax_clean": {**sm_f1, **sm_illegal},
"softmax_noisy_ocr": {**sm_noisy_f1, **sm_noisy_illegal},
"crf_clean": {**crf_f1, **crf_illegal},
"crf_noisy_ocr": {**crf_noisy_f1, **crf_noisy_illegal},
}
class ResumeProfile(BaseModel):
"""Strict Pydantic v2 structured output contract for Enterprise ATS Resume Document AI."""
model_config = ConfigDict(extra="forbid")
candidate_name: str = Field(min_length=1)
target_role: str = Field(min_length=1)
skills: list[str] = Field(min_length=1)
organizations: list[str] = Field(min_length=1)
education: list[str] = Field(min_length=1)
reading_order_method: str = Field(pattern="^(xy_cut|naive_y_sort)$")
reading_order_accuracy: float = Field(ge=0.0, le=1.0)
pii_redacted_summary: str = Field(min_length=1)
def evaluate_layout_reading_order(docs: list[list[LayoutBox]]) -> dict[str, float]:
"""Compare Naive Y-Sort vs Recursive XY-Cut reading-order accuracy across 2-column resumes."""
naive_exact = 0
xy_exact = 0
naive_pair_acc: list[float] = []
xy_pair_acc: list[float] = []
def _pairwise_order_acc(ordered: list[LayoutBox]) -> float:
orders = [b.true_order for b in ordered]
total = 0
correct = 0
for i in range(len(orders)):
for j in range(i + 1, len(orders)):
total += 1
if orders[i] < orders[j]:
correct += 1
return float(correct) / float(max(1, total))
for boxes in docs:
naive_ord = naive_y_sort_reading_order(boxes)
xy_ord = xy_cut_reading_order(boxes)
if [b.true_order for b in naive_ord] == list(range(len(boxes))):
naive_exact += 1
if [b.true_order for b in xy_ord] == list(range(len(boxes))):
xy_exact += 1
naive_pair_acc.append(_pairwise_order_acc(naive_ord))
xy_pair_acc.append(_pairwise_order_acc(xy_ord))
n = max(1, len(docs))
return {
"n_docs": float(len(docs)),
"naive_exact_doc_accuracy": float(naive_exact) / float(n),
"xy_cut_exact_doc_accuracy": float(xy_exact) / float(n),
"naive_pairwise_order_accuracy": float(np.mean(naive_pair_acc)),
"xy_cut_pairwise_order_accuracy": float(np.mean(xy_pair_acc)),
}
def parse_resume_layout_to_profile(
boxes: list[LayoutBox],
crf_model: BiLSTMCRF,
vocab: dict[str, int],
method: str = "xy_cut",
) -> ResumeProfile:
"""End-to-end Document AI pipeline: 2D layout sort -> BiLSTM-CRF IE -> Pydantic v2 + PII redaction."""
ordered = xy_cut_reading_order(boxes) if method == "xy_cut" else naive_y_sort_reading_order(boxes)
orders = [b.true_order for b in ordered]
order_acc = float(sum(1 for idx, o in enumerate(orders) if idx == o)) / float(max(1, len(orders)))
tokens = [tok for box in ordered for tok in box.text.split()]
ids = torch.tensor([[vocab.get(tok, 1) for tok in tokens]], dtype=torch.long)
mask = torch.ones_like(ids, dtype=torch.bool)
crf_model.eval()
pred_paths, _ = crf_model.decode(ids, mask)
pred_tags = [ID_TO_TAG[i] for i in pred_paths[0]]
spans = sorted(extract_bio_spans(pred_tags))
extracted: dict[str, list[str]] = {k: [] for k in ("PERSON", "ROLE", "SKILL", "ORG", "EDU")}
for start, end, et in spans:
text_span = " ".join(tokens[start:end])
if et in extracted and text_span not in extracted[et]:
extracted[et].append(text_span)
candidate = extracted["PERSON"][0] if extracted["PERSON"] else "Unknown Candidate"
role = extracted["ROLE"][0] if extracted["ROLE"] else "Unclassified Role"
skills = extracted["SKILL"] or ["General ML"]
orgs = extracted["ORG"] or ["Unlisted Org"]
edu = extracted["EDU"] or ["Unlisted Education"]
redacted = (
f"[REDACTED_PERSON] | Role: {role} | Skills: {', '.join(skills)} "
f"| Org: {', '.join(orgs)} | Edu: {', '.join(edu)}"
)
return ResumeProfile(
candidate_name=candidate,
target_role=role,
skills=skills,
organizations=orgs,
education=edu,
reading_order_method=method,
reading_order_accuracy=order_acc,
pii_redacted_summary=redacted,
)
def save_bilstm_crf_safetensors(model: BiLSTMCRF) -> bytes:
"""Serialize BiLSTMCRF parameters safely via zero-pickle safetensors binary format."""
tensors = {k: v.detach().cpu().contiguous() for k, v in model.state_dict().items()}
return bytes(sf_save(tensors))
def load_bilstm_crf_safetensors(model: BiLSTMCRF, raw_bytes: bytes) -> BiLSTMCRF:
"""Reload BiLSTMCRF parameters bit-identically from safetensors bytes (strict=True)."""
loaded = sf_load(raw_bytes)
model.load_state_dict(loaded, strict=True)
model.eval()
return model
"""CLI Benchmark & Artifact Generator for Lab 10 (`T1-P4-U01`: NLP, Sequence Models & Resume DocAI)."""
from __future__ import annotations
import argparse
import json
import sys
import time
from pathlib import Path
from typing import Any
_SRC_DIR = str(Path(__file__).resolve().parents[1] / "src")
if _SRC_DIR not in sys.path:
sys.path.insert(0, _SRC_DIR)
import numpy as np # noqa: E402
import torch # noqa: E402
from nlp_docai_lab.bilstm_crf_resume_ie import ( # noqa: E402
BiLSTMCRF,
CRFTrainConfig,
LinearChainCRF,
evaluate_layout_reading_order,
load_bilstm_crf_safetensors,
parse_resume_layout_to_profile,
save_bilstm_crf_safetensors,
train_resume_ner_models,
)
from nlp_docai_lab.resume_dataset import ( # noqa: E402
BIO_TAGS,
generate_domain_classification_corpus,
generate_resume_ner_dataset,
generate_two_column_layout_resumes,
)
from nlp_docai_lab.sequence_models import ( # noqa: E402
LongRangeConfig,
demonstrate_gradient_clipping,
evaluate_text_xai_faithfulness,
measure_bptt_gradient_flow,
train_domain_text_classifier,
train_long_range_benchmark,
)
from nlp_docai_lab.tokenization_and_bm25 import ( # noqa: E402
BM25Index,
ByteLevelBPETokenizer,
SGNSConfig,
TfidfRetriever,
compare_cleanup_modes,
compute_shifted_pmi_matrix,
compute_tokenizer_fertility,
normalize_text_unicode,
train_word2vec_sgns,
)
def _cosine(a: np.ndarray, b: np.ndarray) -> float:
return float(np.dot(a, b) / max(float(np.linalg.norm(a) * np.linalg.norm(b)), 1e-12))
def run_lab10_benchmark(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Execute Tier 1 + Tier 2 NLP & Resume Document AI benchmark and assemble workbench_panels."""
# 1. Tier 1: Unicode Normalization, Byte-Level BPE & Fertility Tax
nfd_sample = (
"He\u0323 tho\u0302\u0301ng tri\u0301ch xua\u0302\u0301t "
"ho\u0302\u0300 so\u031b Python 3.12 & C++"
)
nfc_sample = normalize_text_unicode(nfd_sample, form="NFC")
cleanup_cmp = compare_cleanup_modes(
"Senior ML Engineer | Python 3.12, C++, PyTorch 2.x | F1-score 98.4%"
)
en_train_corpus = [
"Senior Machine Learning Engineer building production NLP pipelines with PyTorch and FastAPI.",
"Implemented Byte-Level BPE tokenization and Okapi BM25 hybrid retrieval for enterprise search.",
"Trained BiLSTM-CRF named entity recognition models for automated resume document extraction.",
"Optimized sequence modeling with LSTM forget gates and global gradient norm clipping on CPU.",
"Evaluated text classification faithfulness using Token Integrated Gradients and comprehensiveness.",
"Designed multi-column PDF layout parsing using recursive XY-Cut and Pydantic v2 validation.",
] * 12
vi_eval_corpus = [
"Kỹ sư Học máy cao cấp xây dựng hệ thống xử lý ngôn ngữ tự nhiên tiếng Việt và trích xuất hồ sơ.",
"Chuẩn hóa bảng mã Unicode NFC giúp giảm phân mảnh từ điển và tiết kiệm chi phí ngữ cảnh LLM.",
"Kiến trúc BiLSTM-CRF kết hợp giải mã Viterbi triệt tiêu hoàn toàn lỗi chuyển tiếp nhãn thực thể.",
"Thuật toán cắt cột đệ quy XY-Cut khôi phục chính xác thứ tự đọc trên hồ sơ ứng viên hai cột.",
]
en_eval_corpus = [
"Senior Machine Learning Engineer designing production NLP and Document AI retrieval pipelines.",
"Normalized Unicode text preserves entity casing and technical symbols during BPE tokenization.",
"BiLSTM-CRF with Viterbi decoding eliminates illegal BIO transitions across resume entity spans.",
"Recursive XY-Cut column segmentation restores exact reading order for two-column PDF resumes.",
]
code_eval_corpus = [
"def viterbi_decode(emissions: torch.Tensor, mask: torch.Tensor) -> list[list[int]]:",
"loss = crf.neg_log_likelihood(emissions, tags, mask); clip_grad_norm_(params, max_norm=1.0)",
"profile = ResumeProfile(candidate_name=name, skills=['PyTorch 2.x'], reading_order_method='xy_cut')",
]
bpe_en = ByteLevelBPETokenizer()
bpe_en_meta = bpe_en.train(en_train_corpus, vocab_size=512, min_freq=2)
bpe_multi = ByteLevelBPETokenizer()
bpe_multi_meta = bpe_multi.train(
en_train_corpus + (vi_eval_corpus * 12) + (code_eval_corpus * 8),
vocab_size=640,
min_freq=2,
)
roundtrip_probe = "Ứng viên Nguyễn Minh Anh — Senior NLP Engineer (PyTorch 2.x, C++, F1=0.98)!"
rt_ids = bpe_multi.encode(roundtrip_probe, normalize_nfc=False)
rt_lossless = bpe_multi.decode(rt_ids) == roundtrip_probe
fert_en_on_en = compute_tokenizer_fertility(bpe_en, en_eval_corpus)
fert_en_on_vi = compute_tokenizer_fertility(bpe_en, vi_eval_corpus)
fert_en_on_code = compute_tokenizer_fertility(bpe_en, code_eval_corpus)
fert_multi_on_vi = compute_tokenizer_fertility(bpe_multi, vi_eval_corpus)
fert_multi_on_en = compute_tokenizer_fertility(bpe_multi, en_eval_corpus)
f_en_en = fert_en_on_en["fertility_tokens_per_word"]
f_en_vi = fert_en_on_vi["fertility_tokens_per_word"]
f_en_code = fert_en_on_code["fertility_tokens_per_word"]
f_multi_vi = fert_multi_on_vi["fertility_tokens_per_word"]
vi_fertility_tax_ratio = f_en_vi / max(f_en_en, 1e-9)
vi_fertility_reduction_pct = (1.0 - f_multi_vi / f_en_vi) * 100.0
# 2. Tier 1: Okapi BM25 vs TF-IDF & Word2Vec SGNS (+ Shifted PMI)
retrieval_docs = [
"Production resume parser using bilstm crf viterbi decoding and xy-cut layout for pdf extraction.",
("bilstm " * 18) + "tutorial introduction overview slides general lecture notes.",
"Compliance audit requires clause iso-20022 section 14-2b with strict pii redaction and safetensors.",
"General compliance policy document covering enterprise governance and quarterly audit review.",
"Okapi bm25 applies term frequency saturation k1 and document length normalization b for ranking.",
"Okapi bm25 overview " + ("background enterprise text archive notes " * 16),
]
retrieval_queries = [
("bilstm crf viterbi xy-cut", 0),
("bilstm viterbi layout", 0),
("clause iso-20022 safetensors", 2),
("okapi bm25 length normalization", 4),
]
bm25_idx = BM25Index(retrieval_docs, k1=1.5, b=0.75)
tfidf_idx = TfidfRetriever(retrieval_docs)
bm25_mrr = 0.0
tfidf_mrr = 0.0
bm25_top1 = 0
tfidf_top1 = 0
for q, gold_id in retrieval_queries:
b_rank = [doc_i for doc_i, _ in bm25_idx.rank(q, top_k=len(retrieval_docs))]
t_rank = [doc_i for doc_i, _ in tfidf_idx.rank(q, top_k=len(retrieval_docs))]
bm25_mrr += 1.0 / float(b_rank.index(gold_id) + 1)
tfidf_mrr += 1.0 / float(t_rank.index(gold_id) + 1)
bm25_top1 += int(b_rank[0] == gold_id)
tfidf_top1 += int(t_rank[0] == gold_id)
bm25_mrr /= float(len(retrieval_queries))
tfidf_mrr /= float(len(retrieval_queries))
bm25_true_vs_spam = (
bm25_idx.score_document("bilstm viterbi", 0),
bm25_idx.score_document("bilstm viterbi", 1),
)
bm25_short_vs_long = (
bm25_idx.score_document("okapi bm25", 4),
bm25_idx.score_document("okapi bm25", 5),
)
sgns_sentences = [
["pytorch", "bilstm", "crf", "ner", "viterbi", "tokens"],
["pytorch", "lstm", "gru", "sequence", "bptt", "gradients"],
["bilstm", "crf", "resume", "entity", "viterbi", "spans"],
["kafka", "spark", "iceberg", "pipeline", "trino", "duckdb"],
["kafka", "airflow", "warehouse", "spark", "pipeline", "etl"],
["basel", "var", "credit", "hedging", "sharpe", "volatility"],
["basel", "risk", "credit", "derivatives", "liquidity", "var"],
] * (6 if quick else 10)
sgns_cfg = SGNSConfig(
embedding_dim=20,
window_size=2,
num_negatives=4,
epochs=35 if quick else 55,
learning_rate=0.08,
seed=seed,
)
sgns_res = train_word2vec_sgns(sgns_sentences, config=sgns_cfg)
w2i = sgns_res["word_to_id"]
emb_norm = sgns_res["embeddings_norm"]
assert isinstance(w2i, dict) and isinstance(emb_norm, np.ndarray)
cos_related_nlp = _cosine(emb_norm[w2i["bilstm"]], emb_norm[w2i["crf"]])
cos_related_data = _cosine(emb_norm[w2i["kafka"]], emb_norm[w2i["spark"]])
cos_unrelated = _cosine(emb_norm[w2i["bilstm"]], emb_norm[w2i["basel"]])
spmi = compute_shifted_pmi_matrix(sgns_sentences, w2i, window_size=2, num_negatives=4)
w_in = sgns_res["w_in"]
w_out = sgns_res["w_out"]
assert isinstance(w_in, np.ndarray) and isinstance(w_out, np.ndarray)
dot_mat = w_in @ w_out.T
nz_mask = spmi != 0.0
spmi_corr = float(np.corrcoef(dot_mat[nz_mask], spmi[nz_mask])[0, 1])
# 3. Tier 2: BPTT Gradient Flow, Clipping, Long-Range & Text XAI
bptt_flow = measure_bptt_gradient_flow(
seq_len=36,
hidden_dim=32,
vanishing_rho=0.68,
exploding_rho=1.45,
lstm_forget_bias=2.0,
seed=seed,
)
clip_demo = demonstrate_gradient_clipping(
seq_len=36, hidden_dim=32, exploding_rho=1.60, max_norm=1.0, seed=seed
)
lr_cfg = LongRangeConfig(
seq_len=36,
vocab_size=16,
n_train=220 if quick else 360,
n_test=80 if quick else 120,
embed_dim=16,
hidden_dim=32,
epochs=20 if quick else 26,
batch_size=32,
learning_rate=6e-3,
max_grad_norm=1.0,
seed=seed,
)
lr_bench = train_long_range_benchmark(lr_cfg)
dom_corpus = generate_domain_classification_corpus(n_per_class=45 if quick else 65, seed=seed)
dom_train = train_domain_text_classifier(dom_corpus, epochs=10 if quick else 12, seed=seed)
ig_steps = 48 if quick else 96
xai_audit = evaluate_text_xai_faithfulness(
model=dom_train["bilstm_model"],
test_tokens=dom_corpus["test_tokens"],
test_rationales=dom_corpus["test_rationales"],
vocab=dom_train["vocab"],
n_eval=12 if quick else 24,
top_k=3,
ig_steps=ig_steps,
seed=seed,
)
# 4. Tier 2: Exact CRF Parity, BiLSTM-CRF Resume NER, XY-Cut & Safetensors
torch.manual_seed(seed)
tiny_crf = LinearChainCRF(num_tags=len(BIO_TAGS), enforce_bio_constraints=True)
tiny_emit = torch.randn(1, 4, len(BIO_TAGS))
tiny_mask = torch.ones((1, 4), dtype=torch.bool)
fwd_log_z = float(tiny_crf.forward_log_partition(tiny_emit, tiny_mask)[0].item())
bf_log_z = float(tiny_crf.bruteforce_log_partition(tiny_emit[0]))
crf_partition_abs_err = abs(fwd_log_z - bf_log_z)
ner_data = generate_resume_ner_dataset(
n_train=160 if quick else 260,
n_test=60 if quick else 90,
seed=seed,
)
ner_cfg = CRFTrainConfig(
embed_dim=32,
hidden_dim=32,
epochs_softmax=14 if quick else 20,
epochs_crf=16 if quick else 24,
batch_size=24,
learning_rate=8e-3,
seed=seed,
)
ner_res = train_resume_ner_models(ner_data["train"], ner_data["test"], config=ner_cfg)
crf_model: BiLSTMCRF = ner_res["crf_model"]
ner_vocab: dict[str, int] = ner_res["vocab"]
sf_bytes = save_bilstm_crf_safetensors(crf_model)
reloaded_crf = load_bilstm_crf_safetensors(
BiLSTMCRF(vocab_size=len(ner_vocab), num_tags=len(BIO_TAGS), embed_dim=32, hidden_dim=32),
sf_bytes,
)
probe_x = torch.tensor(
[[ner_vocab.get(tok, 1) for tok in ner_data["test"][0].tokens]], dtype=torch.long
)
probe_mask = torch.ones_like(probe_x, dtype=torch.bool)
with torch.no_grad():
diff_t = (crf_model.emissions(probe_x) - reloaded_crf.emissions(probe_x)).abs()
sf_max_diff = float(diff_t.max().item())
t0 = time.perf_counter()
n_lat = 40
for _ in range(n_lat):
reloaded_crf.decode(probe_x, probe_mask)
crf_cpu_ms = (time.perf_counter() - t0) * 1000.0 / float(n_lat)
layout_docs = generate_two_column_layout_resumes(n_docs=24, seed=seed)
layout_eval = evaluate_layout_reading_order(layout_docs)
sample_profile_xy = parse_resume_layout_to_profile(
layout_docs[0], reloaded_crf, ner_vocab, method="xy_cut"
)
sample_profile_naive = parse_resume_layout_to_profile(
layout_docs[0], reloaded_crf, ner_vocab, method="naive_y_sort"
)
sm_clean = ner_res["softmax_clean"]
sm_noisy = ner_res["softmax_noisy_ocr"]
crf_clean = ner_res["crf_clean"]
crf_noisy = ner_res["crf_noisy_ocr"]
rnn_acc = lr_bench["vanilla_rnn"]["test_accuracy"] * 100.0
lstm_acc = lr_bench["lstm"]["test_accuracy"] * 100.0
gru_acc = lr_bench["gru"]["test_accuracy"] * 100.0
bi_acc = dom_train["bilstm_test_accuracy"] * 100.0
cnn_acc = dom_train["cnn_lstm_test_accuracy"] * 100.0
# 5. Assemble Wave 7-8 Workbench Panels (6 KPIs, 4 Bars, 4 Tables)
workbench_panels: dict[str, Any] = {
"kpis": [
{
"id": "kpi_bpe_vi_fertility_tax",
"label": "BPE VI Fertility Tax & Reduction",
"value": f"{vi_fertility_tax_ratio:.2f}x -> -{vi_fertility_reduction_pct:.1f}%",
"unit": f"(VI {f_en_vi:.2f} -> {f_multi_vi:.2f} tok/w)",
"status": "ok",
"detail": (
f"Lossless UTF-8 round-trip={rt_lossless}; EN-centric BPE taxes Vietnamese "
f"{vi_fertility_tax_ratio:.2f}x over EN ({f_en_en:.2f})."
),
},
{
"id": "kpi_bm25_vs_tfidf_mrr",
"label": "Okapi BM25 vs TF-IDF MRR",
"value": f"{bm25_mrr:.3f}",
"unit": f"(vs TF-IDF {tfidf_mrr:.3f})",
"status": "ok",
"detail": (
f"BM25 Top-1={bm25_top1}/{len(retrieval_queries)} vs "
f"TF-IDF={tfidf_top1}/{len(retrieval_queries)}; SGNS SPMI corr={spmi_corr:.2f}."
),
},
{
"id": "kpi_bptt_gradient_highway",
"label": "BPTT Gradient Flow (T=36)",
"value": f"{bptt_flow['lstm_c_ratio_t1_to_tT']:.3f}",
"unit": f"(vs RNN {bptt_flow['vanilla_rnn_vanishing_ratio_t1_to_tT']:.1e})",
"status": "ok",
"detail": (
f"LSTM Test Acc={lstm_acc:.1f}%, GRU={gru_acc:.1f}% vs "
f"Vanilla RNN={rnn_acc:.1f}%."
),
},
{
"id": "kpi_bilstm_crf_span_f1",
"label": "BiLSTM-CRF Resume Span F1",
"value": f"{crf_clean['span_f1'] * 100:.1f}%",
"unit": f"(Noisy OCR {crf_noisy['span_f1'] * 100:.1f}%)",
"status": "ok",
"detail": (
f"Forward-vs-BruteForce log Z err={crf_partition_abs_err:.2e}; "
f"safetensors diff={sf_max_diff:.1e} ({len(sf_bytes):,} B, {crf_cpu_ms:.2f} ms/CV)."
),
},
{
"id": "kpi_crf_zero_illegal_bio",
"label": "Illegal BIO Transition Rate",
"value": f"{crf_noisy['illegal_bio_rate'] * 100:.2f}%",
"unit": f"(vs Softmax {sm_noisy['illegal_bio_rate'] * 100:.2f}%)",
"status": "ok",
"detail": (
f"Viterbi CRF guarantees 0 illegal BIO transitions under 25% OCR <UNK> noise "
f"(vs {int(sm_noisy['illegal_transitions'])} Softmax violations)."
),
},
{
"id": "kpi_xy_cut_and_text_xai",
"label": "XY-Cut Reading Order & IG XAI",
"value": f"{layout_eval['xy_cut_exact_doc_accuracy'] * 100:.0f}%",
"unit": f"(vs Y-Sort {layout_eval['naive_exact_doc_accuracy'] * 100:.0f}%)",
"status": "ok",
"detail": (
f"Token IG Comp={xai_audit['ig_comprehensiveness']:.3f} vs "
f"Rand={xai_audit['random_comprehensiveness']:.3f}; "
f"Completeness err={xai_audit['ig_max_completeness_error']:.2e}."
),
},
],
"bars": [
{
"id": "bar_tokenizer_fertility_disparity",
"title": "Byte-Level BPE Fertility: English vs Vietnamese vs Code (Tokens / Word)",
"metric_label": "Fertility (Lower = Cheaper Context)",
"items": [
{
"label": "en_bpe_on_english",
"value": round(f_en_en, 3),
"display": f"EN-BPE on English: {f_en_en:.2f} tok/w",
"css_class": "is-fast",
},
{
"label": "en_bpe_on_vietnamese",
"value": round(f_en_vi, 3),
"display": f"EN-BPE on VI: {f_en_vi:.2f} tok/w ({vi_fertility_tax_ratio:.2f}x tax)",
"css_class": "is-slow",
},
{
"label": "en_bpe_on_code",
"value": round(f_en_code, 3),
"display": f"EN-BPE on Python Code: {f_en_code:.2f} tok/w",
"css_class": "is-mid",
},
{
"label": "multi_bpe_on_vietnamese",
"value": round(f_multi_vi, 3),
"display": (
f"Multi-BPE on VI: {f_multi_vi:.2f} tok/w "
f"(-{vi_fertility_reduction_pct:.1f}%)"
),
"css_class": "is-fast",
},
],
},
{
"id": "bar_long_range_sequence_accuracy",
"title": "Long-Range Dependency Benchmark (T=36): Vanilla RNN vs LSTM vs GRU (%)",
"metric_label": "Test Accuracy (%)",
"items": [
{
"label": "vanilla_rnn_t36",
"value": round(rnn_acc, 2),
"display": f"Vanilla RNN: {rnn_acc:.1f}% (BPTT Vanishing)",
"css_class": "is-slow",
},
{
"label": "lstm_t36",
"value": round(lstm_acc, 2),
"display": f"LSTM (b_f=1.5): {lstm_acc:.1f}%",
"css_class": "is-fast",
},
{
"label": "gru_t36",
"value": round(gru_acc, 2),
"display": f"GRU: {gru_acc:.1f}%",
"css_class": "is-fast",
},
{
"label": "bilstm_domain_routing",
"value": round(bi_acc, 2),
"display": f"BiLSTM Cls: {bi_acc:.1f}% (CNN-LSTM {cnn_acc:.1f}%)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_resume_ner_softmax_vs_crf",
"title": "Resume NER Span Exact F1 (%): BiLSTM-Softmax vs BiLSTM-CRF",
"metric_label": "Span-Level Micro F1 (%)",
"items": [
{
"label": "softmax_clean_f1",
"value": round(sm_clean["span_f1"] * 100.0, 2),
"display": f"Softmax Clean: {sm_clean['span_f1'] * 100:.1f}%",
"css_class": "is-mid",
},
{
"label": "crf_clean_f1",
"value": round(crf_clean["span_f1"] * 100.0, 2),
"display": f"BiLSTM-CRF Clean: {crf_clean['span_f1'] * 100:.1f}% (0% illegal)",
"css_class": "is-fast",
},
{
"label": "softmax_noisy_f1",
"value": round(sm_noisy["span_f1"] * 100.0, 2),
"display": (
f"Softmax 25% OCR: {sm_noisy['span_f1'] * 100:.1f}% "
f"({sm_noisy['illegal_bio_rate'] * 100:.2f}% illegal)"
),
"css_class": "is-slow",
},
{
"label": "crf_noisy_f1",
"value": round(crf_noisy["span_f1"] * 100.0, 2),
"display": f"CRF 25% OCR: {crf_noisy['span_f1'] * 100:.1f}% (0.00% illegal)",
"css_class": "is-fast",
},
],
},
{
"id": "bar_text_xai_faithfulness",
"title": "Token Integrated Gradients Faithfulness (ERASER): Comp & Suff",
"metric_label": "Probability Shift",
"items": [
{
"label": "ig_comprehensiveness",
"value": round(xai_audit["ig_comprehensiveness"], 4),
"display": f"IG Comprehensiveness (High): {xai_audit['ig_comprehensiveness']:.3f}",
"css_class": "is-fast",
},
{
"label": "random_comprehensiveness",
"value": round(xai_audit["random_comprehensiveness"], 4),
"display": f"Random Comprehensiveness: {xai_audit['random_comprehensiveness']:.3f}",
"css_class": "is-slow",
},
{
"label": "ig_sufficiency",
"value": round(max(0.0, xai_audit["ig_sufficiency"]), 4),
"display": f"IG Sufficiency (Low): {xai_audit['ig_sufficiency']:.3f}",
"css_class": "is-fast",
},
{
"label": "random_sufficiency",
"value": round(max(0.0, xai_audit["random_sufficiency"]), 4),
"display": f"Random Sufficiency: {xai_audit['random_sufficiency']:.3f}",
"css_class": "is-slow",
},
],
},
],
"tables": [
{
"id": "tbl_tokenization_bm25_sgns",
"title": "Tier 1 NLP: Unicode NFC, Byte-Level BPE, Okapi BM25 & Word2Vec SGNS",
"columns": ["Component", "Configuration", "Measured Metric", "Status"],
"rows": [
[
"Unicode NFC & Safe Cleanup",
"NFC vs Destructive Strip",
(
f"Safe keeps {cleanup_cmp['safe_special_signal_count']} NER/code signals "
f"vs {cleanup_cmp['destructive_special_signal_count']} destructive"
),
"PASS",
],
[
"Byte-Level BPE (EN vs Multi)",
f"|V|={bpe_en_meta['vocab_size']} vs {bpe_multi_meta['vocab_size']}",
(
f"Lossless={rt_lossless} | VI Fertility {f_en_vi:.2f} -> "
f"{f_multi_vi:.2f} (-{vi_fertility_reduction_pct:.1f}%)"
),
"PASS",
],
[
"Okapi BM25 vs TF-IDF Retrieval",
"k1=1.5, b=0.75 (4 queries)",
(
f"BM25 MRR={bm25_mrr:.3f} vs TF-IDF={tfidf_mrr:.3f}; "
f"True {bm25_true_vs_spam[0]:.2f} > Spam {bm25_true_vs_spam[1]:.2f}"
),
"PASS",
],
[
"Word2Vec SGNS (Pure NumPy)",
f"d={sgns_cfg.embedding_dim}, K={sgns_cfg.num_negatives}",
(
f"Loss {sgns_res['initial_loss']:.3f} -> {sgns_res['final_loss']:.3f} | "
f"cos(bilstm,crf)={cos_related_nlp:.2f} vs basel={cos_unrelated:.2f}"
),
"PASS",
],
],
},
{
"id": "tbl_bptt_sequence_models",
"title": "Tier 2 Sequence Models: BPTT Gradient Pathology, Clipping & Recall (T=36)",
"columns": ["Model / Regime", "Grad Ratio ||g_1||/||g_T||", "T=36 Test Acc", "Notes"],
"rows": [
[
"Vanilla RNN (Vanishing rho=0.68)",
f"{bptt_flow['vanilla_rnn_vanishing_ratio_t1_to_tT']:.2e}",
f"{rnn_acc:.1f}%",
"Exponential Jacobian decay blocks long-range recall",
],
[
"Vanilla RNN (Exploding rho=1.45/1.60)",
f"{bptt_flow['vanilla_rnn_exploding_ratio_t1_to_tT']:.2e}",
"Unstable unclipped",
(
f"Clip(tau=1.0): {clip_demo['raw_grad_norm']:.2f} -> "
f"{clip_demo['clipped_grad_norm']:.3f} "
f"(cos={clip_demo['direction_cosine_similarity']:.4f})"
),
],
[
"LSTM (Forget Bias b_f=1.5/2.0)",
(
f"c_t={bptt_flow['lstm_c_ratio_t1_to_tT']:.3f} | "
f"h_t={bptt_flow['lstm_h_ratio_t1_to_tT']:.3f}"
),
f"{lstm_acc:.1f}%",
f"Additive cell highway ({int(lr_bench['lstm']['num_params']):,} params)",
],
[
"GRU & Hybrid CNN-LSTM",
"Gated update (1-z_t)",
f"GRU {gru_acc:.1f}% | CNN-LSTM {cnn_acc:.1f}%",
f"GRU params={int(lr_bench['gru']['num_params']):,} (~25% fewer weights)",
],
],
},
{
"id": "tbl_resume_ner_and_docai",
"title": "Resume Document AI: BiLSTM-CRF, XY-Cut Layout & Zero-Pickle Deployment",
"columns": ["Pipeline Component", "Clean Metric", "Stress Metric", "Production Invariant"],
"rows": [
[
"BiLSTM-Softmax (Independent)",
f"Span F1={sm_clean['span_f1'] * 100:.1f}%",
f"Noisy F1={sm_noisy['span_f1'] * 100:.1f}%",
(
f"Illegal BIO={sm_noisy['illegal_bio_rate'] * 100:.2f}% "
f"({int(sm_noisy['illegal_transitions'])} errs)"
),
],
[
"BiLSTM-CRF (Forward + Viterbi)",
f"Span F1={crf_clean['span_f1'] * 100:.1f}%",
f"Noisy F1={crf_noisy['span_f1'] * 100:.1f}%",
f"0.00% illegal BIO | log Z parity err={crf_partition_abs_err:.2e}",
],
[
"2-Column Resume Reading Order",
f"XY-Cut Exact={layout_eval['xy_cut_exact_doc_accuracy'] * 100:.1f}%",
f"Naive Y-Sort={layout_eval['naive_exact_doc_accuracy'] * 100:.1f}%",
(
f"Pairwise: XY-Cut {layout_eval['xy_cut_pairwise_order_accuracy'] * 100:.1f}% "
f"vs Y-Sort {layout_eval['naive_pairwise_order_accuracy'] * 100:.1f}%"
),
],
[
"Pydantic v2 + Safetensors CPU",
f"Valid JSON ({len(sample_profile_xy.skills)} skills)",
f"CPU Viterbi={crf_cpu_ms:.2f} ms/CV",
f"safetensors={len(sf_bytes):,} B | max diff={sf_max_diff:.1e} | PII redacted",
],
],
},
{
"id": "tbl_text_xai_faithfulness",
"title": "Text Classification XAI: Token Integrated Gradients & ERASER Faithfulness",
"columns": ["Method", "Comprehensiveness", "Sufficiency", "Axiom / Rationale Check"],
"rows": [
[
f"Token Integrated Gradients (M={ig_steps})",
f"{xai_audit['ig_comprehensiveness']:.4f}",
f"{xai_audit['ig_sufficiency']:.4f}",
(
f"Completeness err={xai_audit['ig_max_completeness_error']:.2e} | "
f"Top-3 Hit={xai_audit['rationale_top3_hit_rate'] * 100:.1f}%"
),
],
[
"Random Token Masking Baseline",
f"{xai_audit['random_comprehensiveness']:.4f}",
f"{xai_audit['random_sufficiency']:.4f}",
"Uninformative baseline reference",
],
[
"BiLSTM Domain Router (3-Class)",
f"Test Acc={bi_acc:.1f}%",
f"Evaluated={int(xai_audit['n_evaluated'])} docs",
"Direct embedding interpolation from E'=0",
],
[
"Hybrid CNN-LSTM Domain Router",
f"Test Acc={cnn_acc:.1f}%",
"Conv1d(k=3) + LSTM",
"Local n-gram filter + sequential pooling",
],
],
},
],
}
return {
"config": {
"seed": seed,
"quick": quick,
"seq_len_bptt": lr_cfg.seq_len,
"n_ner_train": len(ner_data["train"]),
"n_ner_test": len(ner_data["test"]),
"n_layout_resumes": len(layout_docs),
},
"tier1_tokenization_and_bm25": {
"nfc_length": len(nfc_sample),
"nfd_length": len(nfd_sample),
"cleanup_comparison": cleanup_cmp,
"bpe_en_meta": bpe_en_meta,
"bpe_multi_meta": bpe_multi_meta,
"lossless_roundtrip_passed": rt_lossless,
"fertility_en_bpe_on_en": fert_en_on_en,
"fertility_en_bpe_on_vi": fert_en_on_vi,
"fertility_en_bpe_on_code": fert_en_on_code,
"fertility_multi_bpe_on_en": fert_multi_on_en,
"fertility_multi_bpe_on_vi": fert_multi_on_vi,
"vi_fertility_tax_ratio": vi_fertility_tax_ratio,
"vi_fertility_reduction_pct": vi_fertility_reduction_pct,
"bm25_mrr": bm25_mrr,
"tfidf_mrr": tfidf_mrr,
"bm25_top1": bm25_top1,
"tfidf_top1": tfidf_top1,
"bm25_true_vs_spam": list(bm25_true_vs_spam),
"bm25_short_vs_long": list(bm25_short_vs_long),
"word2vec_sgns": {
"initial_loss": sgns_res["initial_loss"],
"final_loss": sgns_res["final_loss"],
"cos_bilstm_crf": cos_related_nlp,
"cos_kafka_spark": cos_related_data,
"cos_bilstm_basel": cos_unrelated,
"shifted_pmi_correlation": spmi_corr,
},
},
"tier2_sequence_models_and_xai": {
"bptt_gradient_flow": {
"seq_len": bptt_flow["seq_len"],
"vanilla_rnn_vanishing_ratio_t1_to_tT": bptt_flow["vanilla_rnn_vanishing_ratio_t1_to_tT"],
"vanilla_rnn_exploding_ratio_t1_to_tT": bptt_flow["vanilla_rnn_exploding_ratio_t1_to_tT"],
"lstm_h_ratio_t1_to_tT": bptt_flow["lstm_h_ratio_t1_to_tT"],
"lstm_c_ratio_t1_to_tT": bptt_flow["lstm_c_ratio_t1_to_tT"],
},
"gradient_clipping": clip_demo,
"long_range_benchmark": lr_bench,
"domain_classification": {
"bilstm_test_accuracy": dom_train["bilstm_test_accuracy"],
"cnn_lstm_test_accuracy": dom_train["cnn_lstm_test_accuracy"],
},
"token_integrated_gradients_xai": xai_audit,
},
"tier2_resume_document_ai": {
"crf_forward_vs_bruteforce_abs_err": crf_partition_abs_err,
"softmax_clean": sm_clean,
"softmax_noisy_ocr": sm_noisy,
"crf_clean": crf_clean,
"crf_noisy_ocr": crf_noisy,
"layout_reading_order": layout_eval,
"sample_profile_xy_cut": sample_profile_xy.model_dump(),
"sample_profile_naive_y_sort": sample_profile_naive.model_dump(),
"safetensors_bytes": len(sf_bytes),
"safetensors_max_diff": sf_max_diff,
"crf_viterbi_cpu_ms": crf_cpu_ms,
},
"workbench_panels": workbench_panels,
}
def main() -> None:
parser = argparse.ArgumentParser(description="Run Lab 10 NLP, Sequence Models & Resume DocAI Demo")
parser.add_argument("--seed", type=int, default=42)
parser.add_argument("--quick", action="store_true", help="Fast mode for automated CI verification")
parser.add_argument(
"--output",
type=str,
default="artifacts/ch18_lab10_results.json",
help="Output JSON artifact path",
)
args = parser.parse_args()
result = run_lab10_benchmark(seed=args.seed, quick=args.quick)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
t1 = result["tier1_tokenization_and_bm25"]
t2 = result["tier2_sequence_models_and_xai"]
docai = result["tier2_resume_document_ai"]
seq_t = result["config"]["seq_len_bptt"]
rnn_p = t2["long_range_benchmark"]["vanilla_rnn"]["test_accuracy"] * 100.0
lstm_p = t2["long_range_benchmark"]["lstm"]["test_accuracy"] * 100.0
print(
f"[Lab 10] Saved {out_path} | VI Fertility Tax={t1['vi_fertility_tax_ratio']:.2f}x "
f"(-{t1['vi_fertility_reduction_pct']:.1f}%) | BM25 MRR={t1['bm25_mrr']:.3f} "
f"| T={seq_t} RNN={rnn_p:.1f}% vs LSTM={lstm_p:.1f}% "
f"| BiLSTM-CRF F1={docai['crf_clean']['span_f1']*100:.1f}% "
f"(Illegal={docai['crf_noisy_ocr']['illegal_bio_rate']*100:.2f}%) "
f"| XY-Cut={docai['layout_reading_order']['xy_cut_exact_doc_accuracy']*100:.0f}%"
)
if __name__ == "__main__":
main()
"""16 Deterministic Offline Tests for Lab 10 (`T1-P4-U01` — `nlp_docai_lab`)."""
from __future__ import annotations
import ast
import json
import subprocess
import sys
from pathlib import Path
import numpy as np
import pytest
import torch
from pydantic import ValidationError
from nlp_docai_lab.bilstm_crf_resume_ie import (
BiLSTMCRF,
CRFTrainConfig,
LinearChainCRF,
ResumeProfile,
compute_illegal_bio_rate,
evaluate_layout_reading_order,
load_bilstm_crf_safetensors,
parse_resume_layout_to_profile,
save_bilstm_crf_safetensors,
train_resume_ner_models,
)
from nlp_docai_lab.resume_dataset import (
BIO_TAGS,
ID_TO_TAG,
generate_domain_classification_corpus,
generate_resume_ner_dataset,
generate_two_column_layout_resumes,
)
from nlp_docai_lab.sequence_models import (
LongRangeConfig,
compute_token_integrated_gradients,
demonstrate_gradient_clipping,
evaluate_text_xai_faithfulness,
measure_bptt_gradient_flow,
train_domain_text_classifier,
train_long_range_benchmark,
)
from nlp_docai_lab.tokenization_and_bm25 import (
BM25Index,
ByteLevelBPETokenizer,
SGNSConfig,
TfidfRetriever,
compare_cleanup_modes,
compute_tokenizer_fertility,
normalize_text_unicode,
train_word2vec_sgns,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_DESERIALIZERS = {"pickle", "joblib", "cloudpickle", "dill", "shelve", "marshal"}
def test_01_ast_no_unsafe_deserializers() -> None:
"""AST security gate: strictly ban unsafe deserializers while allowing legitimate SOTA libraries."""
py_files = list((LAB_ROOT / "src").rglob("*.py")) + list((LAB_ROOT / "scripts").rglob("*.py"))
assert len(py_files) >= 5
for path in py_files:
tree = ast.parse(path.read_text(encoding="utf-8"), filename=str(path))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
top = alias.name.split(".")[0]
assert top not in FORBIDDEN_DESERIALIZERS, f"Forbidden import {top} in {path}"
elif isinstance(node, ast.ImportFrom) and node.module:
top = node.module.split(".")[0]
assert top not in FORBIDDEN_DESERIALIZERS, f"Forbidden import {top} in {path}"
def test_02_unicode_nfc_nfkc_and_safe_cleanup_preserves_ner_code() -> None:
"""Verify NFC collapses decomposed Vietnamese diacritics and safe cleanup retains NER/code signals."""
nfd = "Tie\u0302\u0301ng Vie\u0323\u0302t — Python 3.12 & C++"
nfc = normalize_text_unicode(nfd, form="NFC")
assert len(nfc) < len(nfd)
assert nfc == normalize_text_unicode(nfc, form="NFC")
nfkc = normalize_text_unicode("PyTorch\u00a0file²", form="NFKC")
assert "PyTorch" in nfkc and "file2" in nfkc
cmp = compare_cleanup_modes("Candidate Apple built Python 3.12 & C++ with F1-score 99.1%")
assert int(cmp["safe_special_signal_count"]) >= 5
assert int(cmp["destructive_special_signal_count"]) == 0
def test_03_byte_level_bpe_lossless_roundtrip_en_vi_code() -> None:
"""Byte-Level BPE trained from scratch achieves 100% lossless round-trip on EN, Vietnamese & code."""
corpus = [
"Machine Learning Engineer builds NLP pipelines with PyTorch 2.x and BiLSTM-CRF.",
"Kỹ sư dữ liệu xây dựng hệ thống trích xuất hồ sơ tiếng Việt chuẩn xác.",
"def encode(text: str) -> list[int]: return [b for b in text.encode('utf-8')]",
] * 8
tok = ByteLevelBPETokenizer()
meta = tok.train(corpus, vocab_size=420, min_freq=2)
assert meta["vocab_size"] > 256
assert meta["num_merges"] > 30
probes = [
"Senior NLP Engineer at VinAI Research (PyTorch 2.15, C++, F1=0.985)!",
"Ứng viên Nguyễn Minh Anh — Tốt nghiệp Thạc sĩ Khoa học Máy tính tại ĐHQG.",
"score = idf * (f * (k1 + 1)) / (f + k1 * (1 - b + b * dl / avgdl)) # BM25",
"Unseen UTF-8 symbols: αβγ ≤ ≥ ∑ ∏ — € £ ¥",
]
for sample in probes:
ids = tok.encode(sample, normalize_nfc=False)
assert len(ids) > 0
assert tok.decode(ids) == sample
def test_04_tokenizer_fertility_disparity_and_vocab_tradeoff() -> None:
"""EN-centric BPE imposes a clear fertility tax on Vietnamese; multilingual BPE cuts VI fertility."""
en_docs = [
"Production retrieval pipelines combine Okapi BM25 ranking with neural document extraction.",
"BiLSTM-CRF architectures eliminate illegal BIO sequence transitions during resume parsing.",
] * 14
vi_docs = [
"Hệ thống trích xuất hồ sơ ứng viên tiếng Việt sử dụng mô hình BiLSTM-CRF và giải mã Viterbi.",
"Chuẩn hóa bảng mã Unicode NFC giúp hạn chế phân mảnh từ điển dưới từ tiếng Việt.",
]
tok_en = ByteLevelBPETokenizer()
tok_en.train(en_docs, vocab_size=480, min_freq=2)
tok_multi = ByteLevelBPETokenizer()
tok_multi.train(en_docs + (vi_docs * 14), vocab_size=600, min_freq=2)
f_en_en = compute_tokenizer_fertility(tok_en, en_docs[:2])["fertility_tokens_per_word"]
f_en_vi = compute_tokenizer_fertility(tok_en, vi_docs)["fertility_tokens_per_word"]
f_multi_vi = compute_tokenizer_fertility(tok_multi, vi_docs)["fertility_tokens_per_word"]
assert f_en_vi > f_en_en * 1.4
assert f_multi_vi < f_en_vi * 0.75
def test_05_bm25_saturation_length_norm_and_tfidf_benchmark() -> None:
"""Verify Okapi BM25 term saturation (defeating keyword stuffing) and length normalization."""
docs = [
"bilstm crf viterbi resume parser layout",
("bilstm " * 20) + "generic notes slides",
"okapi bm25 saturation length normalization",
"okapi bm25 " + ("background filler archive notes " * 15),
]
bm25 = BM25Index(docs, k1=1.5, b=0.75)
tfidf = TfidfRetriever(docs)
# Multi-term query: concise doc covering both terms MUST outrank single-term keyword-stuffed doc.
assert bm25.score_document("bilstm viterbi", 0) > bm25.score_document("bilstm viterbi", 1)
assert bm25.rank("bilstm viterbi", top_k=1)[0][0] == 0
# Length normalization: concise doc MUST outrank heavily padded doc with same term frequency.
assert bm25.score_document("okapi bm25", 2) > bm25.score_document("okapi bm25", 3)
# Verify saturation upper bound: adding 100x repetitions never explodes linearly.
s_small = BM25Index(["alpha beta", "gamma delta"], k1=1.5, b=0.75).score_document("alpha", 0)
s_huge = BM25Index([("alpha " * 100) + "beta", "gamma delta"], k1=1.5, b=0.75).score_document("alpha", 0)
assert s_huge < s_small * (1.5 + 1.1)
assert tfidf.rank("okapi bm25 saturation", top_k=1)[0][0] == 2
def test_06_word2vec_sgns_loss_decrease_and_semantic_cosine() -> None:
"""Pure NumPy Word2Vec SGNS decreases loss monotonically and separates semantic clusters."""
sents = [
["pytorch", "bilstm", "crf", "viterbi", "ner"],
["pytorch", "lstm", "bilstm", "crf", "sequence"],
["kafka", "spark", "iceberg", "pipeline", "trino"],
["kafka", "spark", "airflow", "warehouse", "pipeline"],
["basel", "var", "credit", "hedging", "volatility"],
] * 10
res = train_word2vec_sgns(
sents,
config=SGNSConfig(embedding_dim=16, window_size=2, num_negatives=4, epochs=40, seed=42),
)
assert float(res["final_loss"]) < float(res["initial_loss"]) * 0.80
w2i = res["word_to_id"]
emb = res["embeddings_norm"]
assert isinstance(w2i, dict) and isinstance(emb, np.ndarray)
sim_related = float(np.dot(emb[w2i["bilstm"]], emb[w2i["crf"]]))
sim_unrelated = float(np.dot(emb[w2i["bilstm"]], emb[w2i["basel"]]))
assert sim_related > sim_unrelated + 0.15
def test_07_bptt_gradient_vanishing_vanilla_rnn_vs_lstm_highway() -> None:
"""Prove Vanilla RNN (rho=0.72) vanishes over T=32 while LSTM cell highway preserves flow."""
flow = measure_bptt_gradient_flow(
seq_len=32, hidden_dim=32, vanishing_rho=0.72, exploding_rho=1.45, lstm_forget_bias=2.0, seed=42
)
rnn_ratio = float(flow["vanilla_rnn_vanishing_ratio_t1_to_tT"])
lstm_c_ratio = float(flow["lstm_c_ratio_t1_to_tT"])
assert rnn_ratio < 1e-3
assert lstm_c_ratio > 0.10
assert lstm_c_ratio > rnn_ratio * 100.0
def test_08_bptt_gradient_explosion_and_norm_clipping_cap() -> None:
"""Verify exploding RNN gradient norm is strictly capped by global L2 clipping with cosine=1.0."""
demo = demonstrate_gradient_clipping(
seq_len=32, hidden_dim=32, exploding_rho=1.60, max_norm=1.0, seed=42
)
assert demo["raw_grad_norm"] > 5.0
assert demo["clipped_grad_norm"] <= 1.0 + 1e-4
assert demo["direction_cosine_similarity"] > 0.9999
def test_09_long_range_sequence_benchmark_lstm_gru_vs_vanilla_rnn() -> None:
"""On T=32 long-range recall, LSTM & GRU clearly outperform vanishing Vanilla RNN."""
bench = train_long_range_benchmark(
LongRangeConfig(
seq_len=32,
vocab_size=16,
n_train=220,
n_test=80,
embed_dim=16,
hidden_dim=32,
epochs=22,
batch_size=32,
learning_rate=6e-3,
seed=42,
)
)
rnn_acc = float(bench["vanilla_rnn"]["test_accuracy"])
lstm_acc = float(bench["lstm"]["test_accuracy"])
gru_acc = float(bench["gru"]["test_accuracy"])
assert lstm_acc >= 0.90
assert gru_acc >= 0.90
assert lstm_acc - rnn_acc >= 0.25
def test_10_token_integrated_gradients_completeness_and_faithfulness() -> None:
"""Token Integrated Gradients satisfies Completeness axiom and beats random masking on ERASER metrics."""
corpus = generate_domain_classification_corpus(n_per_class=45, seed=42)
trained = train_domain_text_classifier(corpus, epochs=10, seed=42)
assert float(trained["bilstm_test_accuracy"]) >= 0.90
assert float(trained["cnn_lstm_test_accuracy"]) >= 0.90
sample_ids = trained["x_test"][0]
ig = compute_token_integrated_gradients(trained["bilstm_model"], sample_ids, steps=64)
assert float(ig["completeness_error"]) < 5e-3
audit = evaluate_text_xai_faithfulness(
model=trained["bilstm_model"],
test_tokens=corpus["test_tokens"],
test_rationales=corpus["test_rationales"],
vocab=trained["vocab"],
n_eval=12,
top_k=3,
ig_steps=64,
seed=42,
)
assert audit["ig_mean_completeness_error"] < 0.01
assert audit["ig_max_completeness_error"] < 0.03
assert audit["ig_comprehensiveness"] > audit["random_comprehensiveness"] + 0.15
assert audit["ig_sufficiency"] < audit["random_sufficiency"] - 0.15
assert audit["rationale_top3_hit_rate"] >= 0.70
def test_11_crf_forward_log_partition_matches_exact_bruteforce() -> None:
"""Exact log-sum-exp Forward algorithm matches brute-force K^T partition enumeration (< 1e-4)."""
torch.manual_seed(42)
for enforce in (False, True):
crf = LinearChainCRF(num_tags=5, enforce_bio_constraints=enforce, tags=BIO_TAGS[:5])
emissions = torch.randn(1, 4, 5)
mask = torch.ones((1, 4), dtype=torch.bool)
fwd = float(crf.forward_log_partition(emissions, mask)[0].item())
bf = float(crf.bruteforce_log_partition(emissions[0]))
assert abs(fwd - bf) < 1e-4
def test_12_crf_viterbi_optimality_and_zero_illegal_bio_transitions() -> None:
"""Viterbi decoding finds global optimum and enforces strictly 0 illegal BIO transitions."""
torch.manual_seed(7)
crf = LinearChainCRF(num_tags=len(BIO_TAGS), enforce_bio_constraints=True)
# Create adversarial emissions peaking on I-SKILL / I-ORG right after O!
emissions = torch.zeros(4, 9, len(BIO_TAGS))
emissions[:, :, 0] = 0.5 # O
emissions[:, 0, 6] = 4.0 # START -> I-SKILL (illegal)
emissions[:, 3, 8] = 4.0 # O -> I-ORG (illegal)
emissions[:, 5, 2] = 4.0 # I-PERSON without B-PERSON (illegal)
mask = torch.ones((4, 9), dtype=torch.bool)
paths, scores = crf.viterbi_decode(emissions, mask)
tag_seqs = [[ID_TO_TAG[i] for i in p] for p in paths]
illegal = compute_illegal_bio_rate(tag_seqs)
assert illegal["illegal_transitions"] == 0.0
assert illegal["illegal_bio_rate"] == 0.0
# Check exact path score consistency with score_sequence
path_tensor = torch.tensor(paths, dtype=torch.long)
recomputed = crf.score_sequence(emissions, path_tensor, mask)
for sc, rec in zip(scores, recomputed.tolist(), strict=True):
assert abs(sc - rec) < 1e-4
def test_13_bilstm_crf_vs_softmax_resume_ner_span_f1_and_legality() -> None:
"""BiLSTM-CRF achieves high Span F1 on group-split Resume NER and 0% illegal BIO even under OCR noise."""
ner_data = generate_resume_ner_dataset(n_train=160, n_test=60, seed=42)
res = train_resume_ner_models(
ner_data["train"],
ner_data["test"],
config=CRFTrainConfig(epochs_softmax=14, epochs_crf=22, seed=42),
)
assert float(res["crf_clean"]["span_f1"]) >= 0.92
assert float(res["crf_clean"]["illegal_bio_rate"]) == 0.0
assert float(res["crf_noisy_ocr"]["illegal_bio_rate"]) == 0.0
assert float(res["softmax_noisy_ocr"]["illegal_bio_rate"]) > 0.0
assert float(res["crf_noisy_ocr"]["span_f1"]) >= 0.90
def test_14_two_column_resume_xy_cut_fixes_naive_y_sort_bug() -> None:
"""Naive Y-Sort fails on 2-column resumes while Recursive XY-Cut recovers 100% exact reading order."""
docs = generate_two_column_layout_resumes(n_docs=20, seed=42)
stats = evaluate_layout_reading_order(docs)
assert stats["naive_exact_doc_accuracy"] == 0.0
assert stats["xy_cut_exact_doc_accuracy"] == 1.0
assert stats["xy_cut_pairwise_order_accuracy"] == 1.0
assert stats["xy_cut_pairwise_order_accuracy"] > stats["naive_pairwise_order_accuracy"] + 0.15
def test_15_pydantic_resume_profile_and_safetensors_zero_pickle_roundtrip() -> None:
"""Verify strict Pydantic v2 ResumeProfile validation, PII redaction & safetensors parity."""
ner_data = generate_resume_ner_dataset(n_train=120, n_test=30, seed=42)
res = train_resume_ner_models(
ner_data["train"],
ner_data["test"],
config=CRFTrainConfig(epochs_softmax=8, epochs_crf=12, seed=42),
)
crf_model: BiLSTMCRF = res["crf_model"]
vocab: dict[str, int] = res["vocab"]
raw_sf = save_bilstm_crf_safetensors(crf_model)
# Safetensors binary starts with 8-byte little-endian uint64 JSON header length.
header_len = int.from_bytes(raw_sf[:8], byteorder="little")
header_json = json.loads(raw_sf[8 : 8 + header_len].decode("utf-8"))
assert "crf.transitions" in header_json
reloaded = load_bilstm_crf_safetensors(
BiLSTMCRF(vocab_size=len(vocab), num_tags=len(BIO_TAGS), embed_dim=32, hidden_dim=32),
raw_sf,
)
probe_x = torch.tensor([[vocab.get(t, 1) for t in ner_data["test"][0].tokens]], dtype=torch.long)
with torch.no_grad():
diff = float((crf_model.emissions(probe_x) - reloaded.emissions(probe_x)).abs().max().item())
assert diff == 0.0
docs = generate_two_column_layout_resumes(n_docs=4, seed=42)
profile = parse_resume_layout_to_profile(docs[0], reloaded, vocab, method="xy_cut")
assert profile.reading_order_accuracy == 1.0
assert "[REDACTED_PERSON]" in profile.pii_redacted_summary
assert profile.candidate_name not in profile.pii_redacted_summary
with pytest.raises(ValidationError):
ResumeProfile(
candidate_name="Test",
target_role="ML Engineer",
skills=["PyTorch"],
organizations=["Lab"],
education=["MSc"],
reading_order_method="xy_cut",
reading_order_accuracy=1.0,
pii_redacted_summary="[REDACTED_PERSON]",
unexpected_extra_field="forbid_me", # type: ignore[call-arg]
)
def test_16_cli_artifact_and_workbench_panels_schema(tmp_path: Path) -> None:
"""CLI demo runs cleanly in --quick mode and emits valid workbench_panels (6 KPIs, 4 bars, 4 tables)."""
out_file = tmp_path / "ch18_lab10_quick.json"
proc = subprocess.run(
[
sys.executable,
str(LAB_ROOT / "scripts" / "run_lab_demo.py"),
"--seed",
"42",
"--quick",
"--output",
str(out_file),
],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
check=True,
)
assert "[Lab 10]" in proc.stdout
data = json.loads(out_file.read_text(encoding="utf-8"))
wb = data["workbench_panels"]
assert len(wb["kpis"]) == 6
assert len(wb["bars"]) == 4
assert len(wb["tables"]) == 4
for kpi in wb["kpis"]:
assert {"id", "label", "value", "unit", "status", "detail"} <= set(kpi.keys())
for bar in wb["bars"]:
assert len(bar["items"]) >= 4
for tbl in wb["tables"]:
assert len(tbl["columns"]) == 4 and len(tbl["rows"]) >= 4
Senior ML Engineer | Python 3.12, C++, PyTorch 2.x | F1-score 98.4%) cho hệ thống NER và truy hồi trong Lab 10 (Test 02), phát biểu nào ĐÚNG?Lab 10 (Test 02), NFC rút gọn chuỗi tổ hợp NFD (52 -> 43 ký tự) về dạng duy nhất; làm sạch phá hủy xóa sạch 10 -> 0 tín hiệu viết hoa/số/ký hiệu (C++, Python 3.12, F1-score) vốn cực kỳ quan trọng cho NER và mã nguồn.
Byte-Level BPE và hiện tượng bất công ngôn ngữ Tokenizer Fertility đo được trong Lab 10 (Tests 03–04), khẳng định nào ĐÚNG?2–3 byte UTF-8 nên bị xé nhỏ trên BPE thuần Anh (5.74 vs 4.00 tok/từ, thuế 1.44x), còn Multi-BPE giảm xuống 2.32 (-59.7%, Test 04) trong khi giải mã vẫn 100% không mất mát nhờ nền 256 byte (Test 03).
Okapi BM25 (\(k_1 = 1.5, b = 0.75\)) với TF-IDF cổ điển và phân tích lý thuyết Word2Vec SGNS trong Lab 10 (Tests 05–06), kết luận nào ĐÚNG?3.27 > 2.38), chuẩn hóa \(b=0.75\) phạt tài liệu dài (2.62 > 1.06, Test 05). Định lý Levy & Goldberg (2014) chứng minh SGNS phân rã Shifted-PMI (r = 0.69, Test 06).
BPTT của Vanilla RNN \(\frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_k} = \frac{\partial \mathcal{L}_T}{\partial \mathbf{h}_T} \prod_{t=k+1}^T \operatorname{diag}(1-\mathbf{h}_t^2)\mathbf{W}_{hh}\) trên \(T = 36\) bước trong Lab 10 (Tests 07–08). Phát biểu nào ĐÚNG?7.36e-07, Test 07). Global L2 Clipping nhân vô hướng toàn vector gradient nên bảo toàn hướng (cosine = 1.0000, Test 08), chỉ xử lý bùng nổ.
Lab 10 (Tests 07, 09), vì sao LSTM và GRU cùng đạt 100.0% trong khi Vanilla RNN kẹt ở 49.2%?LSTM (\(b_f = 1.5\text{–}2.0\)) giữ tỷ số gradient ô nhớ 0.319 vs 7.36e-07 của Vanilla RNN (Test 07). Trong torch.nn.GRU, \(\mathbf{z}_t\) nhân trực tiếp với \(\mathbf{h}_{t-1}\) nên \(b_z = +1.5\) giúp cả LSTM và GRU đạt 100.0% (Test 09).
BiLSTM trên Lab 10 (Test 10), tiêu chuẩn nào chứng minh Token Integrated Gradients thực sự trung thực thay vì ảo giác?ERASER (DeYoung et al. 2020), xóa token thực sự quan trọng phải làm xác suất giảm sâu (Comprehensiveness cao: 0.565 vs 0.085), còn chỉ giữ chúng phải giữ nguyên dự đoán (Sufficiency thấp: -0.001 vs 0.179, Test 10).
BiLSTM-Softmax độc lập với BiLSTM-CRF trên bài toán Resume NER tách nhóm ứng viên trong Lab 10 (Tests 11–13), nhận định nào CHÍNH XÁC?3.52e-07 parity với duyệt vét cạn, Test 11), khóa hoàn toàn chuyển tiếp BIO bất hợp lệ (0.00% vs 2.86% của Softmax dưới 25% nhiễu OCR, Tests 12–13) và word dropout giúp nhận diện tốt cả PERSON chưa từng gặp.
Lab 10 (Tests 14–16), giải pháp nào xử lý đúng lỗi CV 2 cột, mở rộng thực thể zero-shot và an toàn triển khai sản xuất?Naive Y-Sort trộn xen kẽ cột trái–phải (0.0% exact doc order, Pairwise 71.4%), trong khi Recursive XY-Cut khôi phục 100.0% (Test 14); kết hợp safetensors (0 pickle, diff = 0.0), Pydantic v2 (extra="forbid") và ẩn danh PII (Test 15) đạt chuẩn sản xuất.
Hướng dẫn & Gợi ý Từng bước cho 6 Bài tập Trụ cột 5
Bài tập 1 — Chuẩn hóa Unicode, Byte-Level BPE & Kinh tế học Tokenizer Fertility 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Phân tích vì sao bảng chữ cái cơ sở 256 byte UTF-8 đảm bảo tính song ánh cho mọi chuỗi hợp lệ, rồi tính hệ số nhân lên chi phí KV Cache (\(O(L)\)) và prefill Self-Attention (\(O(L^2)\)) khi \(\mathcal{F}_{\text{VI}} / \mathcal{F}_{\text{EN}} = \kappa\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy normalize_text_unicode, compare_cleanup_modes, ByteLevelBPETokenizer và compute_tokenizer_fertility trong tokenization_and_bm25.py (Tests 02–04).
Tiêu chí Đáp án & Số đối chứng
NFC rút gọn tổ hợp tiếng Việt (52 -> 43 ký tự); làm sạch an toàn giữ 10 tín hiệu NER/code vs 0 làm sạch phá hủy; Byte-Level BPE đạt 100% lossless và Multi-BPE (|V|=640) giảm Fertility tiếng Việt -59.7% (5.74 -> 2.32 tok/từ, xóa bỏ thuế 1.44x).
Bài tập 2 — Bão hòa Okapi BM25 & Định lý Phân rã Shifted-PMI của Word2Vec SGNS 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Lấy giới hạn \(\lim_{f \to \infty} \frac{f(k_1+1)}{f + k_1(1 - b + b|d|/\operatorname{avgdl})} = k_1 + 1\); với SGNS, đặt đạo hàm theo \(x = \mathbf{v}_w^\top \mathbf{u}_c\) của \(P(w,c)\log\sigma(x) + K P(w)P(c)\log\sigma(-x)\) bằng 0 để suy ra \(e^x = \frac{P(w,c)}{K P(w)P(c)}\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy BM25Index, TfidfRetriever, train_word2vec_sgns và compute_shifted_pmi_matrix trong tokenization_and_bm25.py (Tests 05–06).
Tiêu chí Đáp án & Số đối chứng
Okapi BM25 (\(k_1=1.5, b=0.75\)) đạt MRR = 1.000 vs TF-IDF 0.875, đánh bại tài liệu spam từ khóa (3.27 > 2.38) và tài liệu độn dài (2.62 > 1.06); SGNS giảm mất mát 2.874 -> 1.022, tách cụm cosine (0.51 vs 0.35) và đạt tương quan r = 0.69 với ma trận Shifted-PMI.
Bài tập 3 — Giải phẫu BPTT, Cắt chuẩn Toàn cục & Cao tốc Ô nhớ LSTM / GRU 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Dùng tính chất dưới nhân của chuẩn phổ \(\|\prod_t \operatorname{diag}(1-h_t^2)\mathbf{W}_{hh}\|_2 \le \gamma^{T-k}\); kiểm tra công thức chính thức của torch.nn.GRU: \(\mathbf{h}_t = (1-\mathbf{z}_t)\odot \mathbf{n}_t + \mathbf{z}_t \odot \mathbf{h}_{t-1}\) để chọn đúng dấu thiên vị \(b_z = +1.5\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy measure_bptt_gradient_flow, demonstrate_gradient_clipping và train_long_range_benchmark trong sequence_models.py (Tests 07–09).
Tiêu chí Đáp án & Số đối chứng
Tại \(T = 36\), tỷ số gradient Vanilla RNN (\(\rho=0.68\)) tắt xuống 7.36e-07 (Test Acc = 49.2%), nhánh nổ \(\rho=1.60\) bị clip_grad_norm_(1.0) kẹp từ 27.75 -> 1.000 (cosine = 1.0000), còn LSTM (tỷ số ô nhớ 0.319) và GRU (5,122 params, -24%) cùng đạt 100.0%.
Bài tập 4 — Kiểm toán Trung thực Giải thích Văn bản (Token IG & ERASER) 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Áp dụng Định lý Cơ bản của Giải tích cho \(g(\alpha) = F_c(\mathbf{E}' + \alpha(\mathbf{E}-\mathbf{E}'))\) trên \([0, 1]\) và giải thích vì sao cầu phương ghép Gauss–Legendre 8 đoạn hội tụ nhanh hơn nhiều so với tổng Riemann thô qua các vùng chuyển cổng sắc nét của BiLSTM.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy train_domain_text_classifier, compute_token_integrated_gradients và evaluate_text_xai_faithfulness trong sequence_models.py (Test 10).
Tiêu chí Đáp án & Số đối chứng
BiLSTM và CNN-LSTM cùng đạt 100.0%; Token IG vector hóa đạt Mean Completeness Err = 8.76e-03, Comprehensiveness = 0.565 (vs Random 0.085), Sufficiency = -0.001 (vs Random 0.179) và Top-3 Rationale Hit = 83.3%.
Bài tập 5 — Thuật toán Forward log-sum-exp, Giải mã Viterbi & Word Dropout cho BiLSTM-CRF 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh độ phức tạp \(O(TK^2)\) của bước cập nhật \(\alpha_t(j) = P_{t,j} + \operatorname{logsumexp}_i(\alpha_{t-1}(i) + A_{i,j})\) và chỉ ra cách thay logsumexp bằng max dẫn về giải mã Viterbi; phân tích vai trò của word dropout <UNK> khi tên ứng viên tập test hoàn toàn mới.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy LinearChainCRF (forward_log_partition, bruteforce_log_partition, viterbi_decode) và train_resume_ner_models trong bilstm_crf_resume_ie.py (Tests 11–13).
Tiêu chí Đáp án & Số đối chứng
Forward khớp duyệt vét cạn tới 3.52e-07; Viterbi đạt 0.00% chuyển tiếp BIO bất hợp lệ dưới cả phát xạ đối kháng lẫn 25% nhiễu OCR (vs 4.51%/90 lỗi sạch và 2.86%/57 lỗi nhiễu của Softmax); BiLSTM-CRF đạt 99.1% sạch / 96.4% nhiễu OCR Span Exact F1.
Bài tập 6 — Hệ thống Resume Document AI Đa cột (XY-Cut, Pydantic v2, Safetensors) & Toàn trình Lab 10 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Trình bày thuật toán chiếu hình chiếu khoảng tọa độ \(x\) tìm khe cột dọc (vertical gutter) của Recursive XY-Cut và đối chiếu với thất bại trộn dòng của Naive Y-Sort; thiết kế phân luồng XY-Cut + BiLSTM-CRF + GLiNER/Docling fallback.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy evaluate_layout_reading_order, parse_resume_layout_to_profile, save_bilstm_crf_safetensors (Tests 14–16), cùng trọn bộ ruff, mypy, pytest (16/16) và scripts/run_lab_demo.py.
Tiêu chí Đáp án & Số đối chứng
Recursive XY-Cut khôi phục 100.0% thứ tự đọc trên 24 CV 2 cột (vs 0.0% của Naive Y-Sort, Pairwise 100% vs 71.4%); ResumeProfile (Pydantic v2, extra="forbid") ẩn danh [REDACTED_PERSON]; safetensors (87,708 B, diff = 0.0, 1.63 ms/CV) không pickle và 16/16 pytest đạt xanh.