Chương 11 — k-NN, Độ đo Khoảng cách Chính xác, Truy xuất Vector SOTA (HNSW, IVF-PQ, ScaNN, DiskANN) & Hệ thống Gợi ý Đa tầng E-Commerce (Lab 05)
Từ Lời nguyền Chiều Beyer (51.52 -> 0.172), Cover–Hart, Mahalanobis (53.1% -> 86.5%) & Sụp đổ KD-Tree (21.1% -> 100%) đến IVF-PQ ADC (16x RAM, 0.969 R@10), HNSW (100% R@10), ScaNN (-60% MSE), Filtered Iterative Scan (7.6% -> 100%) & Phễu RecSys 3 Tầng (+32.1% LOO Leak Audit).
Unit ID:
T1-P2-U06
Track & Part: Track 1 (DSAI) — Part 2: Classical & Tabular ML, Evaluation Rigor, Forecasting & Domains (part-02-classical-ml-tabular-and-domains)
Truy xuất Giáo trình Gốc (R35,E32:E35): Lesson 10 (kNN & ANN — 1 buổi, phủ trọn vẹn 100% cả 5 mục: Distance metrics: euclidean, manhattan, cosine similarity, kNN algorithm, Neighborhood size (k) & Elbow Plots methods, ANN motivation and algorithms, Industrial tips) + Nhánh miền Thương mại Điện tử (E32:E35— Personalization: Recommender Systems Across the User Journey) (Ranh giới không chồng lấn: tối ưu tuyến tính/logistic kế thừa từch-06; hiệu chuẩn Platt & phân loại rò rỉ kế thừa từch-07; thang đo & chuẩn hóa nội nếp kế thừa từch-08; máy vector hỗ trợ & bẫy tỷ lệ RBF thuộcch-09; cây quyết địnhGBDT&HPOthuộcch-10; nội tạipgvectorACID/MVCC liên thông vớiTrack 2 Ch 03)
Bài thực hành Miền Song hành (Lab 05):labs/lab-05-ecommerce-multi-stage-recsys/(recsys_ann_lab)
Tình huống Mở đầu: Bốn Thảm họa Sản xuất Khi Đưa k-NN, Vector Search & RecSys Ra Thực địa#
Thuật toán \(k\) láng giềng gần nhất (\(k\)-NN) thường bị xem nhẹ như một mô hình "đơn giản cho người mới học". Trong thực tế năm 2026, truy xuất vector gần đúng (Approximate Nearest Neighbor — ANN) chính là xương sống vận hành của mọi hệ thống RAG (Retrieval-Augmented Generation), tìm kiếm đa phương thức và phễu đề xuất thương mại điện tử hàng trăm triệu SKU. Thế nhưng, đưa trực tiếp \(k\)-NN và tìm kiếm vector từ sách giáo khoa lên hệ thống thực tế thường kích hoạt bốn sự cố thảm khốc:
- Bẫy Tỷ lệ Vô hình & Sụp đổ Tập trung Chiều cao (
Beyer 1999/KD-Tree 100% Scan): Trên bảng đặc trưng E-Commerce trộn đơn giá biến thiên lớn (sigma ~ 2500) với các tỷ lệ hành vi tương quan (rho = 0.88), khoảng cách EuclidL2không chuẩn hóa bị cột tiền tệ nuốt chửng hoàn toàn khiến độ chính xác kiểm tra tụt xuống53.1%, trước khi đượcStandardScalernội nếp nâng lên82.7%và khoảng cách Mahalanobis làm trắng \(\boldsymbol{\Sigma}^{-1}\) giải cứu lên86.5%. Đáng sợ hơn, khi đẩy lên không gian embeddingd = 512đẳng hướng, thể tích vỏ siêu cầu ngoài5%nuốt100.00%không gian (\(1 - 0.95^{512}\)), tỷ lệ tương phản \((D_{\max}-D_{\min})/D_{\min}\) sụp đổ từ51.520xuống0.172, vàKD-Treethoái hóa từ quét21.1%nút (d=4) thành quét100.0%toàn bộ tập dữ liệu (d=64) — chậm hơn cả quét tuần tự BLAS! - Nổ Bộ nhớ
HNSW fp32ở Quy mô Hàng tỷ Vector & Thất bại Lượng tử hóaMIPS: Lưu500Membedding768Dtrong đồ thịHNSW(4d + 8Mbyte/vector) ngốn hơn1.6 TBDRAM. Nén sangIVF-PQ(16 B/vectorởd=64) tiết kiệm16x–64xRAM và đạt0.969 Recall@10sau khi tái chấm điểm top-30, nhưng hàm mất mátL2đẳng hướng truyền thống vẫn làm sai lệch thứ hạng tích vô hướng cực đại (MIPS) cho tới khiScaNNlượng tử hóa bất đẳng hướng (\(h_\parallel = 6.0, h_\perp = 1.0\)) cắt giảm-60.0%sai sốtop-20 MIPS MSE(0.284 -> 0.114) và nângRecall@10(0.513 -> 0.543). - Sụp đổ Đói Ứng viên Khi Lọc SQL Có Điều kiện (
selectivity = 2%): Truy vấn vector kết hợp lọcWHERE brand='X' AND in_stock=1 LIMIT 10với độ chọn lọc \(s = 2\%\): lọc hậu kỳ (Post-Filter) trênHNSW(efSearch = 32) chỉ còn kỳ vọng \(0.02 \times 32 = 0.64\) dòng hợp lệ, khiến hệ thống chỉ trả về trung bình0.8/10sản phẩm (Recall@10 = 7.6%); trong khi lọc tiền kỳ cứng trên cạnh đồ thị làm đứt gãy cầu nối thành đảo cô lập (5.6% Recall@10). Chỉ cơ chế duyệt mở rộng bắc cầu (pgvector 0.8+ hnsw.iterative_scanhoặcACORN) mới khôi phục trọn vẹn100.0% Recall@10. - Ảo giác Rò rỉ
Leave-One-Out (+32.1%), Sụp đổ Phổ biến & Danh sách Trùng lặp (Lab 05): Tách tập theo từng người dùng kiểu Leave-One-Out (LOO) cho phép cạnh đồng truy cập từ phiên mua sắm tương lai của người khác (max_train_ts = 1478 > min_test_ts = 305) rò vào tập huấn luyện, thổi phồng giảRecall@40thêm+32.1%(0.090 -> 0.411) so với tách thời gian toàn cục (Global Temporal Split). Đồng thời, truy xuất Two-Tower thô bị thiên lệch phổ biến MNAR chỉ đạt50.4% Recall@200(11.4%độ phủ danh mục) và xếp hạng thiếu đa dạng. Phễu 3 tầng chuẩn củaLab 05(IPS + Co-VisitationHNSW->PIT Ranker+Platt->MMR Re-ranking) nângRecall@200lên73.1%,NDCG@100.119 -> 0.169, hạECE0.147 -> 0.051, tăng độ đa dạngILD0.551 -> 0.632và nâng biên lợi nhuận kỳ vọng$22.18 -> $25.44.
Mục tiêu Học tập (Learning Objectives)#
Sau khi hoàn thành Chương 11 và bài thực hành miền Thương mại Điện tử Lab 05 (recsys_ann_lab), học viên có năng lực:
- Chứng minh Hình học Độ đo Khoảng cách, Cover–Hart (
1967) & BẫyElbow k=1(R35.1–R35.3): Phân biệt chuẩn xác bốn tiên đề metric; chứng minh đẳng thức tương đương tuyệt đối giữa Cosine và Euclidean bình phương trên mặt cầu đơn vị \(\mathbb{S}^{d-1}\), biến đổi giảm trừ \(\text{MIPS} \to L_2\) (Neyshabur–Srebro), và làm trắng tương quan bằng khoảng cách Mahalanobis \(\boldsymbol{\Sigma}^{-1}\); chứng minh cận tiệm cận Cover–Hart (1967) \(R^* \le R_{1\text{-NN}} \le 2R^*(1-R^*)\) bằng bất đẳng thức Jensen, điều kiện nhất quán Stone (1977), và phân rã Bias–Variance theo \(k\) qua OOF CV thay vì bẫy lỗi nội mẫuk=1. - Giải tích Lời nguyền Số chiều (
Beyer 1999) & Sụp đổKD-Tree/Ball-Tree(R35.1,R35.4): Dẫn xuất công thức tập trung thể tích vỏ \(1 - (1-\epsilon)^d\), khoảng cách góc siêu lập phương \(\sqrt{d}\), và định lý Beyer et al. (ICDT 1999) chứng minh \(\operatorname{Std}(D_2)/\mathbb{E}[D_2] = \mathcal{O}(d^{-1/2}) \to 0\) trên phân phối đẳng hướng; giải thích ngoại lệ đa tạp nội tại chiều thấp (\(d_{\text{int}} \ll d\)) và chứng minh lý doKD-Treesụp đổ về quét100%không gian tại \(d \ge 20\text{–}64\). - Thiết kế & Tính toán Ngân sách Hệ thống Vector SOTA (
LSH,IVF-PQ/ADC,HNSW,ScaNN,DiskANN, FilteredANN): Nắm vững bộ ba đánh đổi Recall–Latency–RAM; triển khai từ gốc bảng tra cứuADC LUTcủaIVF-PQ(Jégou et al., TPAMI 2011), đồ thị nhảy bước đa tầngHNSW(Malkov & Yashunin, TPAMI 2020) với công thức bộ nhớ4d + 8Mvà đường biên Pareto(M, efConstruction, efSearch), tối ưu bất đẳng hướngScaNNcho \(\text{MIPS}\) (Guo et al., ICML 2020), kiến trúc SSDDiskANN(Vamana) cho quy mô1Bvector (Subramanya et al., NeurIPS 2019), và xử lý truy vấn lọc chọn lọc thấp bằngACORN(SIGMOD 2024) /pgvector 0.8+ hnsw.iterative_scan. - Kiến trúc Phễu Gợi ý Đa tầng E-Commerce Chống Rò rỉ (
E32:E35,Lab 05): Thay thế Leave-One-Out bằng Global Temporal Split và đặc trưng nhân quả Point-in-Time (t < t_q); kết hợp Two-TowerHNSW+ Khử thiên lệchIPS+ Co-visitation ở Tầng 1 (Recall@200), Ranker + Hiệu chuẩnPlatttrênD_calở Tầng 2 (NDCG@10,ECE), và Tái xếp hạngMMRở Tầng 3 cân bằng liên quan, đa dạngILD, độ phủ danh mục và biên lợi nhuận gộp.
Bảng Truy xuất Giáo trình Gốc sang Chuẩn SOTA 2026 (Unit T1-P2-U06, R35 & E32:E35)#
Nội dung Gốc (01-track-dsai-raw-curriculum.md, R35 & E32:E35) |
Nâng cấp Chuẩn SOTA 2026 (ch-11) |
Mục trong Chương 11 | Mô-đun & Hợp đồng Kiểm thử (recsys_ann_lab) |
|---|---|---|---|
R35.1 Distance Metrics (euclidean, manhattan, cosine) |
4 tiên đề metric, Minkowski \(L_p\), tương đương Cosine-\(L_2\) trên \(\mathbb{S}^{d-1}\), biến đổi \(\text{MIPS}\), và Mahalanobis \(\boldsymbol{\Sigma}^{-1}\) giải cứu bẫy tỷ lệ (53.1% -> 86.5%) |
Trụ cột 1 (§1.1–§1.3) + Widget curse-of-dim-metrics-explorer |
distance_and_ann.py (ExactKNNClassifier, benchmark_scale_trap_mahalanobis), Tests 2, 15 |
| R35.2–3 kNN Algorithm, Size (\(k\)) & Elbow Plots | Chứng minh Cover–Hart (1967) \(R^* \le R_{1\text{-NN}} \le 2R^*(1-R^*)\), nhất quán Stone (1977), Bias–Variance vs \(k\), bẫy k=1 nội mẫu (0.000 -> 0.298) vs OOF CV (k=9, 0.254) |
Trụ cột 1 (§1.4–§1.5) + Widget curse-of-dim-metrics-explorer |
distance_and_ann.py (select_k_via_cv), Test 2 |
| R35.1/4 Curse of Dimensionality & Spatial Trees | Tập trung vỏ \(1-(1-\epsilon)^d\), góc \(\sqrt{d}\), định lý Beyer (1999), ngoại lệ đa tạp 8D (17.472 vs 0.172), và sụp đổ KD-Tree / Ball-Tree (21.1% -> 100.0%) |
Trụ cột 1 (§1.6–§1.7) + Mermaid 1 + Widget 1 | distance_and_ann.py (analyze_curse_of_dimensionality, KDTreeIndex, benchmark_kdtree_collapse), Tests 1, 3 |
| R35.4 ANN Motivation & SOTA Vector Retrieval | Tam đề ANN, LSH/SimHash, IVF-Flat, IVF-PQ + ADC LUT (16x RAM, 0.969 R@10), HNSW (4d+8M, Pareto efSearch), ScaNN bất đẳng hướng (-60% MSE), DiskANN Vamana SSD, RaBitQ, và lọc ACORN / pgvector 0.8+ (7.6% -> 100.0%) |
Trụ cột 2 (§2.1–§2.5) + Mermaid 1, 2, 3 + Widget hnsw-ivfpq-pareto-simulator |
distance_and_ann.py (HNSWIndex, IVFPQIndex, scann_anisotropic_mips_demo, verify_filtered_search_selectivity), Tests 4, 5, 6, 7 |
R35.5 Industrial Tips & E32:E35 E-Commerce RecSys (Lab 05) |
Global Temporal Split vs rò rỉ LOO (+32.1%), Stage 1 Two-Tower HNSW + IPS + Co-vis (R@200 73.1%), Stage 2 PIT (t < t_q) + Platt (NDCG 0.169, ECE 0.051), Stage 3 MMR (ILD 0.632, $25.44), 4 Case & 8 Phản mẫu |
Trụ cột 2 (§2.6) + Trụ cột 3 + Trụ cột 4 + Widget multistage-recsys-mmr-arena |
multistage_recsys.py (generate_ecommerce_sessions, audit_temporal_vs_loo_leakage, MultiSourceRetriever, PointInTimeRanker, mmr_rerank, run_full_ch11_lab05_benchmarks), Tests 8–14, 16 |
Bảng Ký hiệu Toán học Thống nhất (Unified Disambiguated Notation)#
| Ký hiệu (LaTeX) | Miền / Kiểu | Định nghĩa Chuẩn hóa (ch-11) |
Quy ước Phân biệt Bắt buộc | Ký hiệu Mã nguồn (recsys_ann_lab) |
|---|---|---|---|---|
| \(n, d\) | \(\mathbb{N}_+\) | Số vector dữ liệu \(n\) và số chiều môi trường \(d\) (\(\mathbf{x}_i \in \mathbb{R}^d\)) | Phân biệt với chiều không gian con PQ \(d^* = d / M_{\text{pq}}\) và chiều nội tại đa tạp \(d_{\text{int}}\) | n_samples, dim |
| \(k\) | \(\mathbb{N}_+\) | Số láng giềng trong \(k\)-NN và ngưỡng cắt top-\(k\) (Recall@k, NDCG@k) |
Tách khỏi số tâm cụm PQ \(K^*\) và số nếp kiểm chứng \(K_{\text{cv}}\) | k, top_k |
| \(D_p, D_{\cos}, D_M\) | \(\mathbb{R}_{\ge 0}\) | Khoảng cách Minkowski \(L_p\), Cosine \(1 - \operatorname{sim}_{\cos}\), và Mahalanobis \(\sqrt{\Delta\mathbf{x}^\top\boldsymbol{\Sigma}^{-1}\Delta\mathbf{x}}\) | Phân biệt hàm khoảng cách \(D(\cdot, \cdot)\) với điểm tích vô hướng \(\text{MIPS}\) \(\langle \mathbf{q}, \mathbf{x} \rangle\) | metric |
| \(R^*, R_{1\text{-NN}}\) | \([0, 1]\) | Rủi ro Bayes tối ưu \(R^*\) và lỗi tiệm cận 1-NN (\(R^* \le R_{1\text{-NN}} \le 2R^*(1-R^*)\)) |
Áp dụng tại giới hạn \(n \to \infty\) | bayes_risk_est, cover_hart_upper_bound |
| \(V_{\text{shell}}(\epsilon), \gamma_{\text{cd}}\) | \([0, 1], \mathbb{R}_{\ge 0}\) | Tỷ lệ thể tích vỏ ngoài \(1 - (1-\epsilon)^d\) và tương phản Beyer \(\frac{D_{\max} - D_{\min}}{D_{\min}}\) | Tách khỏi \(\gamma_{\text{rbf}}\) (ch-09) |
shell_volume_frac, iso_contrast_ratio |
| \(M, \text{ef}_c, \text{ef}_s\) | \(\mathbb{N}_+\) | Bậc tối đa tầng trên HNSW \(M\) (\(M_{\max, 0} = 2M\)), efConstruction, efSearch |
Phân biệt bậc đồ thị \(M\) với số không gian con PQ \(M_{\text{pq}}\) | m_links, ef_construction, ef_search |
| \(C_{\text{vor}}, \text{nprobe}\) | \(\mathbb{N}_+\) | Số ô Voronoi thô trong IVF và số ô được thăm dò khi truy vấn |
Tách khỏi phạt \(C\) của SVM (ch-09) |
n_lists, nprobe |
| \(M_{\text{pq}}, K^*, d^*\) | \(\mathbb{N}_+\) | Số phân đoạn PQ \(M_{\text{pq}}\), số tâm mỗi phân đoạn \(K^*\) (<= 256), chiều con \(d^* = d/M_{\text{pq}}\) |
Mỗi vector chiếm \(M_{\text{pq}}\) byte mã uint8 khi \(K^* \le 256\) |
m_subspaces, n_centroids, sub_dim |
| \(h_\parallel, h_\perp\) | \(\mathbb{R}_{>0}\) | Trọng số phạt sai số song song và trực giao trong ScaNN (\(h_\parallel \gg h_\perp\)) |
Song song theo hướng \(\hat{\mathbf{x}}_i\) | h_parallel, h_orthogonal |
| \(s\) | \((0, 1]\) | Độ chọn lọc bộ lọc metadata (tỷ lệ bản ghi thỏa WHERE) |
Số ứng viên sống sót kỳ vọng sau post-filter là \(s \cdot \text{ef}_s\) | selectivity |
| \(t_{\text{cut}}, t_q\) | \(\mathbb{R}\) | Mốc thời gian cắt toàn cục và dấu thời gian truy vấn hiện tại | Bắt buộc \(\max t_{\text{train}} < \min t_{\text{cal}} < \min t_{\text{test}}\); PIT chỉ đọc \(t < t_q\) | event_ts, query_ts |
| \(\alpha_{\text{ips}}, \lambda_{\text{mmr}}\) | \([0, 1]\) | Số mũ khử phổ biến IPS (\(p_i^{-\alpha_{\text{ips}}}\)) và hệ số liên quan MMR |
Không nhầm lẫn \(\lambda_{\text{mmr}}\) với phạt Ridge \(\lambda_{\text{reg}}\) | ips_alpha, mmr_lambda |
Trụ cột 1 — Nền tảng Toán học: Độ đo Khoảng cách, Định lý Cover–Hart, Lời nguyền Số chiều & Sụp đổ Cây Không gian#
1.1 Tiên đề Không gian Metric & Gia đình Khoảng cách Minkowski (\(L_p\)) (R35.1)#
Một hàm \(D: \mathcal{X} \times \mathcal{X} \to \mathbb{R}_{\ge 0}\) là một khoảng cách chuẩn (metric) khi và chỉ khi thỏa mãn đồng thời bốn tiên đề với mọi \(\mathbf{x}, \mathbf{y}, \mathbf{z} \in \mathcal{X}\): (1) không âm \(D(\mathbf{x},\mathbf{y}) \ge 0\), (2) định danh phân biệt \(D(\mathbf{x},\mathbf{y}) = 0 \iff \mathbf{x}=\mathbf{y}\), (3) đối xứng \(D(\mathbf{x},\mathbf{y}) = D(\mathbf{y},\mathbf{x})\), và (4) bất đẳng thức tam giác \(D(\mathbf{x},\mathbf{z}) \le D(\mathbf{x},\mathbf{y}) + D(\mathbf{y},\mathbf{z})\) — nền tảng toán học cho phép mọi cây phân hoạch không gian (Ball-Tree, M-Tree) cắt tỉa nhánh mà không bỏ sót nghiệm đúng.
Với \(p \ge 1\), khoảng cách Minkowski (\(L_p\)) giữa hai vector \(\mathbf{x}, \mathbf{y} \in \mathbb{R}^d\) là:
- Euclidean (\(L_2\), \(p=2\)): \(D_2(\mathbf{x},\mathbf{y}) = \sqrt{\sum_{j=1}^d (x_j - y_j)^2}\). Bất biến dưới mọi phép quay trực giao \(\mathbf{Q} \in O(d)\) (\(\|\mathbf{Q}\mathbf{x}\|_2 = \|\mathbf{x}\|_2\)), khả vi ngoài \(\mathbf{x}=\mathbf{y}\), nhưng bình phương độ lệch khiến \(L_2\) cực kỳ nhạy với ngoại lai đơn chiều và chênh lệch thang đo giữa các cột.
- Manhattan (\(L_1\), \(p=1\)): \(D_1(\mathbf{x},\mathbf{y}) = \sum_{j=1}^d |x_j - y_j|\). Không bất biến phép quay (bám trục tọa độ), kháng ngoại lai đơn chiều tốt hơn \(L_2\), và giữ tương phản tốt hơn \(L_2\) ở chiều trung bình–cao (Aggarwal et al., ICDT 2001). (Trong
Lab 05, trên dữ liệu nhiễu tỷ lệ chuẩn hóa,L1đạt81.2%so vớiL2 thô 53.1%.) - Chebyshev (\(L_\infty\), \(p \to \infty\)): \(D_\infty(\mathbf{x}, \mathbf{y}) = \max_{1 \le j \le d} |x_j - y_j|\). (Lưu ý: với \(p \in (0, 1)\), \(D_p\) vi phạm bất đẳng thức tam giác nên phá hỏng cơ chế cắt tỉa nhánh của cây metric.)
1.2 Tương đồng Cosine, Khoảng cách Cosine, Đẳng thức Mặt cầu Đơn vị & \(\text{MIPS}\) (R35.1)#
Với \(\mathbf{x}, \mathbf{y} \in \mathbb{R}^d \setminus \{\mathbf{0}\}\), độ tương đồng Cosine và khoảng cách Cosine lần lượt là:
trong đó \(\hat{\mathbf{x}} := \mathbf{x}/\|\mathbf{x}\|_2 \in \mathbb{S}^{d-1}\).
- Đẳng thức Mặt cầu Đơn vị: Khi cả tập dữ liệu và truy vấn đã được chuẩn hóa \(L_2\) (\(\|\hat{\mathbf{x}}\|_2 = \|\hat{\mathbf{y}}\|_2 = 1\)):
\[\|\hat{\mathbf{x}} - \hat{\mathbf{y}}\|_2^2 = \|\hat{\mathbf{x}}\|_2^2 + \|\hat{\mathbf{y}}\|_2^2 - 2\langle \hat{\mathbf{x}}, \hat{\mathbf{y}} \rangle = 2 - 2\operatorname{sim}_{\cos}(\mathbf{x}, \mathbf{y}) = 2\, D_{\cos}(\mathbf{x}, \mathbf{y}).\]Hệ quả: xếp hạng láng giềng theo Cosine Similarity, Cosine Distance, Euclidean \(L_2\) chuẩn hóa, và Tích vô hướng Cực đại (\(\text{MIPS}\)) trên vector đơn vị cho kết quả đồng nhất 100% (được kiểm chứng tuyệt đối trong
Test 2củaLab 05). - Cảnh báo Tiên đề Metric: Trên vector chưa chuẩn hóa, \(D_{\cos}\) KHÔNG phải là một metric: nó vi phạm cả định danh (\(D_{\cos}(\mathbf{x}, 2\mathbf{x}) = 0\)) lẫn bất đẳng thức tam giác (với \(\mathbf{x}=(1,0), \mathbf{y}=(1,1), \mathbf{z}=(0,1)\): \(D_{\cos}(\mathbf{x},\mathbf{z}) = 1 > (1 - 1/\sqrt{2}) + (1 - 1/\sqrt{2}) \approx 0.586\)). Chỉ khoảng cách góc chuẩn hóa \(\frac{1}{\pi}\arccos(\operatorname{sim}_{\cos}(\mathbf{x}, \mathbf{y}))\) mới là metric thực thụ trên \(\mathbb{S}^{d-1}\).
- \(\text{MIPS}\) trên Embedding Không chuẩn hóa: Khi chuẩn \(\|\mathbf{x}_i\|_2\) mang thông tin độ mạnh/chất lượng (như trong mạng Two-Tower không chuẩn hóa), \(\arg\max_i \langle \mathbf{q}, \mathbf{x}_i \rangle\) khác hoàn toàn \(\arg\min_i \|\mathbf{q} - \mathbf{x}_i\|_2^2\). Có thể quy giản chính xác về \(L_2\) trong \(\mathbb{R}^{d+1}\) bằng phép nhúng Neyshabur & Srebro (2015) với chặn trên \(U \ge \max_i \|\mathbf{x}_i\|_2\): đặt \(\tilde{\mathbf{x}}_i = [\mathbf{x}_i;\, \sqrt{U^2 - \|\mathbf{x}_i\|_2^2}]\) và \(\tilde{\mathbf{q}} = [\mathbf{q};\, 0]\) để thu được \(\|\tilde{\mathbf{q}} - \tilde{\mathbf{x}}_i\|_2^2 = \|\mathbf{q}\|_2^2 + U^2 - 2\langle \mathbf{q}, \mathbf{x}_i \rangle\).
1.3 Khoảng cách Mahalanobis & Giải cứu Bẫy Tỷ lệ Hỗn hợp#
Khi dữ liệu bảng có các đặc trưng mang đơn vị khác nhau và tương quan mạnh hình elip (hiệp phương sai \(\boldsymbol{\Sigma} \succ \mathbf{0}\)), khoảng cách Mahalanobis biến đổi không gian về hệ tọa độ làm trắng trực chuẩn \(\mathbf{z} = \mathbf{L}\mathbf{x}\) (\(\mathbf{L}^\top\mathbf{L} = \boldsymbol{\Sigma}^{-1}\)):
- Quy trình Co cụm Chống Suy biến & Bẫy Đơn vị: Để tránh suy biến ma trận \(\hat{\boldsymbol{\Sigma}}^{-1}\) khi \(n \lesssim d\) và giữ bất biến đơn vị tuyệt đối,
ExactKNNClassifierchuẩn hóa từng cột bằng \(\hat{\boldsymbol{\mu}}, \hat{\boldsymbol{\sigma}}\) nội bộ tậpD_train/ nếp CV, tính ma trận tương quan \(\mathbf{R}\), co cụm lồi \(\mathbf{R}_s = (1 - \alpha)\mathbf{R} + \alpha \mathbf{I}_d\), rồi phân rã phổ lấy \(\mathbf{R}_s^{-1/2}\). Trên tập kiểm thử E-Commerce trộn đơn giá (sigma ~ 2500) với cụm hành vi tương quanrho = 0.88,L2thô chỉ đạt53.1%, chuẩn hóaL2nâng lên82.7%, và Mahalanobis đạt86.5%.
1.4 Thuật toán k-NN, Định lý Cover–Hart (1967) & Tính Nhất quán Stone (1977) (R35.2)#
Cho tập huấn luyện \(\mathcal{D} = \{(\mathbf{x}_i, y_i)\}_{i=1}^n\) và điểm truy vấn \(\mathbf{q}\), ký hiệu \(\mathcal{N}_k(\mathbf{q})\) là \(k\) chỉ số có khoảng cách \(D(\mathbf{q}, \mathbf{x}_i)\) nhỏ nhất. Dự báo được tính theo bỏ phiếu đồng đều \(\hat{p}(y=c\mid\mathbf{q}) = \frac{1}{k}\sum_{i\in\mathcal{N}_k(\mathbf{q})}\mathbb{I}(y_i=c)\) hoặc gán trọng số nghịch đảo khoảng cách \(w_i(\mathbf{q}) = \frac{1}{D(\mathbf{q},\mathbf{x}_i)+\varepsilon}\) để khử hòa phiếu ở biên. Là bộ học lười (lazy learner), chi phí "huấn luyện" vét cạn là \(\mathcal{O}(1)\) còn chi phí truy vấn 1 mẫu là \(\mathcal{O}(nd + n)\) (dùng argpartition chọn phần tử thứ \(k\) thay vì sắp xếp \(\mathcal{O}(n\log n)\)).
Định lý 1.1 (Cận Rủi ro Tiệm cận 1-NN của Cover & Hart, IEEE Trans. Info. Theory 1967)#
Trong bài toán phân loại nhị phân có xác suất hậu nghiệm đúng \(\eta(\mathbf{x}) := \mathbb{P}(Y = 1 \mid \mathbf{X} = \mathbf{x})\) và rủi ro Bayes tối ưu \(R^* := \mathbb{E}[\min(\eta(\mathbf{X}), 1 - \eta(\mathbf{X}))]\), khi số mẫu \(n \to \infty\), láng giềng gần nhất \(\mathbf{x}_{(1)}(\mathbf{q})\) hội tụ theo xác suất về \(\mathbf{q}\). Vì nhãn \(Y\) tại \(\mathbf{q}\) và nhãn \(Y_{(1)}\) của láng giềng độc lập có điều kiện với cùng xác suất \(\eta(\mathbf{q})\), xác suất lỗi 1-NN tại \(\mathbf{q}\) bằng:
với \(r^*(\mathbf{q}) := \min(\eta(\mathbf{q}), 1 - \eta(\mathbf{q}))\). Vì hàm \(g(r) = 2r(1-r)\) lõm trên \([0, \tfrac{1}{2}]\), lấy kỳ vọng theo \(\mathbf{X}\) và áp dụng Bất đẳng thức Jensen (\(\mathbb{E}[g(r^*)] \le g(\mathbb{E}[r^*])\)) thu được cận chặt nổi tiếng:
(Tổng quát cho \(C\) lớp: \(R^* \le R_{1\text{-NN}} \le R^*\big(2 - \frac{C}{C-1}R^*\big)\).) Để \(k\)-NN đạt tính nhất quán phổ quát Bayes (\(R_{k\text{-NN}} \to R^*\)) với mọi phân phối, Định lý Stone (1977) chứng minh điều kiện cần và đủ là \(k_n \to \infty\) đồng thời \(\frac{k_n}{n} \to 0\) khi \(n \to \infty\). (Trong Lab 05, tại rủi ro Bayes \(R^* = 0.232\), cận Cover–Hart bằng \(0.356\) và lỗi CV thực đo của 1-NN là \(0.298 \le 0.356\).)
1.5 Đánh đổi Bias–Variance theo \(k\) & Bẫy Dùng Lỗi Huấn luyện Vẽ Elbow Plot (R35.3)#
Dưới mô hình nhiễu cộng \(y = f(\mathbf{x}) + \varepsilon\) (\(\mathbb{E}[\varepsilon]=0, \operatorname{Var}(\varepsilon)=\sigma_\varepsilon^2\)), sai số bình phương trung bình tại \(\mathbf{q}\) phân rã thành:
- \(k = 1\) (Bẫy Khớp Quá mức): Mỗi điểm chính là láng giềng gần nhất của bản thân nó trong tập train, khiến sai số nội mẫu luôn bằng
0.000! Kẻ mới vào nghề vẽ đường khuỷu tay trên tập huấn luyện sẽ luôn chọn nhầm \(k=1\) (phương sai \(\sigma_\varepsilon^2\) tối đa, lỗiCV = 0.298). - Chọn \(k\) Chuẩn bằng
OOF CV& Chọn số lẻ: ChạyK-Fold CVvới chuẩn hóa nằm chặt trong từng nếp giúp tìm đúng đáy khuỷu tay (k = 9vớiCV Err = 0.254trongLab 05), ưu tiên \(k\) lẻ cho bài toán nhị phân để loại bỏ hòa phiếu.
1.6 Lời nguyền Số chiều (Curse of Dimensionality) — Chứng minh Chính xác (R35.1, R35.4)#
Khi số chiều \(d\) tăng lên, trực giác hình học 3D sụp đổ hoàn toàn theo ba hiện tượng lượng hóa được:
- Tập trung Thể tích trong Vỏ Mỏng Siêu cầu: Thể tích hình cầu \(d\) chiều bán kính \(R\) là \(V_d(R) = \frac{\pi^{d/2}}{\Gamma(d/2+1)}R^d\). Tỷ lệ thể tích nằm trong lớp vỏ ngoài độ dày tương đối \(\epsilon \in (0, 1)\) là:
\[\frac{V_d(R) - V_d((1-\epsilon)R)}{V_d(R)} = 1 - (1 - \epsilon)^d \xrightarrow{d \to \infty} 1.\]Ở độ dày chỉ \(\epsilon = 5\%\):
d=2chiếm9.75%,d=8chiếm33.66%,d=32chiếm80.63%,d=128chiếm99.86%, vàd=512chiếm100.00%(0.999999999996). Hầu như mọi điểm đều dạt sát ra biên! - Nghịch lý Góc Siêu lập phương & Mở rộng Ô Địa phương: Tâm hình cầu đơn vị nội tiếp trong \([-1, 1]^d\) có bán kính \(1\), nhưng \(2^d\) đỉnh góc nằm ở khoảng cách \(\sqrt{d}\) (
22.63tạid=512). Để bao phủ chỉ1%thể tích siêu lập phương \([0,1]^d\), cạnh hộp cục bộ phải dài \(\ell = 0.01^{1/d}\) — ởd=100, \(\ell = 0.955\) (chiếm95.5%mỗi trục, đánh mất hoàn toàn tính cục bộ!). -
Định lý Tập trung Khoảng cách (Beyer, Goldstein, Ramakrishnan, & Shaft, ICDT 1999): Nếu \(\lim_{d\to\infty}\operatorname{Var}\!\left(\frac{\|\mathbf{X}^{(d)} - \mathbf{Q}^{(d)}\|_p^p}{\mathbb{E}[\|\mathbf{X}^{(d)} - \mathbf{Q}^{(d)}\|_p^p]}\right) = 0\), thì khoảng cách tới điểm gần nhất \(D_{\min}^{(d)}\) và xa nhất \(D_{\max}^{(d)}\) hội tụ về cùng một giá trị:
\[\frac{D_{\max}^{(d)} - D_{\min}^{(d)}}{D_{\min}^{(d)}} \xrightarrow{p} 0, \qquad \frac{D_{\min}^{(d)}}{D_{\max}^{(d)}} \xrightarrow{p} 1.\]Chứng minh nhanh cho \(\mathbf{X}, \mathbf{Q} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_d)\): Đặt \(Z_j = (X_j - Q_j)^2\), ta có \(\mathbb{E}[\|\mathbf{X}-\mathbf{Q}\|_2^2] = d\mu_Z\) và \(\operatorname{Std}(\|\mathbf{X}-\mathbf{Q}\|_2^2) = \sqrt{d}\sigma_Z\). Áp dụng phương pháp Delta với \(g(u)=\sqrt{u}\) (\(g'(u)=\frac{1}{2\sqrt{u}}\)), kỳ vọng khoảng cách tăng như \(\sqrt{d\mu_Z}\) trong khi độ lệch chuẩn giữ hằng số \(\mathcal{O}(1)\), nên độ phân tán tương đối \(\frac{\operatorname{Std}(D_2)}{\mathbb{E}[D_2]} = \mathcal{O}(d^{-1/2}) \to 0\)! Thực nghiệm
Lab 05ghi nhận tương phản đẳng hướng rơi từ51.520(d=2) xuống0.172(d=512) (\(D_{\min}/D_{\max}\) nhảy0.024 -> 0.854).- Vì sao Tìm kiếm Vector Sâu vẫn hoạt động ở
d = 768–1536? Định lý Beyer giả định các chiều phân tán độc lập đẳng hướng. Embedding thực tế nằm trên đa tạp phân cụm chiều nội tại thấp (\(d_{\text{int}} \ll d\)) — kiểm chứng trongLab 05với đa tạp8Dnhúng trực giao vào512Dvẫn bảo toàn độ tương phản17.472(> 100xso với đám mây đẳng hướng!).
- Vì sao Tìm kiếm Vector Sâu vẫn hoạt động ở
1.7 Sụp đổ Cây Phân hoạch Không gian (KD-Tree & Ball-Tree) (R35.4)#
KD-Tree(Bentley, 1975): Chia nhị phân không gian đệ quy theo trung vị trên trục biến thiên lớn nhất, lưu hộp giới hạn AABB tại mỗi nút (O(dn log n)xây dựng,O(n)bộ nhớ). Khi quay lui (backtracking), nhánh anh em chỉ được cắt tỉa nếu khoảng cách tới hộp AABB lớn hơn bán kính láng giềng thứ \(k\) hiện tại \(\tau_k\).- Sụp đổ ở \(d \gtrsim 20\): Ở chiều cao, hình cầu bán kính \(\tau_k\) quanh truy vấn cắt ngang hầu hết \(2^d\) ô siêu hộp lân cận khi \(n \ll 2^d\). Tỷ lệ nút phải duyệt bùng nổ về \(\mathcal{O}(2^d + k\log n)\): trong
Lab 05,KD-Treekhớp100%sklearn, chỉ duyệt21.1%mẫu ởd=4, nhưng bị ép quét100.0%toàn bộ mẫu tạid=64— chậm hơn quét vét cạn nhân ma trận BLAS vì nhảy con trỏ phá cache L1/L2!Ball-Tree(cắt tỉa hình cầu qua bất đẳng thức tam giác \(D(\mathbf{q}, \mathbf{c}_v) - R_v \ge \tau_k\)) chịu đựng tốt hơn trên đa tạp \(d \approx 20\text{–}40\) nhưng vẫn sụp đổ khi \(d_{\text{int}}\) hoặc \(d\) lớn, buộc phải chuyển sang Tìm kiếm Láng giềng Gần đúng (ANN).
Trụ cột 2 — Kiến trúc Hệ thống Truy xuất Vector SOTA (LSH, IVF-PQ, HNSW, ScaNN, DiskANN, Filtered ANN) & Phễu RecSys Đa tầng (Lab 05)#
2.1 Tam đề ANN, Băm Nhạy Địa phương (LSH / SimHash) & IVF-Flat (R35.4)#
Tìm kiếm vector quy mô lớn bị chi phối bởi Tam đề ANN (ANN Trilemma): mọi chỉ mục đều phải đánh đổi giữa Độ phủ (Recall@k), Thông lượng / Độ trễ (QPS / p99), và Dung lượng Bộ nhớ (Bytes/Vector).
LSH&SimHash(Indyk & Motwani, 1998; Charikar, 2002): Chọn họ siêu phẳng ngẫu nhiên \(\mathbf{r} \sim \mathcal{N}(\mathbf{0}, \mathbf{I}_d)\) với hàm băm \(h_{\mathbf{r}}(\mathbf{x}) = \operatorname{sgn}(\langle \mathbf{r}, \mathbf{x} \rangle) \in \{-1, +1\}\). Xác suất va chạm hai vector phụ thuộc chính xác vào góc \(\theta(\mathbf{x},\mathbf{y})\): \(\mathbb{P}[h_{\mathbf{r}}(\mathbf{x})=h_{\mathbf{r}}(\mathbf{y})] = 1 - \frac{\theta(\mathbf{x},\mathbf{y})}{\pi}\). Ghép \(b\) bit mỗi dải và lặp \(L\) bảng (OR-ANDamplification) nâng xác suất trúng lên \(1 - (1 - p^b)^L\), nhưng đòi hỏi \(L = 20\text{–}100\) bảng băm gây phình RAM và rời rạc bộ nhớ đệm — ngày nay chủ yếu dùng để khử trùng lặp văn bản (MinHash/SimHash) thay vì truy xuất embedding dày đặc.IVF-Flat(Inverted File): Phân cụm tập dữ liệu thành \(C_{\text{vor}} \approx 4\sqrt{n}\text{–}16\sqrt{n}\) ô Voronoi bằng K-Means. Khi truy vấn, chỉ thăm dònprobetâm gần nhất (quét \(\approx \frac{\text{nprobe}}{C_{\text{vor}}}\) dữ liệu). Tuy nhiên,IVF-Flatvẫn lưu vector gốc không nén (4dbytefp32), tiêu tốn6.14 GBcho mỗi1Mvector1536D.
2.2 Nén Lượng tử Tích IVF-PQ & Tính Khoảng cách Bất đối xứng ADC (Jégou et al., IEEE TPAMI 2011)#
Để nén hàng tỷ vector vào RAM, Product Quantization (PQ) tách vector phần dư \(\mathbf{r}_i = \mathbf{x}_i - \mathbf{c}_{\text{coarse}(\mathbf{x}_i)} \in \mathbb{R}^d\) thành \(M_{\text{pq}}\) không gian con độc lập có chiều \(d^* = d / M_{\text{pq}}\):
Mỗi không gian con \(m\) huấn luyện từ điển riêng \(\mathcal{C}^{(m)}\) gồm \(K^* \le 256\) tâm cụm, nên mã hóa chỉ tốn đúng 1 byte uint8 mỗi phân đoạn (M_pq byte/vector thay vì 4d byte — tiết kiệm 16x ở d=64, M_pq=16 và 64x ở d=768, M_pq=48), trong khi từ điển tích Đề-các \(\mathcal{C}^{(1)} \times \dots \times \mathcal{C}^{(M_{\text{pq}})}\) biểu diễn tới \(256^{M_{\text{pq}}}\) vùng lượng tử hóa!
Bảng tra cứu Bất đối xứng (ADC LUT) Tốc độ Cao#
Thay vì lượng tử hóa cả truy vấn \(\mathbf{q}\) (Symmetric Distance Computation — SDC), ADC giữ nguyên vector \(\mathbf{q}_{\text{res}}\) để triệt tiêu sai số phía truy vấn:
- Dựng trước một bảng tra cứu \(\operatorname{LUT}\) kích thước \(M_{\text{pq}} \times K^*\) duy nhất cho mỗi truy vấn ô Voronoi:
\[\operatorname{LUT}[m, c] := \left\|\mathbf{q}_{\text{res}}^{(m)} - \mathbf{c}_{m, c}\right\|_2^2 \qquad (m = 1,\dots,M_{\text{pq}};\; c = 0,\dots,K^*-1).\]
- Với mỗi vector ứng viên có mã \(\mathbf{b}_i = (b_{i,1}, \dots, b_{i,M_{\text{pq}}})\), ước lượng bình phương khoảng cách chỉ bằng
M_pqphép tra bảng vàM_pq - 1phép cộng:\[\hat{D}_{\text{ADC}}(\mathbf{q}, \mathbf{x}_i)^2 = \sum_{m=1}^{M_{\text{pq}}} \operatorname{LUT}\big[m, b_{i, m}\big].\] - Tái chấm điểm (
Exact Rescoring): TrênLab 05,IVF-PQthuần (16xnén:256 B -> 16 B) đạt0.631 Recall@10, nhưng chỉ cần tái chấm điểm chính xác top-30ứng viên (rescore_top_m = 30),Recall@10nhảy vọt lên0.969.
2.3 Đồ thị Thế giới Nhỏ Phân tầng HNSW (Malkov & Yashunin, IEEE TPAMI 2020 / arXiv:1603.09320)#
HNSW kết hợp nguyên lý danh sách nhảy bước (skip-list) xác suất với đồ thị láng giềng điều hướng được (Navigable Small World):
- Gán tầng Theo Hàm mũ: Nút \(i\) nhận tầng tối đa \(\ell_i = \lfloor -\ln(\mathcal{U}(0, 1)) \cdot m_L \rfloor\) với \(m_L = \frac{1}{\ln M}\), khiến mật độ nút thưa dần theo cấp số nhân từ tầng đáy
0(\(n\) nút, bậc tối đa \(M_{\max, 0} = 2M\)) lên đỉnh (\(n/M^\ell\) nút, bậc tối đa \(M\)). - Chọn Láng giềng Đa dạng Góc (
Algorithm 4): Khi nối cạnh, một ứng viên \(e\) chỉ được giữ lại nếu \(D(q, e) < D(e, r)\) với mọi láng giềng \(r\) đã chọn — ngăn chặn nút kẹt trong một cụm cô lập bằng cách giữ lại các cầu nối liên cụm dài. - Bộ nhớ & Bộ ba Tham số Pareto: Chi phí RAM mỗi vector
fp32xấp xỉ:\[\text{Bytes/Vec}_{\text{HNSW}} \approx 4d + 8M + \frac{4M}{M - 1} \quad (\text{quy tắc nhanh: } 4d + 8M \text{ byte}).\]Ở \(d = 768, M = 16\), mỗi vector ngốn~3.2 KB(~1.66 KBnếu nénfp16 / halfvec). Truy vấn đi tham lam (ef=1) từ đỉnh xuống tầng1trong \(\mathcal{O}(\log n)\) bước rồi mở rộng chùm tia độ rộngefSearchở tầng0: thay đổiefSearchđiều chỉnh tức thời biên Pareto độ trễ–Recall@10mà không phải xây lại chỉ mục (Lab 05đạt1.000 Recall@10chỉ bằng9.3%–35.8%phép tính khoảng cách!).
2.4 SOTA 2020–2025: ScaNN Bất đẳng hướng, DiskANN Vamana SSD & RaBitQ#
ScaNN— Lượng tử hóa Vector Bất đẳng hướng Cho \(\text{MIPS}\) (Guo et al., ICML 2020 /arXiv:1908.10396): Lượng tử hóa \(L_2\) thông thường coi sai số song song (\(\mathbf{r}_\parallel\)) và trực giao (\(\mathbf{r}_\perp\)) với \(\mathbf{x}_i\) ngang nhau. Guo et al. chứng minh đối với truy vấn \(\text{MIPS}\) có tích vô hướng cao (\(\langle \mathbf{q}, \mathbf{x}_i \rangle \ge T\)), kỳ vọng méo tích vô hướng \(\mathbb{E}[(\langle \mathbf{q}, \mathbf{x}_i - \tilde{\mathbf{x}}_i \rangle)^2 \mid \langle \mathbf{q}, \mathbf{x}_i \rangle \ge T]\) bị chi phối áp đảo bởi sai số song song (\(h_\parallel \gg h_\perp\)):\[\ell_{\text{aniso}}(\mathbf{x}_i, \tilde{\mathbf{x}}_i) = h_\parallel \|\mathbf{r}_\parallel\|_2^2 + h_\perp \|\mathbf{r}_\perp\|_2^2, \qquad \mathbf{r}_\parallel = (\hat{\mathbf{x}}_i^\top (\tilde{\mathbf{x}}_i - \mathbf{x}_i))\hat{\mathbf{x}}_i.\]Cập nhật tâm cụm theo nghiệm đóng \(\big(h_\perp \mathbf{I} + (h_\parallel - h_\perp)\frac{1}{|C|}\sum \hat{\mathbf{x}}_i\hat{\mathbf{x}}_i^\top\big)\mathbf{c}^* = h_\parallel \bar{\mathbf{x}}\) kết hợp bảng traLUT164-bit trên thanh ghiAVX2(vpshufb) giúpLab 05giảm-60.0%sai sốtop-20 MIPS MSE(0.284 -> 0.114) và nângRecall@10(0.513 -> 0.543).DiskANN(VamanaGraph trên NVMe SSD — Subramanya et al., NeurIPS 2019): Thay vì đồ thị nhiều tầng củaHNSW,Vamanaxây đồ thị đơn tầng mật độ cao với cắt tỉa \(\alpha\)-RNG (\(\alpha \approx 1.2\)), chỉ lưu mã nén PQ trong RAM (~32–64 GBcho1 tỷvector) và đóng gói mỗi vector gốc + danh sách kề vào cùng một sector4 KiBtrên NVMe SSD. Truy vấn bất đồng bộ quaio_uringđạt< 5–10 msp95 trên duy nhất 1 máy chủ64 GB RAM!RaBitQ(Gao & Long, SIGMOD 2024): Lượng tử hóa vector chuẩn hóa sang chuỗi1–4 bitqua phép xoay trực giao ngẫu nhiên kèm bộ ước lượng không chệch có cận sai số lý thuyết chặt chẽ, tăng tốcpopcountSIMD hàng chục lần.
2.5 Tìm kiếm Vector Có Lọc SQL (Filtered Vector Search, ACORN & pgvector 0.8+)#
Khi truy vấn kết hợp điều kiện lọc metadata (WHERE category='running' AND in_stock=1 LIMIT k) có độ chọn lọc \(s \in (0, 1]\):
- Thất bại Lọc Hậu kỳ (
Post-Filter Starvation): Truy xuấtefSearchứng viên trước rồi mới lọcWHEREchỉ giữ lại kỳ vọng \(s \cdot \text{efSearch}\) kết quả. Ở \(s = 2\%\) vàefSearch = 32, kỳ vọng chỉ còn0.64kết quả —Lab 05đo thực tế chỉ trả về0.8/10dòng (Recall@10 = 7.6%)! - Thất bại Lọc Tiền kỳ trên Cạnh (
Pre-Filter Graph Disconnect): Cấm bước nhảy qua nút không thỏaWHERElàm đồ thịHNSWđứt vỡ thành các đảo cô lập khi \(s < 5\%\) (Recall@10 = 5.6%trongLab 05). - Giải pháp SOTA (
pgvector 0.8+ iterative_scan&ACORNSIGMOD 2024): Cho phép thuật toán đi xuyên qua các nút không khớp làm cầu nối dẫn đường và tự động mở rộng quét biên (hnsw.iterative_scan = 'relaxed_order', giới hạn bởihnsw.max_scan_tuples) hoặc xây liên kết 2-hop không phụ thuộc điều kiện lọc (ACORN, Patel et al., SIGMOD 2024), phục hồi trọn100.0% Recall@10tại \(s = 2\%\). (Khi \(s < 0.5\%\), nên chuyển sang quét chỉ mục B-Tree rồi tính khoảng cách chính xác trên bitset kết quả!)
2.6 Phễu Gợi ý Đa tầng E-Commerce, Tách Thời gian Toàn cục & Tái xếp hạng MMR (E32:E35, Lab 05)#
Để phục vụ hàng triệu SKU trong < 50 ms P99 mà không làm sập ngân sách CPU/Feature Store, kiến trúc Lab 05 tách làm ba tầng rõ ràng:
- Ranh giới Thời gian Toàn cục & Rò rỉ
Leave-One-Out(Ji et al., ACM TOIS 2023): Giữ lại giao dịch cuối của từng user (LOO) cho phép mô hình sử dụng giao dịch tương lai của người dùng khác để dựng cạnh đồng truy cập (max_train_ts = 1478 > min_test_ts = 305trongLab 05), thổi phồng giảRecall@40thêm+32.1%! Bắt buộc tách cứng theo mốc thời gian toàn cục:\[\max_{e \in \mathcal{D}_{\text{train}}} t(e) < \min_{e \in \mathcal{D}_{\text{cal}}} t(e) \le \max_{e \in \mathcal{D}_{\text{cal}}} t(e) < \min_{e \in \mathcal{D}_{\text{test}}} t(e).\] - Tầng 1 — Truy xuất Đa nguồn & Khử Thiên lệch Phổ biến
IPS(Schnabel et al., ICML 2016): Dữ liệu click tự nhiên mang thiên lệch quan sát MNAR (nhóm hàng đầu15%chiếm phần lớn lượt hiển thị). Chấm điểm nhúng không khử thiên lệch gây sụp đổ phổ biến (R@200 = 50.4%, độ phủ top-20 chỉ11.4%). Trọng số nghịch đảo xác suất xuất hiện được cắt ngọn \(w_{\text{ips}}(i) = \operatorname{clip}(\hat{p}_i^{-\alpha_{\text{ips}}})\) kết hợp đồ thị đồng truy cập trênHNSWnângRecall@200lên73.1%và độ phủ lên85.9%. - Tầng 2 — Xếp hạng Đặc trưng Điểm Thời gian (
PIT) & Hiệu chuẩnPlatt(ch-07): Mọi đặc trưng xếp hạng (pit_user_cosine,pit_ctx_cosine,user_ctx_product,pit_cat_match,pit_price_match,pit_eb_ctr) đều chỉ đọc lịch sử thỏa mãn điều kiện nhân quả nghiêm ngặt \(t < t_q\). Điểm logit của ranker huấn luyện cân bằng lớp được hiệu chuẩn bằng Platt Scaling trên lát cắt thời gianD_cal(hạECE: 0.147 -> 0.051,Brier: 0.055 -> 0.013) trước khi nhân với biên lợi nhuận \(\text{margin}_i\). - Tầng 3 — Tái xếp hạng Kinh doanh Bằng
MMR(Carbonell & Goldstein, SIGIR 1998): Xếp hạng thuần túy theo xác suất nhấp lấp đầy 10 ô bằng các biến thể trùng lặp của cùng một món đồ. Maximal Marginal Relevance (MMR) chọn tham lam từng vị trí \(i_t \in R \setminus S_{t-1}\) cực đại hóa:\[\operatorname{MMR}(i \mid S_{t-1}) := \lambda_{\text{mmr}}\, \tilde{r}(u, i) - (1 - \lambda_{\text{mmr}}) \max_{j \in S_{t-1}} \max\!\big(0,\, \langle \mathbf{e}_i, \mathbf{e}_j \rangle\big),\]nâng độ đa dạng nội danh sáchILD@10từ0.551 -> 0.632, mở rộng độ phủ danh mục lên70.5%và nâng biên lợi nhuận kỳ vọng từ$22.18 -> $25.44.
Bảng Ngân sách Độ trễ, Bộ nhớ & Chi phí Kiến trúc Truy xuất Vector 2026#
| Phương pháp / Tầng | Quy mô Khuyến nghị | Bộ nhớ / Vector (d=768) |
Độ trễ P99 (k=10) |
Trần Recall@10 |
Điểm nghẽn Vận hành Chính |
|---|---|---|---|---|---|
Brute-Force BLAS (GEMM) |
\(n \le 50\text{k}\) | \(4d = 3{,}072\text{ B}\) | 0.5–3 ms |
1.000 |
Băng thông bộ nhớ DRAM |
KD-Tree / Ball-Tree |
\(d \le 16\) | \(4d + 32\text{ B}\) | > 50 ms ở \(d \ge 64\) |
1.000 |
Bùng nổ quét 100% ở chiều cao |
HNSW (M=16, fp32) |
\(n \le 50\text{M}\) (RAM) | \(4d + 8M \approx 3.2\text{ KB}\) | 0.8–3.0 ms |
0.97–0.995 |
Chi phí DRAM & thời gian dựng đồ thị |
HNSW (halfvec fp16 / SQ8) |
\(n \le 100\text{M}\) (RAM) | 0.9–1.7 KB |
0.8–3.0 ms |
0.95–0.985 |
Cần rescore nhẹ ở biên chính xác cao |
IVF-PQ (M_pq=48 + rescore) |
\(10\text{M}\text{–}500\text{M}\) | ~48–96 B (+ codebook) |
3–12 ms |
0.90–0.97 |
Huấn luyện Voronoi thô & nhiễu lượng tử hóa |
ScaNN (Aniso-PQ + LUT16) |
\(10\text{M}\text{–}1\text{B}\) (\(\text{MIPS}\)) | ~48–128 B |
1.5–6.0 ms |
0.94–0.98 |
Thiết kế chuyên \(\text{MIPS}\); cần rescore top-\(R\) |
DiskANN (Vamana NVMe SSD) |
\(100\text{M}\text{–}1\text{B}+\) | ~48 B RAM + SSD |
4–12 ms |
0.93–0.97 |
IOPS đọc ngẫu nhiên 4 KiB trên NVMe |
Phễu 3 Tầng E-Commerce (Lab 05) |
10^6 SKU -> 200 -> 10 |
Chỉ mục tiền tính toán | < 30–50 ms tổng |
R@200 = 73.1% |
Đồng bộ Feature Store PIT + MMR |
Trụ cột 3 — Công nghệ Sản xuất 2026: Bốn Case Thực chiến, Tám Phản mẫu & Mã nguồn Thực thi (R35.5)#
3.1 Bốn Kịch bản Sản xuất Thực tế (Production Case Studies)#
- Case 1 — Rò rỉ
Leave-One-OutKhi Đánh giá RecSys Tại Sàn Thương mại Điện tử (Ji et al., ACM TOIS 2023): Một đội kỹ thuật dùngLOOgiữ lại phiên cuối của mỗi người dùng làm test trong khi giữ mọi giao dịch khác vào train. Chiến dịch flash-sale cuối tháng tạo ra cạnh đồng truy cập giữa sản phẩm \(A \leftrightarrow B\) từ người dùng \(U_1\) (ngày 28) rò rỉ vào tập huấn luyện khi chấm điểm người dùng \(U_2\) (ngày 25). Chỉ sốLOOthổi phồng giả+32.1%(0.090 -> 0.411) trongLab 05, khiến mô hình học vẹt đồng truy cập thắng mô hình cá nhân hóa tổng quát trước khi sụp đổ sau khi A/B test. Khắc phục: Bắt buộc Global Temporal Split + kiểm thử Canary chứng minh mọi đặc trưngPITbất biến khi thay đổi dữ liệu \(t \ge t_q\). - Case 2 — Đói Kết quả Trên Tìm kiếm RAG / SKU Có Lọc
WHERE tenant_id / in_stock(selectivity = 2%): Kho1Mvector trongpgvectordùngHNSWvớief_search = 32phục vụ lọcWHERE category='running_shoes' AND in_stock=1(s = 2%). Lọc hậu kỳ trả về trung bình0.8dòng thay vì10dòng (Recall@10 = 7.6%), gây trang kết quả trống trên ứng dụng! Khắc phục: Bậthnsw.iterative_scan = 'relaxed_order'(pgvector 0.8+) hoặc triển khai đồ thịACORN, cho phép duyệt xuyên nút không khớp để khôi phục100.0% Recall@10(hoặc chuyển thẳng sang quét B-Tree + exact cosine khi \(s < 0.5\%\)). - Case 3 — Sụp đổ Khoảng cách Hỗn hợp & Thống trị Chuẩn Embedding \(\text{MIPS}\):
Trên mô hình đối chiếu sản phẩm bảng kết hợp
price_vndvàrating/CTR, bỏ qua chuẩn hóa khiếnL2chỉ còn đo khoảng cách giá (53.1%accuracy). Tương tự, mạng Two-Tower không chuẩn hóa khiến các sản phẩm có norm embedding lớn chiếm trọn top-200 bất chấp góc lệch người dùng. Khắc phục: Áplog1p + StandardScaler/ Mahalanobis nội nếp cho bảng (86.5%) và chuẩn hóa đơn vị hoặc dùng IPS debiasing +ScaNNcho Two-Tower. - Case 4 — Cắt giảm
$15,000/thángChi phí RAM Kho 500M Embedding Multimodal (768D): Lưu 500 triệu embedding768Dfp32trênHNSWtốn~1.66 TBRAM (> 25máy chủ DRAM lớn). Lộ trình hạ tầng chuẩn: Từ1M–10MdùngHNSW halfvec(~1.6 KB/vec); từ10M–200Mchuyển sangIVF-PQ/ScaNN(M_pq = 48, nén64xxuống24 GBcode + rescore top-50 trên NVMe); vượt200M–1B+dùngDiskANN Vamanađặt toàn bộ vector thô và cạnh trên NVMe SSD cùng bảng PQ gọn trong64 GBRAM!
3.2 Tám Phản mẫu Sản xuất & Cổng Kiểm soát (Anti-Patterns Matrix)#
| # | Phản mẫu (Anti-Pattern) |
Triệu chứng Sản xuất | Cổng Phát hiện / Kiểm thử | Biện pháp Khắc phục Bắt buộc |
|---|---|---|---|---|
| 1 | Dùng L2 thô trên dữ liệu đa đơn vị |
Cột tiền tệ chiếm 99.99% khoảng cách, độ chính xác rớt về ngẫu nhiên (53.1%) |
So sánh raw L2 vs Standardized / Mahalanobis |
Đặt StandardScaler / làm trắng nội nếp CV (86.5%) |
| 2 | Chọn \(k\) bằng sai số nội mẫu (Train Err) |
Luôn chọn \(k=1\) (Train Err = 0.000), quá khớp nhiễu nặng |
Cấm k=1 nếu không có kiểm chứng chéo OOF |
Vẽ Elbow Plot từ OOF CV (k=9, 0.254 vs 0.298) |
| 3 | Triển khai KD-Tree cho embedding \(d \ge 32\) |
KD-Tree quét 100% nút, chậm hơn quét BLAS tuần tự |
Đo mean_visit_frac trên truy vấn mẫu |
Chuyển sang HNSW / IVF-PQ / ScaNN khi \(d \ge 20\) |
| 4 | Lọc hậu kỳ trên HNSW ở \(s \le 5\%\) |
Truy vấn LIMIT 10 chỉ trả về 0–2 kết quả (Recall@10 = 7.6%) |
Kiểm thử bắt buộc ở \(s = 2\%\) với efSearch=32 |
Bật iterative_scan (pgvector 0.8+) / ACORN (100.0%) |
| 5 | Chia tập Leave-One-Out (LOO) cho RecSys |
max_train_ts > min_test_ts, Recall@40 ảo tăng +32.1% |
Cổng CI khẳng định max(train_ts) < min(test_ts) |
Chuyển sang Global Temporal Split + Canary PIT t < t_q |
| 6 | Two-Tower thiếu khử thiên lệch phổ biến IPS |
Top 15% sản phẩm phổ biến chiếm hết gợi ý (Cov@20 = 11.4%) |
Giám sát Catalog Coverage & Recall@200 đuôi dài |
Áp trọng số IPS (\(p_i^{-\alpha}\)) + ghép đồ thị Co-visitation (85.9%) |
| 7 | Nhân logit ranker thô chưa hiệu chuẩn với biên lợi nhuận | Sai thứ tự kỳ vọng \(\hat{p} \cdot \text{margin}\) do lệch xác suất nền (ECE = 0.147) |
Kiểm tra ECE & Brier trên lát cắt D_cal |
Huấn luyện PlattCalibrator trên D_cal (ECE -> 0.051) |
| 8 | Bỏ qua tái xếp hạng đa dạng (lambda_mmr = 1.0) |
Trang chủ hiện 10 mẫu gần giống hệt nhau (ILD = 0.551) |
Đo ILD@10 và độ phủ danh mục trước khi phát hành |
Áp MMR (\(\lambda_{\text{mmr}} \approx 0.58\)) nâng ILD -> 0.632 & biên $25.44 |
3.3 Mẹo Công nghiệp SOTA 2025–2026: Lượng tử hóa Bất đối xứng (Qdrant ABQ, Extended RaBitQ), Định dạng Lance & Thoái hóa Đồ thị HNSW tombstones (Principal Tip #8)#
Khi mở rộng hệ thống tìm kiếm vector từ vài trăm nghìn lên hàng trăm triệu đến hàng tỷ bản ghi đa phương thức có tần suất cập nhật/xóa cao, 3 quyết định hạ tầng SOTA 2025–2026 dưới đây quyết định trực tiếp cân bằng giữa RAM, Recall@10 và độ ổn định p99:
- Lượng tử hóa 1-Bit đến Đa-Bit Không Đánh mất Độ chính xác (
Qdrant ABQ&Extended RaBitQ):Qdrant ABQ(Asymmetric Binary Quantization): Nén nhị phân đối xứng (Symmetric BQ) ép cả vector lưu trữ lẫn vector truy vấn xuống1-bit(sign(x)), cắt32×RAM nhưng làm mất thông tin biên độ truy vấn và kéo sập độ chính xác khi chiều \(d < 1024\) hoặc chuẩn vector biến thiên.Qdrant ABQgiữ các vector trong kho ở dạng nén nhị phân siêu gọn (1-bit/1.5-bit/2-bit) để tối đa hóa tiết kiệm RAM và tốc độ phép toán bit SIMD, nhưng giữ nguyên vector truy vấn ở độ chính xác cao (int8vô hướng hoặcfloat32) kèm tái chuẩn hóa độ dài — giúp thu hẹp mạnh khoảng cáchRecall@10trước bướcrescoretop-\(K_{\text{cand}}\) từ NVMe.Extended RaBitQ(SIGMOD 2025): Mở rộngRaBitQ(1-bit,SIGMOD 2024) sang lượng tử hóa đa bit tùy ý (2-bitđến8-bitmỗi chiều) sau phép xoay trực giao ngẫu nhiên (Hadamard / orthogonal rotation), giữ nguyên cận sai số lý thuyết chặt chẽ và bộ ước lượng tích vô hướng không chệch. Khác vớiIVF-PQ(phải huấn luyện bảng mãk-meansnặng nề và dễ lệch phân phối khi dữ liệu mới đổ vào),Extended RaBitQhoạt động ổn định không cần huấn luyện codebook phức tạp mà vẫn vượt chuẩn lượng tử hóa vô hướng/tích ở cùng ngân sách bit.
- Kho Lưu trữ Lakehouse Vector & Đa phương thức Định dạng
Lance:Parquettruyền thống lưu theo khối nén tuần tự lớn (row groups), khiến truy cập ngẫu nhiên top-\(50\) vector gốc cho bướcrescorehoặc đọc mảnh ảnh/tài liệu đa phương thức bị khuếch đại I/O nghiêm trọng. Định dạng bảng cộtLance(columnar vector/multimodal lakehouse format) giải quyết bằng bố cục truy cập ngẫu nhiên \(\mathcal{O}(1)\) tốc độ NVMe (chỉ đọc đúng phần tử được chọn mà không giải nén cả khối), hỗ trợ lập phiên bản dữ liệu + chỉ mục không sao chép (zero-copy versioning / time travel), và tích hợp bản địa chỉ mụcIVF-PQ/DiskANN/HNSWtrên cùng kho lưu trữ đa phương thức. - Thoái hóa Đồ thị
HNSW tombstones(Soft-Delete Graph Degradation, Zombie Hops & Compaction Triggers): Trong sản xuất, xóa cứng trực tiếp một nút khỏi đồ thị đa tầngHNSWđòi hỏi khóa ghi và nối lại cạnh nhiều tầng tốn \(\mathcal{O}(M \cdot \text{efConstruction})\). Vì vậy hầu hết vector DB (Qdrant,Milvus,pgvector) áp dụng xóa mềm bằng cách gắn cờHNSW tombstoneslên bản ghi bịDELETEhoặc bị thay thế bởiUPSERT. Nếu luồng dữ liệu cập nhật/hết hạn TTL liên tục, các nút bị gắn tombstone trở thành "nút thây ma" (zombie nodes) vẫn chiếm RAM và nằm trên đường dẫn đồ thị: thuật toán beam search phải trả chi phí duyệt qua hàng loạtzombie hopsvô ích khiến độ trễp99đội lên2–5×, đồng thời làm đứt gãy cầu nối cục bộ kéo tụtRecall@10. Quy tắc vận hành bắt buộc: (a) đặt cảnh báo tỷ lệtombstone_ratiovà kích hoạt ngưỡng nén/tái dựng phân đoạn (compaction / segment vacuum trigger) ngay khi vượt15%–20%(ví dụdeleted_thresholdtrong optimizer củaQdranthoặcVACUUM/REINDEXtrongpgvector); (b) với dữ liệu hết hạn theo ngày/tuần, tách theo bộ sưu tập cuộn theo cửa sổ thời gian (time-bucketed rolling collections + collection aliasing) đểDROPnguyên phân đoạn cũ không sinhHNSW tombstones! (Ghi chú liên thông: Khi dùng chỉ số truy xuất trên nhật ký gợi ý quan sát để ước lượng hiệu quả nhân quảCATE/DoubleML/Causal Forests, xem quy trình trực giao hóa Neyman và kiểm định nhạy cảm \(\Gamma\) tạich-05.)
3.4 Mã nguồn Thực thi Hệ sinh thái 2026 (scikit-learn Mahalanobis/KDTree, ADC LUT, HNSW Lọc Iterative Scan, & MMR)#
(Các hàm dưới đây thực thi trực tiếp trong môi trường Python 3.12+ .venv với NumPy, SciPy, scikit-learn.)
from __future__ import annotations
import numpy as np
from numpy.typing import NDArray
from scipy.spatial.distance import cdist
from sklearn.cluster import KMeans
from sklearn.neighbors import KDTree, KNeighborsClassifier
from sklearn.preprocessing import StandardScaler
FloatArray = NDArray[np.float64]
def demo_metrics_kdtree_and_ivfpq_adc(seed: int = 42) -> dict[str, float]:
"""Demonstrate scale trap rescue, KD-Tree high-dim collapse, and IVF-PQ ADC lookup."""
rng = np.random.default_rng(seed)
n, d = 600, 64
# 1. Scale trap + correlation rescue via fold-isolated StandardScaler & Whitened Mahalanobis
y = rng.integers(0, 2, size=n)
z1 = rng.normal(0.0, 2.0, size=n)
z2 = 0.88 * z1 + rng.normal(0.0, 0.35, size=n)
sep = np.where(y == 1, 0.65, -0.65) + rng.normal(0.0, 0.30, size=n)
price_noise = rng.normal(12000.0, 2500.0, size=n)
X_tab = np.column_stack([price_noise, z1, z2 + sep, 0.7 * z1 + 0.6 * sep])
X_tr, y_tr, X_te, y_te = X_tab[:400], y[:400], X_tab[400:], y[400:]
raw_acc = float(KNeighborsClassifier(n_neighbors=7).fit(X_tr, y_tr).score(X_te, y_te))
scaler = StandardScaler().fit(X_tr)
X_tr_s, X_te_s = scaler.transform(X_tr), scaler.transform(X_te)
std_acc = float(KNeighborsClassifier(n_neighbors=7).fit(X_tr_s, y_tr).score(X_te_s, y_te))
cov_reg = 0.98 * np.cov(X_tr_s, rowvar=False) + 0.02 * np.eye(X_tr_s.shape[1])
evals, evecs = np.linalg.eigh(cov_reg)
whiten = (evecs / np.sqrt(np.maximum(evals, 1e-9))) @ evecs.T
mahal_acc = float(
KNeighborsClassifier(n_neighbors=7).fit(X_tr_s @ whiten.T, y_tr).score(X_te_s @ whiten.T, y_te)
)
# 2. Verify Cosine == L2 order on L2-normalized vectors
U_raw = rng.normal(0.0, 1.0, size=(100, 16))
U_norm = U_raw / np.linalg.norm(U_raw, axis=1, keepdims=True)
Q_norm = U_norm[:5]
idx_l2 = np.argsort(cdist(Q_norm, U_norm, metric="euclidean"), axis=1)[:, :5]
idx_cos = np.argsort(cdist(Q_norm, U_norm, metric="cosine"), axis=1)[:, :5]
cos_l2_agreement = float(np.mean(idx_l2 == idx_cos))
# 3. KD-Tree query parity & IVF-PQ Asymmetric Distance Computation (ADC LUT)
centers = rng.normal(0.0, 1.8, size=(12, d))
X_vec = centers[rng.integers(0, 12, size=n)] + rng.normal(0.0, 0.45, size=(n, d))
Q_vec = centers[rng.integers(0, 12, size=20)] + rng.normal(0.0, 0.45, size=(20, d))
_, gt_idx = KDTree(X_vec, leaf_size=16).query(Q_vec, k=10)
# Residual PQ with M_pq=16 subspaces (16 bytes/vec vs 256 bytes fp32 -> 16x compression)
m_pq, k_cent, n_lists = 16, 16, 16
sub_d = d // m_pq
km_c = KMeans(n_clusters=n_lists, n_init=3, random_state=seed).fit(X_vec)
c_lbl = km_c.labels_
res = X_vec - km_c.cluster_centers_[c_lbl]
codes = np.zeros((n, m_pq), dtype=np.uint8)
books: list[FloatArray] = []
for m in range(m_pq):
sl = slice(m * sub_d, (m + 1) * sub_d)
km_s = KMeans(n_clusters=k_cent, n_init=2, random_state=seed + m).fit(res[:, sl])
codes[:, m] = km_s.labels_.astype(np.uint8)
books.append(km_s.cluster_centers_)
recalls_rescore: list[float] = []
for qi in range(20):
q = Q_vec[qi]
probed = np.argsort(np.sum((km_c.cluster_centers_ - q) ** 2, axis=1))[:6]
cand_mask = np.isin(c_lbl, probed)
cand_ids = np.flatnonzero(cand_mask)
adc_d = np.zeros(len(cand_ids), dtype=np.float64)
for cid in probed:
loc = np.flatnonzero(c_lbl[cand_ids] == cid)
if len(loc) == 0:
continue
q_res = q - km_c.cluster_centers_[cid]
for m in range(m_pq):
sl = slice(m * sub_d, (m + 1) * sub_d)
lut = np.sum((books[m] - q_res[sl]) ** 2, axis=1)
adc_d[loc] += lut[codes[cand_ids[loc], m]]
top30 = cand_ids[np.argsort(adc_d)[:30]]
top10 = top30[np.argsort(np.sum((X_vec[top30] - q) ** 2, axis=1))[:10]]
recalls_rescore.append(len(set(top10.tolist()) & set(gt_idx[qi].tolist())) / 10.0)
return {
"raw_l2_acc": round(raw_acc, 4),
"std_l2_acc": round(std_acc, 4),
"mahalanobis_acc": round(mahal_acc, 4),
"cos_l2_unit_agreement": cos_l2_agreement,
"ivfpq_rescore30_recall10": round(float(np.mean(recalls_rescore)), 4),
}
def demo_greedy_mmr_rerank(seed: int = 42) -> dict[str, float]:
"""Demonstrate greedy MMR diversity and margin optimization over candidate embeddings."""
rng = np.random.default_rng(seed)
# 12 candidates: items 0..5 share category 0 (near-duplicate sneakers), 6..11 diverse categories
embs = rng.normal(0.0, 0.15, size=(12, 8))
embs[:6, 0] += 2.5
for idx in range(6, 12):
embs[idx, idx - 5] += 2.5
embs /= np.linalg.norm(embs, axis=1, keepdims=True)
rel = np.array([0.96, 0.94, 0.92, 0.90, 0.88, 0.86, 0.82, 0.80, 0.78, 0.75, 0.72, 0.70])
def ild(slate: list[int]) -> float:
sub = embs[slate]
sim = sub @ sub.T
i_u, j_u = np.triu_indices(len(slate), k=1)
return float(np.mean(1.0 - sim[i_u, j_u]))
pure_top5 = list(np.argsort(-rel)[:5])
mmr_top5 = [int(np.argmax(rel))]
rem = [i for i in range(12) if i != mmr_top5[0]]
lam = 0.55
while len(mmr_top5) < 5:
best = max(
rem,
key=lambda c: lam * rel[c] - (1.0 - lam) * max(float(embs[c] @ embs[s]) for s in mmr_top5),
)
mmr_top5.append(best)
rem.remove(best)
return {"pure_ild5": round(ild(pure_top5), 4), "mmr_ild5": round(ild(mmr_top5), 4)}
if __name__ == "__main__":
print("Metrics/KDTree/IVFPQ:", demo_metrics_kdtree_and_ivfpq_adc())
print("MMR Diversity:", demo_greedy_mmr_rerank())
Trụ cột 4 — Phòng Thí nghiệm Công nghiệp Miền E-Commerce (Lab 05: recsys_ann_lab)#
4.1 Kiến trúc Hai Tầng (Two-Tier), uv.lock & Bảo mật AST Deserialization#
Gói recsys_ann_lab triển khai Tầng 1 (Reference Core) từ con số 0 trên Python/NumPy (KDTreeIndex, HNSWIndex, IVFPQIndex, ScaNN bất đẳng hướng, phễu RecSys 3 tầng) song song với Tầng 2 (SOTA Parity) tương thích hoàn toàn với scikit-learn, scipy, pandas, và pydantic>=2 (extra="forbid"), khóa phụ thuộc bằng uv.lock và kiểm toán AST bảo mật deserialization (0 pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal):
labs/lab-05-ecommerce-multi-stage-recsys/
├── pyproject.toml # Python >=3.10, numpy, pandas, pydantic>=2, scikit-learn, scipy, dev tools
├── uv.lock # Khóa phiên bản tái lập (39 gói) qua `uv lock`
├── README.md # Hướng dẫn Lab 05 (100% tiếng Việt)
├── artifacts/
│ └── ch11_lab05_results.json # Kết quả thực nghiệm đầy đủ + `workbench_panels`
├── src/
│ └── recsys_ann_lab/
│ ├── __init__.py
│ ├── distance_and_ann.py # Curse analyzer, ExactKNN/Mahalanobis, KDTree, HNSW, IVF-PQ/ADC, ScaNN, Filtered ANN
│ └── multistage_recsys.py # Global Temporal vs LOO, IPS+HNSW Stage 1, PIT+Platt Stage 2, MMR Stage 3 & Runner
├── scripts/
│ └── run_lab_demo.py # CLI hỗ trợ `--quick`, `--seed`, `--output`
└── tests/
└── test_recsys_ann_lab.py # 16 kiểm thử tự động (toán học, PIT Canary, Tier 2 parity, AST bảo mật)
4.2 Kết quả Thực nghiệm CLI (artifacts/ch11_lab05_results.json)#
Chạy một lệnh duy nhất từ thư mục gốc của Lab 05:
python scripts/run_lab_demo.py --seed 42 --output artifacts/ch11_lab05_results.json
Báo cáo JSON xuất đầy đủ workbench_panels (6 KPI, 4 biểu đồ cột, 4 bảng dữ liệu) khớp 100% các thông số thực đo dưới đây:
Mã KPI (workbench_panels.kpis) |
Giá trị Thực nghiệm Chính xác | Trạng thái & Ý nghĩa Kiểm chứng |
|---|---|---|
kpi_curse_and_mahalanobis |
0.17 vs 51.5 | 86.5% (d=512 vs d=2 | Acc) |
ok — Tương phản đẳng hướng sụp đổ 51.52 -> 0.172 (vỏ 5%: 9.75% -> 100.00%), đa tạp 8D giữ 17.472; Raw L2 53.1% được StandardScaler cứu lên 82.7% và Mahalanobis đạt 86.5% (k=1 train 0.000 vs CV 0.298, chọn k=9 đạt 0.254 <= 0.356). |
kpi_kdtree_vs_hnsw_recall |
KD 100% | HNSW 100.0% (Scan% | Recall@10) |
ok — KD-Tree khớp sklearn 100%, quét 21.1% ở d=4 nhưng vọt lên 100.0% ở d=64; HNSW (M=12, 228 B/vec) đạt 100.0% Recall@10 khi chỉ quét 9.3%–35.8%. |
kpi_ivfpq_compression_and_scann |
16x RAM | Rec 96.9% (ScaNN 54.3%) |
ok — IVF-PQ nén 256 B -> 16 B/vec, tăng 0.631 -> 0.969 Recall@10 khi rescore top-30; ScaNN (\(h_\parallel = 6.0, h_\perp = 1.0\)) cắt top-20 MIPS MSE 0.284 -> 0.114 (-60.0%) và nâng Recall@10 0.513 -> 0.543. |
kpi_filtered_ann_selectivity |
7.6% -> 100.0% (Recall@10) |
warn — Tại độ chọn lọc s = 2%: lọc hậu kỳ chỉ trả 0.8/10 sản phẩm (7.6%), lọc tiền kỳ cạnh đứt gãy (5.6%), còn Iterative Scan (pgvector 0.8+/ACORN) khôi phục 100.0%. |
kpi_recsys_temporal_stage2_lift |
R@200 73.1% | NDCG 0.119->0.169 (LOO Leak +32.1%) |
critical — LOO rò rỉ tương lai (1478 > 305) thổi phồng Recall@40 thêm +32.1% (0.090 -> 0.411). Global Temporal Split (974 < 975 <= 1199 < 1200): Stage 1 IPS+CoVis HNSW nâng R@200 50.4% -> 73.1% (Cov20 11.4% -> 85.9%); Stage 2 PIT + Platt nâng NDCG@10 0.119 -> 0.169 (MAP 0.066 -> 0.098), hạ ECE 0.147 -> 0.051. |
kpi_mmr_diversity_and_margin |
ILD 0.551->0.632 | Cov 70.5% (Margin $25.44) |
ok — Tái xếp hạng MMR (\(\lambda_{\text{mmr}} = 0.58\)) nâng đa dạng ILD@10 0.551 -> 0.632, độ phủ top-10 69.9% -> 70.5%, và nâng biên lợi nhuận kỳ vọng từ $22.18 -> $25.44. |
4.3 Hợp đồng 16 Kiểm thử Tự động pytest (tests/test_recsys_ann_lab.py)#
| # | Tên Hàm Kiểm thử Chính xác | Tiêu chuẩn Khẳng định & Bất biến Cần Đạt |
|---|---|---|
| 1 | test_01_pydantic_configs_and_curse_of_dimensionality |
Kiểm chứng Pydantic extra="forbid" và suy giảm đơn điệu của tương phản đẳng hướng vs bảo toàn đa tạp 8D qua d = 2..512. |
| 2 | test_02_exact_knn_metrics_scale_trap_and_mahalanobis_rescue |
Khẳng định tương đương Cosine == L2 trên \(\mathbb{S}^{d-1}\), Mahalanobis > Std L2 > Raw L2 (> 85%), và OOF CV k > 1 thắng bẫy k=1 thỏa Cover–Hart. |
| 3 | test_03_kdtree_exact_parity_with_sklearn_and_high_dim_collapse |
Đối chiếu KDTreeIndex khớp 100% sklearn.neighbors.KDTree, quét < 30% ở d=4 và sụp đổ > 85% (100%) ở d=64. |
| 4 | test_04_hnsw_pareto_ef_search_lifts_recall_and_memory_formula |
Khẳng định HNSW tăng Recall@10 >= 0.90 theo efSearch ở phân suất quét nhỏ và thỏa công thức bộ nhớ 4d + 8M. |
| 5 | test_05_ivf_pq_adc_compression_and_recall_tradeoff |
Kiểm chứng IVF-PQ nén >= 8x (16x) và kết hợp rescore nâng Recall@10 >= 0.80 (0.969). |
| 6 | test_06_scann_anisotropic_quantization_beats_isotropic_on_mips |
Khẳng định lượng tử hóa bất đẳng hướng ScaNN giảm top-20 MIPS MSE và giữ MIPS Recall@10 vượt K-Means đẳng hướng. |
| 7 | test_07_filtered_ann_selectivity_collapse_and_iterative_scan_rescue |
Tại s = 2%, khẳng định post_filter < 0.45, pre_filter_graph < 0.60, còn iterative_scan >= 0.90 (1.000). |
| 8 | test_08_global_temporal_split_strict_vs_leave_one_out_leakage |
Khẳng định max(train_ts) < min(cal_ts) < min(test_ts) và chứng minh LOO rò rỉ tương lai thổi phồng Recall@40. |
| 9 | test_09_stage1_ips_debiasing_and_covisitation_beat_popularity_baseline |
Chứng minh Stage 1 IPS + Co-Visitation vượt trội đối chứng thiên lệch phổ biến trên cả Recall@120/200 và Catalog Coverage@20. |
| 10 | test_10_stage2_pit_ranker_beats_stage1_ndcg_and_map |
Khẳng định Stage 2 PIT Feature Ranker vượt Stage 1 chặt chẽ trên cả NDCG@10 và MAP@10. |
| 11 | test_11_platt_calibration_improves_ece_and_brier |
Khẳng định PlattCalibrator khớp trên D_cal cắt giảm > 50% ECE và hạ Brier Score trên tập D_test. |
| 12 | test_12_stage3_mmr_reranking_raises_ild_and_catalog_coverage |
Khẳng định MMR nâng ILD@10 thêm > +0.05 và mở rộng Catalog Coverage@10 so với xếp hạng thuần liên quan. |
| 13 | test_13_point_in_time_feature_causality_canary |
Canary Chống Rò rỉ: Làm sai lệch toàn bộ dữ liệu tương lai t >= q_ts và khẳng định vector đặc trưng PIT bất biến tuyệt đối (0.0 sai khác). |
| 14 | test_14_cli_demo_quick_flag_and_workbench_panels_contract |
Chạy scripts/run_lab_demo.py --quick, xác nhận config["quick"] is True và toàn vẹn workbench_panels (6 KPI, 4 bar, 4 bảng). |
| 15 | test_15_tier2_sklearn_scipy_parity_exact_knn_and_distance |
Đối chiếu ExactKNNClassifier khớp tuyệt đối scipy.spatial.distance.cdist (< 1e-10) và sklearn.neighbors.KNeighborsClassifier. |
| 16 | test_16_security_only_ast_deserialization_guard |
Quét AST toàn bộ src/, scripts/, tests/ khẳng định 0 import giải tuần tự hóa nguy hiểm (pickle, _pickle, cPickle, joblib, cloudpickle, dill, shelve, marshal). |
Trụ cột 5 — Tài liệu Đọc SOTA (1967–2026) & Bộ Đánh giá Năng lực (SOTA Reading List & Mastery Assessment)#
5.1 Danh mục Tài liệu Kinh điển & Tiên phong (Curated SOTA Reading List)#
- Cover, T. M., & Hart, P. E. (
IEEE Trans. Info. Theory, 1967). "Nearest neighbor pattern classification".
Vì sao quan trọng: Thiết lập định lý nền tảng chứng minh ngay cả1-NNđơn giản nhất cũng có sai số tiệm cận bị chặn chặt bởi \(2R^*(1 - R^*)\). - Beyer, K., Goldstein, J., Ramakrishnan, R., & Shaft, U. (
ICDT, 1999). "When is 'nearest neighbor' meaningful?".
Vì sao quan trọng: Định hình điều kiện chính xác của Lời nguyền Số chiều (\(D_{\min}/D_{\max} \to 1\)), đồng thời làm rõ vì sao cấu trúc đa tạp phân cụm vẫn giữ được ý nghĩa khoảng cách. - Jégou, H., Douze, M., & Schmid, C. (
IEEE TPAMI, 2011). "Product Quantization for Nearest Neighbor Search".
Vì sao quan trọng: Tạo ra chuẩn nén không gian conIVF-PQvà phép tính khoảng cách bất đối xứngADC LUT, cho phép chứa hàng trăm triệu đến hàng tỷ vector trong bộ nhớ. - Malkov, Y. A., & Yashunin, D. A. (
IEEE TPAMI, 2020 /arXiv:1603.09320). "Efficient and robust approximate nearest neighbor search using Hierarchical Navigable Small World graphs".
Vì sao quan trọng: Phát minh kiến trúc đồ thị đa tầngHNSW— chuẩn mực mặc định cho tìm kiếm độ trễ dưới3 mstrong mọi cơ sở dữ liệu vector hiện đại (pgvector,Qdrant,Milvus,FAISS). - Guo, R., Sun, P., Lindgren, E., Geng, Q., Simcha, D., Chern, F., & Kumar, S. (
ICML, 2020 /arXiv:1908.10396). "Accelerating Large-Scale Inference with Anisotropic Vector Quantization" (ScaNN).
Vì sao quan trọng: Chứng minh hàm mất mát bất đẳng hướng trọng số hóa thành phần song song (\(h_\parallel \gg h_\perp\)) tối ưu vượt trội cho truy xuất tích vô hướng \(\text{MIPS}\) trong Two-Tower RecSys & RAG. - Subramanya, S. J., et al. (
NeurIPS, 2019); Patel, L., et al. (SIGMOD, 2024 —ACORN); Ji, Y., et al. (ACM TOIS, 2023); Schnabel, T., et al. (ICML, 2016); Carbonell, J., & Goldstein, J. (SIGIR, 1998 —MMR).
Vì sao quan trọng: Mở rộngANNra quy mô tỷ vector trên SSD (DiskANN Vamana), giải quyết lọc metadata chọn lọc thấp (ACORN/pgvector 0.8+), bóc trần rò rỉLOOtrong RecSys, khử thiên lệchIPS, và tái xếp hạng đa dạngMMR.
5.2 Tám Câu hỏi Kiểm tra Nắm vững Khái niệm (Q1–Q8)#
- Q1: Chứng minh đại số vì sao trên vector chuẩn hóa \(L_2\), xếp hạng theo
Cosine Similarity,Cosine DistancevàEuclidean L2cho kết quả giống hệt nhau; và giải thích vì saoL2thô tụt về53.1%trên dữ liệu trộn đơn giá trong khiMahalanobisđạt86.5%? - Q2: Dẫn xuất cận Cover–Hart (
1967) \(R^* \le R_{1\text{-NN}} \le 2R^*(1-R^*)\) bằng bất đẳng thức Jensen, và giải thích vì sao dùng sai số tập huấn luyện vẽElbow Plotluôn chọn nhầm \(k=1\) (0.000train vs0.298CV)? - Q3: Chứng minh quy luật tập trung vỏ \(1 - (1-\epsilon)^d\) và tốc độ suy giảm độ phân tán tương đối \(\mathcal{O}(d^{-1/2})\) của định lý Beyer (
1999), giải thích vì sao đa tạp8Dnhúng vào512Dvẫn giữ tương phản17.472, và lý doKD-Treephải quét100.0%nút tạid=64? - Q4: Giải thích cơ chế nhảy bước tầng trên xuống tầng
0trongHNSW, vai trò chọn cạnh đa dạng góc, ý nghĩa từng tham số(M, efConstruction, efSearch), và cách tính công thức RAM4d + 8M? - Q5: Phân biệt
SDCvsADCtrongIVF-PQ, viết công thức dựng bảng tra cứuLUTkích thước \(M_{\text{pq}} \times K^*\), và giải thích vì sao nén16xkết hợp tái chấm điểm top-30 nângRecall@10từ0.631 -> 0.969? - Q6: Vì sao hàm mất mát đẳng hướng \(L_2\) làm sai lệch điểm số \(\text{MIPS}\) so với hàm bất đẳng hướng
ScaNN(\(h_\parallel \gg h_\perp\), giảmMSE -60.0%), và kiến trúcDiskANN Vamanađặt những gì trên RAM vs trên NVMe SSD? - Q7: Ở độ chọn lọc lọc SQL \(s = 2\%\) (
LIMIT 10,efSearch = 32), vì sao lọc hậu kỳ tụt xuống7.6%(0.8/10dòng), lọc tiền kỳ cứng trên đồ thị tụt xuống5.6%, vàpgvector 0.8+ hnsw.iterative_scan/ACORNkhôi phục100.0%bằng cơ chế nào? - Q8: Giải thích luồng dữ liệu 3 tầng của
Lab 05(từGlobal Temporal Splitchặn rò rỉLOO +32.1%,IPS + CoVis HNSWnângR@200 50.4% -> 73.1%,PIT + PlatthạECE 0.147 -> 0.051, đếnMMRnângILD 0.551 -> 0.632và biên lợi nhuận$22.18 -> $25.44)?
5.3 Sáu Bài tập Thực hành & Chứng minh Tính điểm (Ex1–Ex6)#
- Bài tập 1 (
15%): Chứng minh tập trung thể tích vỏ \(1-(1-\epsilon)^d\), định lý Beyer \(\mathcal{O}(d^{-1/2})\) và phép biến đổi làm trắng Mahalanobis; chạyanalyze_curse_of_dimensionality()vàbenchmark_scale_trap_mahalanobis()kiểm chứng51.52 -> 0.172và53.1% -> 86.5%. - Bài tập 2 (
15%): Dẫn xuất cận Cover–Hart \(2R^*(1-R^*)\) và phân rã Bias–Variance theo \(k\); chạyselect_k_via_cv()đối chiếu ảo giáck=1(0.000train vs0.298CV) với tối ưu OOFk=9(0.254). - Bài tập 3 (
20%): So sánhKDTreeIndexvớisklearn.neighbors.KDTreequabenchmark_kdtree_collapse()(21.1%ởd=4vs100.0%ởd=64) và khảo sát đường cong ParetoHNSWIndexcùng ngân sách RAM4d + 8M. - Bài tập 4 (
20%): ChạyIVFPQIndex(16xnén,0.969rescore), dẫn xuất nghiệm đóng tâm cụm bất đẳng hướng củaScaNN(0.284 -> 0.114 MSE), và tái lập sự cố lọc \(s = 2\%\) (7.6%/5.6%\(\to\)100.0%vớiiterative_scan). - Bài tập 5 (
15%): Kiểm toán rò rỉ thời gian quaaudit_temporal_vs_loo_leakage()(LOO +32.1%vsGlobal Temporal) và chạy kiểm thử Canarytest_13_point_in_time_feature_causality_canarychứng minh đặc trưngPITbất biến tuyệt đối trước tương lai. - Bài tập 6 (
15%): Chạy trọn vẹn phễu RecSys 3 tầng (Stage 1 IPS+HNSW -> Stage 2 PIT+Platt -> Stage 3 MMR) quascripts/run_lab_demo.py, kiểm traruff0lỗi,0import deserialization bị cấm (Test 16), và vượt toàn bộ16/16kiểm thửpytest.
5.4 Thang Điểm & Tiêu chuẩn Nghiệm thu (Grading Rubric)#
| Cấp độ | Thang điểm | Tiêu chí Đánh giá Chi tiết |
|---|---|---|
| Principal Standard | 90–100% | Chứng minh chặt chẽ đẳng thức mặt cầu Cosine-\(L_2\), Cover–Hart 1967, Beyer 1999, công thức ADC LUT, nghiệm đóng bất đẳng hướng ScaNN, bộ nhớ 4d+8M của HNSW, và cơ chế giải cứu lọc iterative_scan / ACORN; hoàn thành 16/16 pytest trên recsys_ann_lab (Canary PIT lệch 0.0, LOO audit chuẩn, MMR tăng ILD & biên, AST 0 import giải tuần tự hóa nguy hiểm) và đạt ruff 0 lỗi. |
| Senior Standard | 75–89% | Vượt qua 16/16 pytest, nắm vững chọn tham số HNSW/IVF-PQ, hiệu chuẩn Platt trên D_cal và phễu 3 tầng Lab 05, nhưng còn thiếu bước dẫn xuất giải tích cho định lý Beyer hoặc nghiệm đóng cập nhật tâm ScaNN. |
| Needs Remediation | < 75% | Dùng L2 không chuẩn hóa trên dữ liệu hỗn hợp; chọn \(k=1\) theo sai số huấn luyện; dùng KD-Tree ở \(d \ge 32\); dùng lọc hậu kỳ thô ở \(s \le 5\%\); tách tập Leave-One-Out gây rò rỉ tương lai trong RecSys; bỏ qua Platt/IPS/MMR; hoặc để lọt pickle/joblib (CWE-502). |
Curse of Dimensionality: Isotropic Contrast Ratio (D_max-D_min)/D_min across Dim d
Exact k-NN Metric Accuracy under Mixed Feature Units & Correlated Ellipses
Filtered Vector Search at Selectivity s=2% (Recall@10)
E-Commerce Multi-Stage RecSys: NDCG@10, Diversity (ILD) & Catalog Coverage
Curse of Dimensionality (Isotropic vs 8D Manifold) & KD-Tree Scan Collapse
| Dim d | Shell (5%) Vol | Iso Contrast | Manifold Contrast | KD-Tree Scan% |
|---|---|---|---|---|
| 2 | 9.75% | 51.520 | 153.866 | 21.1% |
| 8 | 33.66% | 3.426 | 23.860 | — |
| 32 | 80.63% | 0.919 | 18.854 | 100.0% |
| 128 | 99.86% | 0.372 | 17.932 | 100.0% |
| 512 | 100.00% | 0.172 | 17.472 | 100.0% |
HNSW efSearch Pareto Frontier vs IVF-PQ ADC Compression
| Index / Mode | Param | Recall@10 | Visited / Scanned | Bytes / Vec |
|---|---|---|---|---|
| HNSW (M=12) | efSearch=20 | 1.000 | 97.6 (10.2%) | 228 B |
| HNSW (M=12) | efSearch=64 | 1.000 | 177.0 (18.4%) | 228 B |
| IVF-PQ (ADC) | nprobe=3, rescore=0 | 0.631 | 114.2 cands | 16 B (16x) |
| IVF-PQ (ADC) | nprobe=6, rescore=30 | 0.969 | 228.6 cands | 16 B (16x) |
Exact k-NN CV Elbow Trap (k=1 Train 0.0) & ScaNN Anisotropic MIPS
| Experiment | Setting | Metric A | Metric B | Takeaway |
|---|---|---|---|---|
| kNN Elbow Trap | k=1 (In-Sample) | Train Err=0.000 | CV Err=0.298 | Best CV k=9 (0.254) |
| Cover-Hart Bound | Bayes R* Check | R*=0.232 | 2R(1-R)=0.356 | 1-NN CV=0.298 <= Bound |
| ScaNN MIPS Quant | Isotropic vs Aniso | Iso MSE=0.284 | Aniso MSE=0.114 | Recall@10 0.513->0.543 |
E-Commerce Multi-Stage RecSys (Global Temporal Split vs LOO & MMR)
| Stage / Method | Recall / NDCG | MAP@10 / ECE | ILD@10 / Cov | Margin (USD) |
|---|---|---|---|---|
| Stage 1 (Pop-Biased) | R@200=0.504 | — | Cov20=11.4% | — |
| Stage 1 (IPS + CoVis HNSW) | R@200=0.731 | NDCG=0.119 | Cov20=85.9% | — |
| Stage 2 (PIT + Platt) | NDCG@10=0.169 | MAP=0.098 | ECE=0.051 | Cov10=69.9% | $22.18 |
| Stage 3 (MMR Re-rank) | NDCG@10=0.133 | MAP=0.098 | Uncal=0.147 | ILD=0.632 | Cov=70.5% | $25.44 |
02-track-1-data-science-and-ai/part-02-classical-ml-tabular-and-domains/labs/lab-05-ecommerce-multi-stage-recsys
[build-system]
requires = ["setuptools>=68.0"]
build-backend = "setuptools.build_meta"
[project]
name = "recsys-ann-lab"
version = "0.1.0"
description = "Lab 05: kNN Distance Metrics, Curse of Dimensionality, KD-Tree/HNSW/IVF-PQ/ScaNN/Filtered Vector Search & E-Commerce Multi-Stage RecSys (T1-P2-U06)."
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
"numpy>=1.26",
"pandas>=2.2",
"pydantic>=2.0",
"scikit-learn>=1.4",
"scipy>=1.12",
]
[project.optional-dependencies]
dev = [
"pytest>=8.0",
"ruff>=0.6",
"mypy>=1.11",
]
[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 05: kNN Exact Metrics, SOTA Vector Retrieval (HNSW/IVF-PQ/ScaNN) & Multi-Stage E-Commerce RecSys."""
from recsys_ann_lab.distance_and_ann import (
ExactKNNClassifier,
HNSWConfig,
HNSWIndex,
IVFPQConfig,
IVFPQIndex,
KDTreeConfig,
KDTreeIndex,
KNNConfig,
analyze_curse_of_dimensionality,
benchmark_hnsw_ef_pareto,
benchmark_scale_trap_mahalanobis,
scann_anisotropic_mips_demo,
select_k_via_cv,
verify_filtered_search_selectivity,
)
from recsys_ann_lab.multistage_recsys import (
ECommerceDataset,
MMRConfig,
MultiSourceRetriever,
PlattCalibrator,
PointInTimeRanker,
RankerConfig,
RecSysDatasetConfig,
RetrievalConfig,
audit_temporal_vs_loo_leakage,
generate_ecommerce_sessions,
mmr_rerank,
run_full_ch11_lab05_benchmarks,
split_global_temporal,
split_leave_one_out_leaky,
)
__all__ = [
"ExactKNNClassifier",
"HNSWConfig",
"HNSWIndex",
"IVFPQConfig",
"IVFPQIndex",
"KDTreeConfig",
"KDTreeIndex",
"KNNConfig",
"analyze_curse_of_dimensionality",
"benchmark_hnsw_ef_pareto",
"benchmark_scale_trap_mahalanobis",
"scann_anisotropic_mips_demo",
"select_k_via_cv",
"verify_filtered_search_selectivity",
"ECommerceDataset",
"MMRConfig",
"MultiSourceRetriever",
"PlattCalibrator",
"PointInTimeRanker",
"RankerConfig",
"RecSysDatasetConfig",
"RetrievalConfig",
"audit_temporal_vs_loo_leakage",
"generate_ecommerce_sessions",
"mmr_rerank",
"run_full_ch11_lab05_benchmarks",
"split_global_temporal",
"split_leave_one_out_leaky",
]
"""Distance metrics, Curse of Dimensionality, Exact kNN, KD-Tree, HNSW, IVF-PQ, ScaNN & Filtered Search."""
from __future__ import annotations
import heapq
import math
from dataclasses import dataclass
from typing import Any, Literal
import numpy as np
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
from sklearn.cluster import KMeans
from sklearn.neighbors import KDTree as SklearnKDTree
from sklearn.neighbors import KNeighborsClassifier
FloatArray = NDArray[np.float64]
IntArray = NDArray[np.int64]
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Configuration Contracts
# ---------------------------------------------------------------------------
class KNNConfig(BaseModel):
"""Configuration for ExactKNNClassifier."""
model_config = ConfigDict(frozen=True, extra="forbid")
k: int = Field(default=5, ge=1, le=501)
metric: Literal["l2", "l1", "cosine", "mahalanobis"] = "l2"
weighted: bool = False
standardize: bool = False
shrinkage: float = Field(default=0.05, ge=0.0, le=1.0)
class KDTreeConfig(BaseModel):
"""Configuration for Tier 1 Reference KDTreeIndex."""
model_config = ConfigDict(frozen=True, extra="forbid")
leaf_size: int = Field(default=16, ge=1, le=256)
class HNSWConfig(BaseModel):
"""Configuration for Tier 1 Reference HNSWIndex."""
model_config = ConfigDict(frozen=True, extra="forbid")
m_links: int = Field(default=16, ge=2, le=128)
ef_construction: int = Field(default=64, ge=4, le=1024)
ef_search: int = Field(default=40, ge=1, le=1024)
metric: Literal["l2", "cosine"] = "l2"
seed: int = 42
class IVFPQConfig(BaseModel):
"""Configuration for Tier 1 Reference IVFPQIndex."""
model_config = ConfigDict(frozen=True, extra="forbid")
n_lists: int = Field(default=16, ge=2, le=4096)
m_subspaces: int = Field(default=8, ge=1, le=256)
n_centroids: int = Field(default=16, ge=2, le=256)
nprobe: int = Field(default=4, ge=1, le=4096)
rescore_top_m: int = Field(default=0, ge=0, le=1000)
seed: int = 42
# ---------------------------------------------------------------------------
# 1. Curse of Dimensionality Analyzer
# ---------------------------------------------------------------------------
def analyze_curse_of_dimensionality(
dims: tuple[int, ...] = (2, 8, 32, 128, 512),
n_points: int = 400,
shell_eps: float = 0.05,
n_queries: int = 16,
intrinsic_dim: int = 8,
seed: int = 42,
) -> list[dict[str, float]]:
"""Measure Beyer contrast decay, hypershell concentration & manifold contrast preservation."""
rng = np.random.default_rng(seed)
rows: list[dict[str, float]] = []
for d in dims:
shell_fraction = 1.0 - (1.0 - shell_eps) ** d
cube_corner_dist = math.sqrt(float(d))
# Isotropic Gaussian cloud: Beyer conditions hold -> contrast collapses as d^{-1/2}
X_iso = rng.normal(0.0, 1.0, size=(n_points, d))
Q_iso = rng.normal(0.0, 1.0, size=(n_queries, d))
dists_iso = np.linalg.norm(Q_iso[:, None, :] - X_iso[None, :, :], axis=2)
d_min = np.min(dists_iso, axis=1)
d_max = np.max(dists_iso, axis=1)
contrast_iso = float(np.mean((d_max - d_min) / np.maximum(d_min, 1e-12)))
ratio_min_max = float(np.mean(d_min / np.maximum(d_max, 1e-12)))
mean_d_iso = np.maximum(np.mean(dists_iso, axis=1), 1e-12)
rel_std_iso = float(np.mean(np.std(dists_iso, axis=1) / mean_d_iso))
# Low-intrinsic-dimensional clustered manifold embedded orthogonally into R^d
d_eff = min(d, intrinsic_dim)
basis_raw = rng.normal(0.0, 1.0, size=(d_eff, d))
q_orth, _ = np.linalg.qr(basis_raw.T)
proj = q_orth[:, :d_eff].T # (d_eff, d) orthogonal projection
centers_lat = rng.normal(0.0, 3.0, size=(6, d_eff))
cluster_ids = rng.integers(0, 6, size=n_points)
X_lat = centers_lat[cluster_ids] + rng.normal(0.0, 0.35, size=(n_points, d_eff))
q_cids = rng.integers(0, 6, size=n_queries)
Q_lat = centers_lat[q_cids] + rng.normal(0.0, 0.35, size=(n_queries, d_eff))
X_man = X_lat @ proj + rng.normal(0.0, 0.02, size=(n_points, d))
Q_man = Q_lat @ proj + rng.normal(0.0, 0.02, size=(n_queries, d))
dists_man = np.linalg.norm(Q_man[:, None, :] - X_man[None, :, :], axis=2)
m_min = np.min(dists_man, axis=1)
m_max = np.max(dists_man, axis=1)
contrast_man = float(np.mean((m_max - m_min) / np.maximum(m_min, 1e-12)))
rows.append(
{
"dim": float(d),
"shell_volume_frac": float(shell_fraction),
"cube_corner_dist": float(cube_corner_dist),
"iso_d_min": float(np.mean(d_min)),
"iso_d_max": float(np.mean(d_max)),
"iso_contrast_ratio": contrast_iso,
"iso_d_min_over_d_max": ratio_min_max,
"iso_rel_std": rel_std_iso,
"manifold_contrast_ratio": contrast_man,
}
)
return rows
# ---------------------------------------------------------------------------
# 2. Exact k-NN Classifier, Scale Trap & CV k-Selection
# ---------------------------------------------------------------------------
class ExactKNNClassifier:
"""Exact k-NN classifier supporting L2, L1, Cosine, and shrinkage Mahalanobis metrics."""
def __init__(self, config: KNNConfig | None = None) -> None:
self.config = config or KNNConfig()
self.X_train_: FloatArray | None = None
self.y_train_: IntArray | None = None
self.classes_: IntArray | None = None
self.mean_: FloatArray | None = None
self.scale_: FloatArray | None = None
self.whiten_: FloatArray | None = None
def _transform(self, X: FloatArray) -> FloatArray:
arr = np.asarray(X, dtype=np.float64)
if self.config.metric == "mahalanobis":
assert self.mean_ is not None and self.scale_ is not None and self.whiten_ is not None
z = (arr - self.mean_) / self.scale_
return z @ self.whiten_.T
if self.config.standardize:
assert self.mean_ is not None and self.scale_ is not None
arr = (arr - self.mean_) / self.scale_
if self.config.metric == "cosine":
norms = np.linalg.norm(arr, axis=1, keepdims=True)
arr = arr / np.maximum(norms, 1e-12)
return arr
def fit(self, X: FloatArray, y: IntArray) -> ExactKNNClassifier:
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64)
self.y_train_ = y_arr
self.classes_ = np.unique(y_arr)
if self.config.standardize or self.config.metric == "mahalanobis":
self.mean_ = np.mean(X_arr, axis=0)
std = np.std(X_arr, axis=0)
self.scale_ = np.where(std > 1e-12, std, 1.0)
if self.config.metric == "mahalanobis":
assert self.mean_ is not None and self.scale_ is not None
Z = (X_arr - self.mean_) / self.scale_
# Shrink correlation matrix toward I_d so scale invariance holds cleanly
cov = np.cov(Z, rowvar=False, bias=False) if Z.shape[0] > 1 else np.eye(Z.shape[1])
if cov.ndim == 0:
cov = np.array([[float(cov)]], dtype=np.float64)
s = self.config.shrinkage
cov_reg = (1.0 - s) * cov + s * np.eye(Z.shape[1], dtype=np.float64)
eigvals, eigvecs = np.linalg.eigh(cov_reg)
eigvals_safe = np.maximum(eigvals, 1e-9)
self.whiten_ = (eigvecs / np.sqrt(eigvals_safe)) @ eigvecs.T
self.X_train_ = self._transform(X_arr)
return self
def pairwise_distances(self, X_query: FloatArray) -> FloatArray:
assert self.X_train_ is not None
Q = self._transform(X_query)
T = self.X_train_
if self.config.metric == "l1":
return np.sum(np.abs(Q[:, None, :] - T[None, :, :]), axis=2)
if self.config.metric == "cosine":
sim = np.clip(Q @ T.T, -1.0, 1.0)
return 1.0 - sim
# L2 & Mahalanobis (already whitened into Euclidean space)
q_sq = np.sum(Q * Q, axis=1, keepdims=True)
t_sq = np.sum(T * T, axis=1, keepdims=True).T
sq_dists = np.maximum(q_sq + t_sq - 2.0 * (Q @ T.T), 0.0)
return np.sqrt(sq_dists)
def kneighbors(self, X_query: FloatArray, k: int | None = None) -> tuple[FloatArray, IntArray]:
assert self.X_train_ is not None
k_use = min(k or self.config.k, self.X_train_.shape[0])
dists = self.pairwise_distances(X_query)
idx_part = np.argpartition(dists, kth=k_use - 1, axis=1)[:, :k_use]
row_idx = np.arange(dists.shape[0])[:, None]
part_dists = dists[row_idx, idx_part]
order = np.argsort(part_dists, axis=1)
sorted_idx = idx_part[row_idx, order]
sorted_dists = part_dists[row_idx, order]
return sorted_dists, sorted_idx
def predict(self, X_query: FloatArray) -> IntArray:
assert self.y_train_ is not None and self.classes_ is not None
dists, indices = self.kneighbors(X_query, self.config.k)
preds = np.empty(indices.shape[0], dtype=np.int64)
for i in range(indices.shape[0]):
nbr_labels = self.y_train_[indices[i]]
if self.config.weighted:
w = 1.0 / np.maximum(dists[i], 1e-9)
scores = {int(c): float(np.sum(w[nbr_labels == c])) for c in self.classes_}
else:
scores = {int(c): float(np.sum(nbr_labels == c)) for c in self.classes_}
preds[i] = max(scores, key=lambda c: (scores[c], -c))
return preds
def score_accuracy(self, X_query: FloatArray, y_true: IntArray) -> float:
preds = self.predict(X_query)
return float(np.mean(preds == np.asarray(y_true, dtype=np.int64)))
def select_k_via_cv(
X: FloatArray,
y: IntArray,
k_candidates: tuple[int, ...] = (1, 3, 5, 9, 15, 25),
n_folds: int = 5,
metric: Literal["l2", "l1", "cosine", "mahalanobis"] = "l2",
standardize: bool = True,
seed: int = 42,
) -> dict[str, Any]:
"""Select k via stratified OOF cross-validation (exposing the k=1 training-error trap)."""
rng = np.random.default_rng(seed)
X_arr = np.asarray(X, dtype=np.float64)
y_arr = np.asarray(y, dtype=np.int64)
n = X_arr.shape[0]
perm = rng.permutation(n)
folds = np.array_split(perm, n_folds)
curve: list[dict[str, float]] = []
for k in k_candidates:
# In-sample resubstitution accuracy trap (k=1 always gets 1.000!)
insample_clf = ExactKNNClassifier(
KNNConfig(k=k, metric=metric, standardize=standardize)
).fit(X_arr, y_arr)
train_err = 1.0 - insample_clf.score_accuracy(X_arr, y_arr)
fold_errs: list[float] = []
for f_idx in range(n_folds):
val_idx = folds[f_idx]
tr_idx = np.concatenate([folds[j] for j in range(n_folds) if j != f_idx])
clf = ExactKNNClassifier(
KNNConfig(k=k, metric=metric, standardize=standardize)
).fit(X_arr[tr_idx], y_arr[tr_idx])
fold_errs.append(1.0 - clf.score_accuracy(X_arr[val_idx], y_arr[val_idx]))
mean_cv_err = float(np.mean(fold_errs))
se_cv_err = float(np.std(fold_errs, ddof=1) / math.sqrt(n_folds))
curve.append(
{
"k": float(k),
"train_resub_error": float(train_err),
"cv_error": mean_cv_err,
"cv_se": se_cv_err,
}
)
best_row = min(curve, key=lambda r: (r["cv_error"], r["k"]))
return {
"best_k": int(best_row["k"]),
"best_cv_error": float(best_row["cv_error"]),
"k1_train_error": float(curve[0]["train_resub_error"]),
"k1_cv_error": float(curve[0]["cv_error"]),
"elbow_curve": curve,
}
def benchmark_scale_trap_mahalanobis(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Compare raw L2 vs standardized L2 vs Mahalanobis on skewed + correlated features & CV k."""
rng = np.random.default_rng(seed)
n_train = 360 if quick else 540
n_test = 180 if quick else 260
n_total = n_train + n_test
# Class 0 & 1 share correlated elliptical manifold (corr=0.88) in dims 1..3 + skewed distraction dim 0
y = rng.integers(0, 2, size=n_total)
z1 = rng.normal(0.0, 2.2, size=n_total)
z2 = 0.88 * z1 + rng.normal(0.0, 0.35, size=n_total)
z_sep = np.where(y == 1, 0.55, -0.55) + rng.normal(0.0, 0.32, size=n_total)
# Transform signal strictly perpendicular/diagonal to correlated noise
f1 = z1
f2 = z2 + z_sep
f3 = 0.75 * z1 + 0.65 * z_sep + rng.normal(0.0, 0.25, size=n_total)
# High-scale uninformative price/volume nuisance feature (std ~ 2500)
f0_skewed = rng.normal(12000.0, 2500.0, size=n_total) + np.where(y == 1, 60.0, -60.0)
X = np.column_stack([f0_skewed, f1, f2, f3])
X_tr, y_tr = X[:n_train], y[:n_train]
X_te, y_te = X[n_train:], y[n_train:]
acc_raw_l2 = ExactKNNClassifier(
KNNConfig(k=7, metric="l2", standardize=False)
).fit(X_tr, y_tr).score_accuracy(X_te, y_te)
acc_std_l2 = ExactKNNClassifier(
KNNConfig(k=7, metric="l2", standardize=True)
).fit(X_tr, y_tr).score_accuracy(X_te, y_te)
acc_l1_std = ExactKNNClassifier(
KNNConfig(k=7, metric="l1", standardize=True)
).fit(X_tr, y_tr).score_accuracy(X_te, y_te)
acc_mahal = ExactKNNClassifier(
KNNConfig(k=7, metric="mahalanobis", standardize=True, shrinkage=0.02)
).fit(X_tr, y_tr).score_accuracy(X_te, y_te)
# Tier 2 sklearn parity check on raw L2
sk_knn = KNeighborsClassifier(n_neighbors=7, metric="euclidean").fit(X_tr, y_tr)
sk_acc = float(sk_knn.score(X_te, y_te))
# Noisy Cover-Hart & Elbow CV experiment (Bayes risk ~ 13%)
n_cv = 320 if quick else 480
X_cv = rng.normal(0.0, 1.0, size=(n_cv, 3))
logits = 1.45 * X_cv[:, 0] - 1.15 * X_cv[:, 1] + 0.55 * X_cv[:, 2]
probs = 1.0 / (1.0 + np.exp(-logits))
y_cv = (rng.random(n_cv) < probs).astype(np.int64)
bayes_risk = float(np.mean(np.minimum(probs, 1.0 - probs)))
cv_summary = select_k_via_cv(
X_cv, y_cv, k_candidates=(1, 3, 5, 9, 15, 25), n_folds=5, metric="l2", standardize=True, seed=seed
)
return {
"raw_l2_acc": float(acc_raw_l2),
"std_l2_acc": float(acc_std_l2),
"std_l1_acc": float(acc_l1_std),
"mahalanobis_acc": float(acc_mahal),
"sklearn_raw_l2_acc": sk_acc,
"bayes_risk_est": bayes_risk,
"cover_hart_upper_bound": float(2.0 * bayes_risk * (1.0 - bayes_risk)),
"cv_k_selection": cv_summary,
}
# ---------------------------------------------------------------------------
# 3. Tier 1 Reference KD-Tree & High-Dimensional Collapse Check
# ---------------------------------------------------------------------------
@dataclass
class _KDNode:
bounds_min: FloatArray
bounds_max: FloatArray
split_dim: int | None = None
split_val: float = 0.0
indices: IntArray | None = None
left: _KDNode | None = None
right: _KDNode | None = None
class KDTreeIndex:
"""Exact recursive median-split KD-Tree with branch-and-bound distance-eval tracking."""
def __init__(self, config: KDTreeConfig | None = None) -> None:
self.config = config or KDTreeConfig()
self.X_: FloatArray | None = None
self.root_: _KDNode | None = None
def _build_node(self, idx: IntArray) -> _KDNode:
assert self.X_ is not None
pts = self.X_[idx]
b_min = np.min(pts, axis=0)
b_max = np.max(pts, axis=0)
if idx.shape[0] <= self.config.leaf_size:
return _KDNode(bounds_min=b_min, bounds_max=b_max, indices=idx)
spread = b_max - b_min
split_dim = int(np.argmax(spread))
if spread[split_dim] <= 1e-12:
return _KDNode(bounds_min=b_min, bounds_max=b_max, indices=idx)
order = np.argsort(pts[:, split_dim], kind="mergesort")
mid = order.shape[0] // 2
split_val = float(pts[order[mid], split_dim])
left_idx = idx[order[:mid]]
right_idx = idx[order[mid:]]
return _KDNode(
bounds_min=b_min,
bounds_max=b_max,
split_dim=split_dim,
split_val=split_val,
left=self._build_node(left_idx),
right=self._build_node(right_idx),
)
def build(self, X: FloatArray) -> KDTreeIndex:
self.X_ = np.asarray(X, dtype=np.float64)
idx = np.arange(self.X_.shape[0], dtype=np.int64)
self.root_ = self._build_node(idx)
return self
@staticmethod
def _aabb_sq_dist(q: FloatArray, b_min: FloatArray, b_max: FloatArray) -> float:
delta = np.maximum(0.0, np.maximum(b_min - q, q - b_max))
return float(np.dot(delta, delta))
def query(self, q: FloatArray, k: int = 10) -> tuple[IntArray, FloatArray, int]:
assert self.X_ is not None and self.root_ is not None
q_arr = np.asarray(q, dtype=np.float64)
heap: list[tuple[float, int]] = [] # max-heap via negated squared distances
dist_evals = 0
def _visit(node: _KDNode) -> None:
nonlocal dist_evals
if node.indices is not None:
pts = self.X_[node.indices] # type: ignore[index]
diffs = pts - q_arr
sq_ds = np.sum(diffs * diffs, axis=1)
dist_evals += int(node.indices.shape[0])
for pt_idx, sq_d in zip(node.indices.tolist(), sq_ds.tolist(), strict=True):
if len(heap) < k:
heapq.heappush(heap, (-sq_d, pt_idx))
elif sq_d < -heap[0][0]:
heapq.heapreplace(heap, (-sq_d, pt_idx))
return
assert node.split_dim is not None and node.left is not None and node.right is not None
if q_arr[node.split_dim] <= node.split_val:
near, far = node.left, node.right
else:
near, far = node.right, node.left
_visit(near)
tau_sq = -heap[0][0] if len(heap) == k else math.inf
if self._aabb_sq_dist(q_arr, far.bounds_min, far.bounds_max) < tau_sq:
_visit(far)
_visit(self.root_)
res = sorted((-neg_d, idx) for neg_d, idx in heap)
out_idx = np.array([idx for _, idx in res], dtype=np.int64)
out_dist = np.sqrt(np.array([max(0.0, sq_d) for sq_d, _ in res], dtype=np.float64))
return out_idx, out_dist, dist_evals
def benchmark_kdtree_collapse(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Compare KD-Tree exact parity with sklearn and contrast d=4 pruning vs d=64 collapse."""
rng = np.random.default_rng(seed)
n_pts = 600 if quick else 1000
n_q = 20 if quick else 30
k = 10
results: dict[str, Any] = {}
for dim in (4, 64):
X = rng.normal(0.0, 1.0, size=(n_pts, dim))
Q = rng.normal(0.0, 1.0, size=(n_q, dim))
kd = KDTreeIndex(KDTreeConfig(leaf_size=16)).build(X)
sk_kd = SklearnKDTree(X, leaf_size=16)
sk_dists, sk_idx = sk_kd.query(Q, k=k)
eval_fracs: list[float] = []
recalls: list[float] = []
for qi in range(n_q):
idx_got, _, evals = kd.query(Q[qi], k=k)
eval_fracs.append(evals / float(n_pts))
recalls.append(len(set(idx_got.tolist()) & set(sk_idx[qi].tolist())) / float(k))
results[f"d{dim}"] = {
"dim": dim,
"n_points": n_pts,
"mean_visit_frac": float(np.mean(eval_fracs)),
"exact_recall_at_10": float(np.mean(recalls)),
}
return results
# ---------------------------------------------------------------------------
# 4. Tier 1 Reference HNSW Index & Filtered Vector Search
# ---------------------------------------------------------------------------
class HNSWIndex:
"""Navigable Small-World multi-layer graph (Malkov & Yashunin, TPAMI 2020)."""
def __init__(self, config: HNSWConfig | None = None) -> None:
self.config = config or HNSWConfig()
self.X_: FloatArray | None = None
self.levels_: IntArray | None = None
self.layers_: list[dict[int, list[int]]] = []
self.entry_point_: int = -1
self.max_level_: int = -1
def _prepare(self, X: FloatArray) -> FloatArray:
arr = np.asarray(X, dtype=np.float64)
if self.config.metric == "cosine":
norms = np.linalg.norm(arr, axis=1, keepdims=True)
arr = arr / np.maximum(norms, 1e-12)
return arr
def _dist_pair(self, q: FloatArray, node_id: int) -> float:
assert self.X_ is not None
if self.config.metric == "cosine":
return float(max(0.0, 1.0 - np.dot(q, self.X_[node_id])))
diff = q - self.X_[node_id]
return float(np.dot(diff, diff))
def _search_layer(
self,
q: FloatArray,
entry_ids: list[int],
ef: int,
level: int,
dist_cache: dict[int, float] | None = None,
) -> tuple[list[tuple[float, int]], int]:
visited: set[int] = set()
candidates: list[tuple[float, int]] = [] # min-heap
results: list[tuple[float, int]] = [] # max-heap (negated dist)
evals = 0
graph = self.layers_[level]
def get_dist(nid: int) -> float:
nonlocal evals
if dist_cache is not None and nid in dist_cache:
return dist_cache[nid]
d = self._dist_pair(q, nid)
evals += 1
if dist_cache is not None:
dist_cache[nid] = d
return d
for ep in entry_ids:
if ep not in visited:
visited.add(ep)
d = get_dist(ep)
heapq.heappush(candidates, (d, ep))
heapq.heappush(results, (-d, ep))
if len(results) > ef:
heapq.heappop(results)
while candidates:
c_dist, c_id = heapq.heappop(candidates)
worst_res = -results[0][0]
if c_dist > worst_res and len(results) >= ef:
break
for nb in graph.get(c_id, ()):
if nb in visited:
continue
visited.add(nb)
d_nb = get_dist(nb)
worst_res = -results[0][0]
if len(results) < ef or d_nb < worst_res:
heapq.heappush(candidates, (d_nb, nb))
heapq.heappush(results, (-d_nb, nb))
if len(results) > ef:
heapq.heappop(results)
ordered = sorted((-nd, nid) for nd, nid in results)
return ordered, evals
def _select_neighbors_heuristic(
self,
q_node_vec: FloatArray,
cands: list[tuple[float, int]],
m_max: int,
) -> list[int]:
assert self.X_ is not None
selected: list[int] = []
discarded: list[tuple[float, int]] = []
for d_e, e_id in sorted(cands):
if len(selected) >= m_max:
break
e_vec = self.X_[e_id]
closer_to_query = True
for r_id in selected:
if self.config.metric == "cosine":
d_er = max(0.0, 1.0 - float(np.dot(e_vec, self.X_[r_id])))
else:
diff = e_vec - self.X_[r_id]
d_er = float(np.dot(diff, diff))
if d_er < d_e:
closer_to_query = False
break
if closer_to_query:
selected.append(e_id)
else:
discarded.append((d_e, e_id))
# Keep connectivity if heuristic left slots open
for _, e_id in discarded:
if len(selected) >= m_max:
break
selected.append(e_id)
return selected
def build(self, X: FloatArray) -> HNSWIndex:
self.X_ = self._prepare(X)
n = self.X_.shape[0]
rng = np.random.default_rng(self.config.seed)
m_links = self.config.m_links
m_max0 = 2 * m_links
m_l = 1.0 / math.log(m_links)
levels = np.array(
[int(-math.log(max(float(rng.random()), 1e-12)) * m_l) for _ in range(n)],
dtype=np.int64,
)
self.levels_ = levels
max_lvl = int(np.max(levels))
self.layers_ = [{} for _ in range(max_lvl + 1)]
self.entry_point_ = 0
self.max_level_ = int(levels[0])
for l_idx in range(self.max_level_ + 1):
self.layers_[l_idx][0] = []
for node_id in range(1, n):
node_lvl = int(levels[node_id])
for l_idx in range(node_lvl + 1):
self.layers_[l_idx][node_id] = []
cur_ep = [self.entry_point_]
vec = self.X_[node_id]
for l_idx in range(self.max_level_, node_lvl, -1):
res, _ = self._search_layer(vec, cur_ep, ef=1, level=l_idx)
cur_ep = [res[0][1]]
for l_idx in range(min(node_lvl, self.max_level_), -1, -1):
res, _ = self._search_layer(
vec, cur_ep, ef=self.config.ef_construction, level=l_idx
)
m_cap = m_max0 if l_idx == 0 else m_links
chosen = self._select_neighbors_heuristic(vec, res, m_cap)
self.layers_[l_idx][node_id] = chosen
for nb in chosen:
nb_list = self.layers_[l_idx][nb]
if node_id not in nb_list:
nb_list.append(node_id)
if len(nb_list) > m_cap:
nb_vec = self.X_[nb]
nb_cands = [(self._dist_pair(nb_vec, x), x) for x in nb_list]
self.layers_[l_idx][nb] = self._select_neighbors_heuristic(
nb_vec, nb_cands, m_cap
)
if res:
cur_ep = [res[0][1]]
if node_lvl > self.max_level_:
self.max_level_ = node_lvl
self.entry_point_ = node_id
return self
def memory_bytes_per_vector(self) -> float:
"""Exact fp32 vector + Layer-0/upper graph link memory footprint in bytes/vector."""
assert self.X_ is not None and self.levels_ is not None
dim = self.X_.shape[1]
m = self.config.m_links
avg_upper = 1.0 / max(m - 1, 1)
return float(4 * dim + 8 * m + 4 * m * avg_upper)
def search(
self,
q: FloatArray,
k: int = 10,
ef_search: int | None = None,
allowed_mask: NDArray[np.bool_] | None = None,
filter_mode: Literal["none", "post_filter", "iterative_scan", "pre_filter_graph"] = "none",
max_scan_nodes: int = 2000,
) -> tuple[IntArray, FloatArray, int]:
assert self.X_ is not None and self.entry_point_ >= 0
q_prep = np.asarray(q, dtype=np.float64)
if self.config.metric == "cosine":
q_prep = q_prep / max(float(np.linalg.norm(q_prep)), 1e-12)
ef = max(k, ef_search or self.config.ef_search)
cur_ep = [self.entry_point_]
total_evals = 0
cache: dict[int, float] = {}
for l_idx in range(self.max_level_, 0, -1):
res, ev = self._search_layer(q_prep, cur_ep, ef=1, level=l_idx, dist_cache=cache)
total_evals += ev
cur_ep = [res[0][1]]
if filter_mode == "none" or allowed_mask is None:
res0, ev0 = self._search_layer(q_prep, cur_ep, ef=ef, level=0, dist_cache=cache)
total_evals += ev0
top = res0[:k]
return (
np.array([nid for _, nid in top], dtype=np.int64),
np.array([d for d, _ in top], dtype=np.float64),
total_evals,
)
if filter_mode == "post_filter":
res0, ev0 = self._search_layer(q_prep, cur_ep, ef=ef, level=0, dist_cache=cache)
total_evals += ev0
filtered = [(d, nid) for d, nid in res0 if bool(allowed_mask[nid])][:k]
return (
np.array([nid for _, nid in filtered], dtype=np.int64),
np.array([d for d, _ in filtered], dtype=np.float64),
total_evals,
)
if filter_mode == "pre_filter_graph":
# Restrict Layer-0 graph hops strictly to matching nodes -> island disconnection!
graph0 = self.layers_[0]
visited: set[int] = set()
candidates: list[tuple[float, int]] = []
results: list[tuple[float, int]] = []
seeds = [ep for ep in cur_ep if bool(allowed_mask[ep])]
if not seeds:
# Try 1-hop neighbors of entry point that pass filter
for nb in graph0.get(cur_ep[0], ()):
if bool(allowed_mask[nb]):
seeds.append(nb)
break
for ep in seeds:
visited.add(ep)
d = cache.get(ep)
if d is None:
d = self._dist_pair(q_prep, ep)
total_evals += 1
cache[ep] = d
heapq.heappush(candidates, (d, ep))
heapq.heappush(results, (-d, ep))
while candidates:
c_dist, c_id = heapq.heappop(candidates)
if len(results) >= ef and c_dist > -results[0][0]:
break
for nb in graph0.get(c_id, ()):
if nb in visited or not bool(allowed_mask[nb]):
continue
visited.add(nb)
d_nb = cache.get(nb)
if d_nb is None:
d_nb = self._dist_pair(q_prep, nb)
total_evals += 1
cache[nb] = d_nb
if len(results) < ef or d_nb < -results[0][0]:
heapq.heappush(candidates, (d_nb, nb))
heapq.heappush(results, (-d_nb, nb))
if len(results) > ef:
heapq.heappop(results)
ordered = sorted((-nd, nid) for nd, nid in results)[:k]
return (
np.array([nid for _, nid in ordered], dtype=np.int64),
np.array([d for d, _ in ordered], dtype=np.float64),
total_evals,
)
# iterative_scan (pgvector 0.8+ relaxed_order / ACORN): route across all nodes
graph0 = self.layers_[0]
visited_it: set[int] = set()
cand_it: list[tuple[float, int]] = []
matched_res: list[tuple[float, int]] = []
for ep in cur_ep:
visited_it.add(ep)
d = cache.get(ep)
if d is None:
d = self._dist_pair(q_prep, ep)
total_evals += 1
cache[ep] = d
heapq.heappush(cand_it, (d, ep))
if bool(allowed_mask[ep]):
heapq.heappush(matched_res, (-d, ep))
scanned = 0
target_beam = max(k * 2, ef)
while cand_it and scanned < max_scan_nodes:
c_dist, c_id = heapq.heappop(cand_it)
scanned += 1
if len(matched_res) >= target_beam and c_dist > -matched_res[0][0]:
break
for nb in graph0.get(c_id, ()):
if nb in visited_it:
continue
visited_it.add(nb)
d_nb = cache.get(nb)
if d_nb is None:
d_nb = self._dist_pair(q_prep, nb)
total_evals += 1
cache[nb] = d_nb
heapq.heappush(cand_it, (d_nb, nb))
if bool(allowed_mask[nb]):
heapq.heappush(matched_res, (-d_nb, nb))
if len(matched_res) > target_beam:
heapq.heappop(matched_res)
ordered_it = sorted((-nd, nid) for nd, nid in matched_res)[:k]
return (
np.array([nid for _, nid in ordered_it], dtype=np.int64),
np.array([d for d, _ in ordered_it], dtype=np.float64),
total_evals,
)
def benchmark_hnsw_ef_pareto(
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Sweep HNSW ef_search Pareto frontier (Recall@10 vs visited distance evals & RAM)."""
rng = np.random.default_rng(seed)
n_vecs = 520 if quick else 960
dim = 32
n_queries = 20 if quick else 32
k = 10
# Clustered manifold with realistic overlap so efSearch exhibits a smooth Pareto curve
centers = rng.normal(0.0, 1.5, size=(16, dim))
labels = rng.integers(0, 16, size=n_vecs)
X = centers[labels] + rng.normal(0.0, 0.90, size=(n_vecs, dim))
q_labels = rng.integers(0, 16, size=n_queries)
Q = centers[q_labels] + rng.normal(0.0, 0.90, size=(n_queries, dim))
# Ground-truth exact nearest neighbors
gt_dists = np.sum((Q[:, None, :] - X[None, :, :]) ** 2, axis=2)
gt_idx = np.argpartition(gt_dists, kth=k - 1, axis=1)[:, :k]
index = HNSWIndex(HNSWConfig(m_links=12, ef_construction=40, ef_search=32, seed=seed)).build(X)
pareto_rows: list[dict[str, float]] = []
for ef in (10, 20, 40, 64, 96):
recalls: list[float] = []
evals: list[int] = []
for qi in range(n_queries):
got_idx, _, ev = index.search(Q[qi], k=k, ef_search=ef)
recalls.append(len(set(got_idx.tolist()) & set(gt_idx[qi].tolist())) / float(k))
evals.append(ev)
pareto_rows.append(
{
"ef_search": float(ef),
"recall_at_10": float(np.mean(recalls)),
"mean_dist_evals": float(np.mean(evals)),
"scan_frac": float(np.mean(evals) / n_vecs),
}
)
return {
"n_vectors": n_vecs,
"dim": dim,
"m_links": 12,
"bytes_per_vector": index.memory_bytes_per_vector(),
"raw_fp32_bytes_per_vector": float(4 * dim),
"pareto_sweep": pareto_rows,
}
def verify_filtered_search_selectivity(
selectivity: float = 0.02,
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Compare Post-Filter starvation vs Pre-Filter disconnect vs Iterative Scan at 2% selectivity."""
rng = np.random.default_rng(seed)
n_vecs = 500 if quick else 800
dim = 24
n_queries = 15 if quick else 25
k = 10
centers = rng.normal(0.0, 1.8, size=(10, dim))
X = centers[rng.integers(0, 10, size=n_vecs)] + rng.normal(0.0, 0.5, size=(n_vecs, dim))
Q = centers[rng.integers(0, 10, size=n_queries)] + rng.normal(0.0, 0.5, size=(n_queries, dim))
# Assign exact target fraction matching filter (guaranteed >= k items globally)
n_match = max(k + 5, int(round(selectivity * n_vecs)))
allowed = np.zeros(n_vecs, dtype=bool)
allowed[rng.choice(n_vecs, size=n_match, replace=False)] = True
allowed_ids = np.flatnonzero(allowed)
index = HNSWIndex(HNSWConfig(m_links=12, ef_construction=48, ef_search=32, seed=seed)).build(X)
post_recalls: list[float] = []
pre_recalls: list[float] = []
iter_recalls: list[float] = []
post_counts: list[int] = []
iter_evals: list[int] = []
for qi in range(n_queries):
sub_dists = np.sum((X[allowed_ids] - Q[qi]) ** 2, axis=1)
gt_filtered = set(allowed_ids[np.argsort(sub_dists)[:k]].tolist())
got_post, _, _ = index.search(
Q[qi], k=k, ef_search=32, allowed_mask=allowed, filter_mode="post_filter"
)
got_pre, _, _ = index.search(
Q[qi], k=k, ef_search=32, allowed_mask=allowed, filter_mode="pre_filter_graph"
)
got_it, _, ev_it = index.search(
Q[qi],
k=k,
ef_search=32,
allowed_mask=allowed,
filter_mode="iterative_scan",
max_scan_nodes=n_vecs,
)
post_counts.append(int(got_post.shape[0]))
post_recalls.append(len(set(got_post.tolist()) & gt_filtered) / float(k))
pre_recalls.append(len(set(got_pre.tolist()) & gt_filtered) / float(k))
iter_recalls.append(len(set(got_it.tolist()) & gt_filtered) / float(k))
iter_evals.append(ev_it)
return {
"selectivity": float(n_match / n_vecs),
"n_vectors": n_vecs,
"n_matching": int(n_match),
"ef_search": 32,
"post_filter_recall_at_10": float(np.mean(post_recalls)),
"post_filter_avg_returned": float(np.mean(post_counts)),
"pre_filter_graph_recall_at_10": float(np.mean(pre_recalls)),
"iterative_scan_recall_at_10": float(np.mean(iter_recalls)),
"iterative_scan_mean_evals": float(np.mean(iter_evals)),
}
# ---------------------------------------------------------------------------
# 5. Tier 1 Reference IVF-PQ + ADC LUT & ScaNN Anisotropic MIPS Demo
# ---------------------------------------------------------------------------
class IVFPQIndex:
"""Inverted File + Product Quantization with Residual ADC Lookup Tables (Jegou et al., TPAMI 2011)."""
def __init__(self, config: IVFPQConfig | None = None) -> None:
self.config = config or IVFPQConfig()
self.X_raw_: FloatArray | None = None
self.coarse_centroids_: FloatArray | None = None
self.inv_lists_: dict[int, IntArray] = {}
self.codebooks_: list[FloatArray] = []
self.codes_: NDArray[np.uint8] | None = None
self.dim_: int = 0
def build(self, X: FloatArray) -> IVFPQIndex:
X_arr = np.asarray(X, dtype=np.float64)
n, dim = X_arr.shape
if dim % self.config.m_subspaces != 0:
raise ValueError(f"dim={dim} must be divisible by m_subspaces={self.config.m_subspaces}")
self.dim_ = dim
self.X_raw_ = X_arr.copy()
n_lists = min(self.config.n_lists, n)
km_coarse = KMeans(n_clusters=n_lists, n_init=4, max_iter=35, random_state=self.config.seed)
coarse_labels = km_coarse.fit_predict(X_arr)
self.coarse_centroids_ = np.asarray(km_coarse.cluster_centers_, dtype=np.float64)
residuals = X_arr - self.coarse_centroids_[coarse_labels]
self.inv_lists_ = {}
for cid in range(n_lists):
self.inv_lists_[cid] = np.flatnonzero(coarse_labels == cid).astype(np.int64)
sub_dim = dim // self.config.m_subspaces
n_cent = min(self.config.n_centroids, n)
codes = np.zeros((n, self.config.m_subspaces), dtype=np.uint8)
self.codebooks_ = []
for m in range(self.config.m_subspaces):
sl = slice(m * sub_dim, (m + 1) * sub_dim)
sub_res = residuals[:, sl]
km_sub = KMeans(n_clusters=n_cent, n_init=3, max_iter=30, random_state=self.config.seed + m + 1)
sub_ids = km_sub.fit_predict(sub_res)
self.codebooks_.append(np.asarray(km_sub.cluster_centers_, dtype=np.float64))
codes[:, m] = sub_ids.astype(np.uint8)
self.codes_ = codes
return self
def memory_bytes_per_vector(self) -> float:
"""PQ compressed byte footprint per vector (M_pq uint8 codes + 4B list ID)."""
return float(self.config.m_subspaces + 4)
def compression_ratio(self) -> float:
raw_bytes = 4.0 * float(self.dim_)
return raw_bytes / float(self.config.m_subspaces)
def search(
self,
q: FloatArray,
k: int = 10,
nprobe: int | None = None,
rescore_top_m: int | None = None,
) -> tuple[IntArray, FloatArray, int]:
assert (
self.coarse_centroids_ is not None
and self.codes_ is not None
and self.X_raw_ is not None
)
q_arr = np.asarray(q, dtype=np.float64)
n_lists = self.coarse_centroids_.shape[0]
probe_cnt = min(nprobe or self.config.nprobe, n_lists)
coarse_dists = np.sum((self.coarse_centroids_ - q_arr) ** 2, axis=1)
probed_cids = np.argsort(coarse_dists)[:probe_cnt]
sub_dim = self.dim_ // self.config.m_subspaces
cand_ids_list: list[IntArray] = []
cand_adc_list: list[FloatArray] = []
for cid in probed_cids.tolist():
member_ids = self.inv_lists_.get(cid)
if member_ids is None or member_ids.shape[0] == 0:
continue
q_res = q_arr - self.coarse_centroids_[cid]
# Build M_pq x K* Asymmetric Distance Computation Lookup Table (LUT)
adc_sq = np.zeros(member_ids.shape[0], dtype=np.float64)
member_codes = self.codes_[member_ids]
for m in range(self.config.m_subspaces):
sl = slice(m * sub_dim, (m + 1) * sub_dim)
lut_m = np.sum((self.codebooks_[m] - q_res[sl]) ** 2, axis=1)
adc_sq += lut_m[member_codes[:, m]]
cand_ids_list.append(member_ids)
cand_adc_list.append(adc_sq)
if not cand_ids_list:
return np.empty(0, dtype=np.int64), np.empty(0, dtype=np.float64), 0
all_ids = np.concatenate(cand_ids_list)
all_adc = np.concatenate(cand_adc_list)
n_scanned = int(all_ids.shape[0])
rescore_m = self.config.rescore_top_m if rescore_top_m is None else rescore_top_m
if rescore_m > 0:
m_use = min(max(k, rescore_m), n_scanned)
top_m_pos = np.argpartition(all_adc, kth=m_use - 1)[:m_use]
top_m_ids = all_ids[top_m_pos]
exact_sq = np.sum((self.X_raw_[top_m_ids] - q_arr) ** 2, axis=1)
ord_idx = np.argsort(exact_sq)[:k]
return top_m_ids[ord_idx], np.sqrt(np.maximum(exact_sq[ord_idx], 0.0)), n_scanned
k_use = min(k, n_scanned)
top_k_pos = np.argpartition(all_adc, kth=k_use - 1)[:k_use]
ord_idx = np.argsort(all_adc[top_k_pos])
best_pos = top_k_pos[ord_idx]
return all_ids[best_pos], np.sqrt(np.maximum(all_adc[best_pos], 0.0)), n_scanned
def benchmark_ivf_pq_adc(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Benchmark IVF-PQ memory compression and ADC + Rescore recall tradeoff."""
rng = np.random.default_rng(seed)
n_vecs = 550 if quick else 900
dim = 64
n_queries = 20 if quick else 32
k = 10
centers = rng.normal(0.0, 1.8, size=(20, dim))
X = centers[rng.integers(0, 20, size=n_vecs)] + rng.normal(0.0, 0.55, size=(n_vecs, dim))
Q = centers[rng.integers(0, 20, size=n_queries)] + rng.normal(0.0, 0.55, size=(n_queries, dim))
gt_idx = np.argpartition(np.sum((Q[:, None, :] - X[None, :, :]) ** 2, axis=2), kth=k - 1, axis=1)[:, :k]
ivfpq = IVFPQIndex(
IVFPQConfig(n_lists=24, m_subspaces=16, n_centroids=16, nprobe=4, rescore_top_m=0, seed=seed)
).build(X)
sweep: list[dict[str, float]] = []
for nprobe, rescore in ((1, 0), (3, 0), (6, 0), (6, 30)):
recs: list[float] = []
scans: list[int] = []
for qi in range(n_queries):
got_ids, _, n_sc = ivfpq.search(Q[qi], k=k, nprobe=nprobe, rescore_top_m=rescore)
recs.append(len(set(got_ids.tolist()) & set(gt_idx[qi].tolist())) / float(k))
scans.append(n_sc)
sweep.append(
{
"nprobe": float(nprobe),
"rescore_top_m": float(rescore),
"recall_at_10": float(np.mean(recs)),
"mean_scanned": float(np.mean(scans)),
}
)
return {
"dim": dim,
"m_subspaces": 16,
"raw_fp32_bytes": float(4 * dim),
"pq_code_bytes": 16.0,
"compression_ratio": ivfpq.compression_ratio(),
"sweep": sweep,
}
def scann_anisotropic_mips_demo(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Compare Isotropic PQ vs ScaNN Anisotropic PQ (h_par >> h_perp) for MIPS."""
rng = np.random.default_rng(seed)
n_items = 450 if quick else 700
dim = 32
m_subspaces = 8
sub_dim = dim // m_subspaces
n_clusters = 12
n_queries = 40 if quick else 60
k = 10
# Heterogeneous clusters (tight vs broad spread) + radial norm variation (classic MIPS!)
centers = rng.normal(0.0, 1.0, size=(12, dim))
centers /= np.maximum(np.linalg.norm(centers, axis=1, keepdims=True), 1e-12)
cids = rng.integers(0, 12, size=n_items)
c_spread = np.where(cids < 6, 0.12, 0.55)[..., None]
dirs = centers[cids] + rng.normal(0.0, 1.0, size=(n_items, dim)) * c_spread
dirs /= np.maximum(np.linalg.norm(dirs, axis=1, keepdims=True), 1e-12)
norms = rng.uniform(0.8, 2.8, size=(n_items, 1))
X = dirs * norms
# MIPS queries align with cluster centers
q_cids = rng.integers(0, 12, size=n_queries)
Q = centers[q_cids] + rng.normal(0.0, 0.15, size=(n_queries, dim))
# Build 8-subspace Product Quantization under Isotropic L2 vs ScaNN Anisotropic Loss
X_iso_hat = np.zeros_like(X)
X_aniso_hat = np.zeros_like(X)
h_par, h_perp = 6.0, 1.0
for m in range(m_subspaces):
sl = slice(m * sub_dim, (m + 1) * sub_dim)
X_sub = X[:, sl]
u_sub = X_sub / np.maximum(np.linalg.norm(X_sub, axis=1, keepdims=True), 1e-12)
# 1. Isotropic K-Means centroids in subspace m
km_iso = KMeans(n_clusters=n_clusters, n_init=4, max_iter=30, random_state=seed + m)
iso_labels = km_iso.fit_predict(X_sub)
C_iso = np.asarray(km_iso.cluster_centers_, dtype=np.float64)
X_iso_hat[:, sl] = C_iso[iso_labels]
# 2. ScaNN Anisotropic Quantization (Guo et al., ICML 2020) in subspace m
C_aniso = C_iso.copy()
aniso_labels = iso_labels.copy()
for _ in range(12):
diffs = X_sub[:, None, :] - C_aniso[None, :, :]
par_proj = np.sum(diffs * u_sub[:, None, :], axis=2, keepdims=True) * u_sub[:, None, :]
perp_proj = diffs - par_proj
aniso_loss = (
h_par * np.sum(par_proj**2, axis=2) + h_perp * np.sum(perp_proj**2, axis=2)
)
aniso_labels = np.argmin(aniso_loss, axis=1)
for cid in range(n_clusters):
mask = aniso_labels == cid
if not np.any(mask):
continue
pts = X_sub[mask]
u = u_sub[mask]
A = h_perp * np.eye(sub_dim) + (h_par - h_perp) * (u.T @ u) / float(pts.shape[0])
rhs = h_par * np.mean(pts, axis=0)
C_aniso[cid] = np.linalg.solve(A + 1e-8 * np.eye(sub_dim), rhs)
X_aniso_hat[:, sl] = C_aniso[aniso_labels]
# Compare MIPS inner-product distortion & Recall@10
ip_true = Q @ X.T
ip_iso = Q @ X_iso_hat.T
ip_aniso = Q @ X_aniso_hat.T
gt_top = np.argsort(-ip_true, axis=1)[:, :k]
iso_top = np.argsort(-ip_iso, axis=1)[:, :k]
aniso_top = np.argsort(-ip_aniso, axis=1)[:, :k]
iso_recalls = [
len(set(iso_top[i].tolist()) & set(gt_top[i].tolist())) / float(k) for i in range(n_queries)
]
aniso_recalls = [
len(set(aniso_top[i].tolist()) & set(gt_top[i].tolist())) / float(k) for i in range(n_queries)
]
# Measure inner-product MSE specifically on top-20 high-MIPS pairs (Guo et al. Theorem condition!)
iso_top_mse: list[float] = []
aniso_top_mse: list[float] = []
for i in range(n_queries):
hi_idx = np.argsort(-ip_true[i])[:20]
iso_top_mse.append(float(np.mean((ip_true[i, hi_idx] - ip_iso[i, hi_idx]) ** 2)))
aniso_top_mse.append(float(np.mean((ip_true[i, hi_idx] - ip_aniso[i, hi_idx]) ** 2)))
return {
"n_items": n_items,
"dim": dim,
"n_clusters": n_clusters,
"h_parallel": h_par,
"h_orthogonal": h_perp,
"isotropic_top20_mips_mse": float(np.mean(iso_top_mse)),
"anisotropic_top20_mips_mse": float(np.mean(aniso_top_mse)),
"isotropic_mips_recall_at_10": float(np.mean(iso_recalls)),
"anisotropic_mips_recall_at_10": float(np.mean(aniso_recalls)),
}
"""E-Commerce Multi-Stage Recommender System (Global Temporal Split, Two-Tower+IPS, PIT Ranker+Platt, MMR)."""
from __future__ import annotations
import math
from dataclasses import dataclass
from typing import Any
import numpy as np
import pandas as pd
from numpy.typing import NDArray
from pydantic import BaseModel, ConfigDict, Field
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import brier_score_loss
from recsys_ann_lab.distance_and_ann import (
HNSWConfig,
HNSWIndex,
analyze_curse_of_dimensionality,
benchmark_hnsw_ef_pareto,
benchmark_ivf_pq_adc,
benchmark_kdtree_collapse,
benchmark_scale_trap_mahalanobis,
scann_anisotropic_mips_demo,
verify_filtered_search_selectivity,
)
FloatArray = NDArray[np.float64]
IntArray = NDArray[np.int64]
# ---------------------------------------------------------------------------
# Strict Pydantic v2 Config Contracts
# ---------------------------------------------------------------------------
class RecSysDatasetConfig(BaseModel):
"""Configuration for synthetic e-commerce user-session dataset."""
model_config = ConfigDict(frozen=True, extra="forbid")
n_users: int = Field(default=260, ge=40, le=5000)
n_items: int = Field(default=420, ge=60, le=10000)
n_sessions: int = Field(default=1600, ge=200, le=50000)
n_categories: int = Field(default=10, ge=3, le=50)
dim: int = Field(default=16, ge=4, le=128)
class RetrievalConfig(BaseModel):
"""Configuration for Stage 1 Multi-Source Retrieval."""
model_config = ConfigDict(frozen=True, extra="forbid")
top_k_candidates: int = Field(default=200, ge=20, le=1000)
ips_alpha: float = Field(default=0.55, ge=0.0, le=1.5)
pop_penalty: float = Field(default=0.08, ge=0.0, le=2.0)
covis_weight: float = Field(default=0.85, ge=0.0, le=3.0)
use_hnsw: bool = True
class RankerConfig(BaseModel):
"""Configuration for Stage 2 Point-in-Time Feature Ranker."""
model_config = ConfigDict(frozen=True, extra="forbid")
neg_samples_per_session: int = Field(default=24, ge=4, le=100)
l2_c: float = Field(default=1.0, gt=0.0, le=100.0)
prior_ctr: float = Field(default=0.08, gt=0.0, lt=0.5)
prior_strength: float = Field(default=8.0, gt=0.0, le=100.0)
class MMRConfig(BaseModel):
"""Configuration for Stage 3 Maximal Marginal Relevance Re-ranking."""
model_config = ConfigDict(frozen=True, extra="forbid")
top_k: int = Field(default=10, ge=2, le=50)
candidate_pool_size: int = Field(default=60, ge=10, le=300)
mmr_lambda: float = Field(default=0.58, ge=0.0, le=1.0)
margin_blend: float = Field(default=0.35, ge=0.0, le=1.0)
@dataclass
class ECommerceDataset:
"""Container for e-commerce catalog, users, and ordered session interactions."""
items_df: pd.DataFrame
item_embeddings: FloatArray
user_embeddings: FloatArray
interactions_df: pd.DataFrame
# ---------------------------------------------------------------------------
# 1. Synthetic E-Commerce Benchmark & Temporal vs LOO Split
# ---------------------------------------------------------------------------
def generate_ecommerce_sessions(
config: RecSysDatasetConfig | None = None,
seed: int = 42,
) -> ECommerceDataset:
"""Generate ordered e-commerce user sessions with popularity skew, margins, and seasonal trend."""
cfg = config or RecSysDatasetConfig()
rng = np.random.default_rng(seed)
# Category prototypes in latent embedding space
cat_protos = rng.normal(0.0, 1.0, size=(cfg.n_categories, cfg.dim))
cat_protos /= np.maximum(np.linalg.norm(cat_protos, axis=1, keepdims=True), 1e-12)
item_cats = rng.integers(0, cfg.n_categories, size=cfg.n_items)
item_brands = rng.integers(0, 20, size=cfg.n_items)
raw_emb = cat_protos[item_cats] * 1.4 + rng.normal(0.0, 0.45, size=(cfg.n_items, cfg.dim))
item_emb = raw_emb / np.maximum(np.linalg.norm(raw_emb, axis=1, keepdims=True), 1e-12)
# Power-law exposure bias (MNAR: head 15% items dominate logs, carry lower unit margins)
ranks = np.arange(1, cfg.n_items + 1, dtype=np.float64)
perm_items = rng.permutation(cfg.n_items)
base_pop = np.zeros(cfg.n_items, dtype=np.float64)
base_pop[perm_items] = 1.0 / (ranks**1.20)
base_pop /= np.sum(base_pop)
is_head = base_pop > np.quantile(base_pop, 0.85)
prices = np.round(np.exp(rng.normal(3.6, 0.65, size=cfg.n_items)), 2)
margin_rate = np.where(
is_head,
rng.uniform(0.10, 0.16, size=cfg.n_items),
rng.uniform(0.25, 0.44, size=cfg.n_items),
)
margins = np.round(prices * margin_rate, 2)
items_df = pd.DataFrame(
{
"item_id": np.arange(cfg.n_items, dtype=np.int64),
"category_id": item_cats.astype(np.int64),
"brand_id": item_brands.astype(np.int64),
"price_usd": prices,
"margin_usd": margins,
"true_pop_prob": base_pop,
"is_head": is_head,
}
)
# User latent preferences across favorite category + price preference
user_fav_cat = rng.integers(0, cfg.n_categories, size=cfg.n_users)
u_raw = cat_protos[user_fav_cat] * 1.55 + rng.normal(0.0, 0.42, size=(cfg.n_users, cfg.dim))
user_emb = u_raw / np.maximum(np.linalg.norm(u_raw, axis=1, keepdims=True), 1e-12)
user_log_price_pref = rng.normal(3.6, 0.45, size=cfg.n_users)
# Seasonal trend bundle pairs emerge strictly in the final 28% of timeline (LOO leakage trap!)
n_trend = max(16, cfg.n_items // 15)
late_trend_items = rng.choice(cfg.n_items, size=n_trend, replace=False)
trend_partner: dict[int, int] = {}
for idx_t in range(len(late_trend_items)):
a = int(late_trend_items[idx_t])
b = int(late_trend_items[(idx_t + 1) % len(late_trend_items)])
trend_partner[a] = b
records: list[dict[str, Any]] = []
user_item_cos = user_emb @ item_emb.T
price_diff = np.abs(np.log(prices)[None, :] - user_log_price_pref[:, None])
# MNAR logged exposure bias in training: head items appear heavily in naive logs
log_exposure = np.log(base_pop + 1e-6)
for s_id in range(cfg.n_sessions):
ts = float(s_id)
frac = s_id / float(cfg.n_sessions)
uid = int(rng.integers(0, cfg.n_users))
is_late = frac >= 0.72
# Early logged browsing suffers MNAR exposure bias; true relevance is personalized + price-matched
exposure_w = 0.75 if frac < 0.65 else 0.15
u_logits = 4.4 * user_item_cos[uid] - 0.85 * price_diff[uid] + exposure_w * log_exposure
if is_late and rng.random() < 0.55:
ctx1 = int(rng.choice(late_trend_items))
else:
u_logits -= np.max(u_logits)
u_probs = np.exp(u_logits)
u_probs /= np.sum(u_probs)
ctx1 = int(rng.choice(cfg.n_items, p=u_probs))
if is_late and ctx1 in trend_partner:
ctx2 = trend_partner[ctx1]
else:
sim_ctx = item_emb @ item_emb[ctx1]
c2_logits = 3.8 * sim_ctx + 0.20 * exposure_w * log_exposure
c2_logits[ctx1] -= 50.0
c2_logits -= np.max(c2_logits)
c2_p = np.exp(c2_logits)
c2_p /= np.sum(c2_p)
ctx2 = int(rng.choice(cfg.n_items, p=c2_p))
# True personalization relevance: latent taste + context + price match (Stage 2 exploits price!)
ctx_mean = 0.5 * (item_emb[ctx1] + item_emb[ctx2])
ctx_mean /= max(float(np.linalg.norm(ctx_mean)), 1e-12)
t_logits = (
4.2 * user_item_cos[uid]
+ 3.4 * (item_emb @ ctx_mean)
- 1.45 * price_diff[uid]
)
if is_late and ctx1 in trend_partner:
# Late cross-category bundle edge (invisible in early train, leaked in LOO!)
partner_b = trend_partner[trend_partner[ctx1]]
t_logits[partner_b] += 6.5
t_logits[ctx2] += 0.0 # keep ctx2 excluded
t_logits[ctx1] -= 50.0
t_logits[ctx2] -= 50.0
t_logits -= np.max(t_logits)
t_probs = np.exp(t_logits)
t_probs /= np.sum(t_probs)
target_item = int(rng.choice(cfg.n_items, p=t_probs))
top_rel = np.argsort(-t_probs)[:4].tolist()
rel_set = sorted(set([target_item] + [x for x in top_rel if x not in (ctx1, ctx2)][:2]))
clicked = 1
purchased = int(rng.random() < (0.28 + 0.18 * float(user_item_cos[uid, target_item])))
records.append(
{
"session_id": s_id,
"user_id": uid,
"event_ts": ts,
"ctx_item_1": ctx1,
"ctx_item_2": ctx2,
"target_item_id": target_item,
"relevant_items": rel_set,
"clicked": clicked,
"purchased": purchased,
"is_late_trend": bool(is_late and ctx1 in trend_partner),
}
)
interactions_df = pd.DataFrame(records)
return ECommerceDataset(
items_df=items_df,
item_embeddings=item_emb,
user_embeddings=user_emb,
interactions_df=interactions_df,
)
def split_global_temporal(
interactions_df: pd.DataFrame,
train_frac: float = 0.65,
cal_frac: float = 0.15,
) -> tuple[pd.DataFrame, pd.DataFrame, pd.DataFrame]:
"""Split strictly by global timestamp: max(train) < min(cal) < min(test)."""
ordered = interactions_df.sort_values("event_ts").reset_index(drop=True)
n = len(ordered)
i_train = int(round(train_frac * n))
i_cal = int(round((train_frac + cal_frac) * n))
train_df = ordered.iloc[:i_train].reset_index(drop=True)
cal_df = ordered.iloc[i_train:i_cal].reset_index(drop=True)
test_df = ordered.iloc[i_cal:].reset_index(drop=True)
return train_df, cal_df, test_df
def split_leave_one_out_leaky(interactions_df: pd.DataFrame) -> tuple[pd.DataFrame, pd.DataFrame]:
"""Per-user Leave-One-Out split (exposes future global timestamps leaking into train!)."""
ordered = interactions_df.sort_values(["user_id", "event_ts"]).reset_index(drop=True)
last_idx = ordered.groupby("user_id")["event_ts"].idxmax()
is_test = ordered.index.isin(last_idx)
train_loo = ordered.loc[~is_test].sort_values("event_ts").reset_index(drop=True)
test_loo = ordered.loc[is_test].sort_values("event_ts").reset_index(drop=True)
return train_loo, test_loo
# ---------------------------------------------------------------------------
# 2. Stage 1 Candidate Retrieval (Two-Tower + IPS Debiasing + Co-Visitation + HNSW)
# ---------------------------------------------------------------------------
class MultiSourceRetriever:
"""Stage 1 Candidate Generator blending Two-Tower ANN (HNSW), IPS Debiasing & Co-Visitation."""
def __init__(self, config: RetrievalConfig | None = None, seed: int = 42) -> None:
self.config = config or RetrievalConfig()
self.seed = seed
self.item_emb_: FloatArray | None = None
self.user_profiles_raw_: FloatArray | None = None
self.user_profiles_ips_: FloatArray | None = None
self.item_counts_: FloatArray | None = None
self.ips_weights_: FloatArray | None = None
self.covis_scores_: FloatArray | None = None
self.hnsw_index_: HNSWIndex | None = None
self.n_users_: int = 0
self.n_items_: int = 0
def fit(self, train_df: pd.DataFrame, item_embeddings: FloatArray, n_users: int) -> MultiSourceRetriever:
self.item_emb_ = np.asarray(item_embeddings, dtype=np.float64)
self.n_items_ = self.item_emb_.shape[0]
self.n_users_ = n_users
dim = self.item_emb_.shape[1]
# Item frequencies strictly inside train_df
counts = np.zeros(self.n_items_, dtype=np.float64)
for col in ("ctx_item_1", "ctx_item_2", "target_item_id"):
vals = train_df[col].to_numpy(dtype=np.int64)
np.add.at(counts, vals, 1.0)
self.item_counts_ = counts
total_events = max(float(np.sum(counts)), 1.0)
propensity = np.maximum(counts / total_events, 1.0 / (total_events + 5.0))
raw_ips = propensity ** (-self.config.ips_alpha)
# Clip IPS weights to prevent extreme tail variance explosion
self.ips_weights_ = np.clip(raw_ips / np.mean(raw_ips), 0.15, 6.0)
# Build Two-Tower user representations (raw vs IPS-weighted) strictly from train_df
u_raw = np.zeros((n_users, dim), dtype=np.float64)
u_ips = np.zeros((n_users, dim), dtype=np.float64)
u_cnt = np.zeros(n_users, dtype=np.float64)
for row in train_df.itertuples(index=False):
uid = int(row.user_id)
for iid in (int(row.ctx_item_1), int(row.ctx_item_2), int(row.target_item_id)):
v = self.item_emb_[iid]
u_raw[uid] += v
u_ips[uid] += self.ips_weights_[iid] * v
u_cnt[uid] += 1.0
global_mean = np.mean(self.item_emb_, axis=0)
for uid in range(n_users):
if u_cnt[uid] > 0:
u_raw[uid] /= max(float(np.linalg.norm(u_raw[uid])), 1e-12)
u_ips[uid] /= max(float(np.linalg.norm(u_ips[uid])), 1e-12)
else:
u_raw[uid] = global_mean / max(float(np.linalg.norm(global_mean)), 1e-12)
u_ips[uid] = u_raw[uid]
self.user_profiles_raw_ = u_raw
self.user_profiles_ips_ = u_ips
# Build Cosine Similarity Co-visitation graph strictly from train_df sessions
co_mat = np.zeros((self.n_items_, self.n_items_), dtype=np.float64)
for row in train_df.itertuples(index=False):
c1, c2, tgt = int(row.ctx_item_1), int(row.ctx_item_2), int(row.target_item_id)
for src in (c1, c2):
co_mat[src, tgt] += 1.0
co_mat[tgt, src] += 0.5
co_mat[c1, c2] += 0.5
co_mat[c2, c1] += 0.5
denom = np.sqrt((counts[:, None] + 6.0) * (counts[None, :] + 6.0))
self.covis_scores_ = co_mat / denom
if self.config.use_hnsw:
self.hnsw_index_ = HNSWIndex(
HNSWConfig(
m_links=16,
ef_construction=64,
ef_search=max(64, self.config.top_k_candidates),
metric="cosine",
seed=self.seed,
)
).build(self.item_emb_)
return self
def retrieve(
self,
user_id: int,
ctx_items: tuple[int, int],
mode: str = "ips_covis",
k: int | None = None,
) -> tuple[IntArray, FloatArray]:
assert (
self.item_emb_ is not None
and self.user_profiles_raw_ is not None
and self.user_profiles_ips_ is not None
and self.item_counts_ is not None
and self.covis_scores_ is not None
)
k_use = min(k or self.config.top_k_candidates, self.n_items_)
c1, c2 = ctx_items
ctx_vec = self.item_emb_[c1] + self.item_emb_[c2]
ctx_vec /= max(float(np.linalg.norm(ctx_vec)), 1e-12)
if mode == "popularity_biased":
# Raw Two-Tower + heavy un-debiased log-popularity boost -> popularity collapse!
q_vec = 0.55 * self.user_profiles_raw_[user_id] + 0.45 * ctx_vec
q_vec /= max(float(np.linalg.norm(q_vec)), 1e-12)
scores = (self.item_emb_ @ q_vec) + 0.95 * np.log1p(self.item_counts_)
scores[c1] = -1e9
scores[c2] = -1e9
top_idx = np.argpartition(-scores, kth=k_use - 1)[:k_use]
ord_pos = np.argsort(-scores[top_idx])
best = top_idx[ord_pos]
return best.astype(np.int64), scores[best].astype(np.float64)
if mode == "covis_only":
covis_vec = 0.5 * (self.covis_scores_[c1] + self.covis_scores_[c2])
covis_vec[c1] = -1e9
covis_vec[c2] = -1e9
top_idx = np.argpartition(-covis_vec, kth=k_use - 1)[:k_use]
ord_pos = np.argsort(-covis_vec[top_idx])
best = top_idx[ord_pos]
return best.astype(np.int64), covis_vec[best].astype(np.float64)
# Hybrid IPS-Debiased Two-Tower (via HNSW ANN + Co-visitation graph fusion)
q_ips = 0.62 * self.user_profiles_ips_[user_id] + 0.38 * ctx_vec
q_ips /= max(float(np.linalg.norm(q_ips)), 1e-12)
pop_pen = self.config.pop_penalty * np.log1p(self.item_counts_)
covis_vec = 0.5 * (self.covis_scores_[c1] + self.covis_scores_[c2])
if self.hnsw_index_ is not None:
ann_pool = min(self.n_items_, max(k_use, int(k_use * 1.4)))
ann_ids, _, _ = self.hnsw_index_.search(q_ips, k=ann_pool, ef_search=max(96, ann_pool))
covis_top = np.argpartition(-covis_vec, kth=min(80, self.n_items_) - 1)[: min(80, self.n_items_)]
pool = np.unique(np.concatenate([ann_ids, covis_top]))
pool = pool[(pool != c1) & (pool != c2)]
pool_scores = (
(self.item_emb_[pool] @ q_ips)
- pop_pen[pool]
+ self.config.covis_weight * covis_vec[pool]
)
k_eff = min(k_use, pool.shape[0])
top_p = np.argpartition(-pool_scores, kth=k_eff - 1)[:k_eff]
ord_p = np.argsort(-pool_scores[top_p])
best_ids = pool[top_p[ord_p]]
return best_ids.astype(np.int64), pool_scores[top_p[ord_p]].astype(np.float64)
scores = (self.item_emb_ @ q_ips) - pop_pen + self.config.covis_weight * covis_vec
scores[c1] = -1e9
scores[c2] = -1e9
top_idx = np.argpartition(-scores, kth=k_use - 1)[:k_use]
ord_pos = np.argsort(-scores[top_idx])
best = top_idx[ord_pos]
return best.astype(np.int64), scores[best].astype(np.float64)
def evaluate_recall_and_coverage(
self,
eval_df: pd.DataFrame,
mode: str = "ips_covis",
k: int = 200,
) -> dict[str, float]:
recalls: list[float] = []
unique_served: set[int] = set()
for row in eval_df.itertuples(index=False):
cands, _ = self.retrieve(
int(row.user_id), (int(row.ctx_item_1), int(row.ctx_item_2)), mode=mode, k=k
)
rel_set = set(row.relevant_items)
hits = len(set(cands.tolist()) & rel_set)
recalls.append(hits / float(max(len(rel_set), 1)))
unique_served.update(cands[:20].tolist())
return {
f"recall_at_{k}": float(np.mean(recalls)),
"catalog_coverage_top20": float(len(unique_served) / float(self.n_items_)),
}
# ---------------------------------------------------------------------------
# 3. Stage 2 Point-in-Time Feature Ranking & Platt Calibration
# ---------------------------------------------------------------------------
class PlattCalibrator:
"""Post-hoc Platt Scaling fitted strictly on calibration split D_cal."""
def __init__(self) -> None:
self.lr_ = LogisticRegression(C=100.0, solver="lbfgs", max_iter=200)
self.is_fitted_: bool = False
def fit(self, raw_logits: FloatArray, y_true: IntArray) -> PlattCalibrator:
x = np.asarray(raw_logits, dtype=np.float64).reshape(-1, 1)
y = np.asarray(y_true, dtype=np.int64)
self.lr_.fit(x, y)
self.is_fitted_ = True
return self
def predict_proba(self, raw_logits: FloatArray) -> FloatArray:
assert self.is_fitted_
x = np.asarray(raw_logits, dtype=np.float64).reshape(-1, 1)
return np.asarray(self.lr_.predict_proba(x)[:, 1], dtype=np.float64)
def compute_ece(y_true: IntArray, y_prob: FloatArray, n_bins: int = 10) -> float:
"""Expected Calibration Error across equal-width probability bins."""
y = np.asarray(y_true, dtype=np.float64)
p = np.clip(np.asarray(y_prob, dtype=np.float64), 0.0, 1.0)
edges = np.linspace(0.0, 1.0, n_bins + 1)
ece = 0.0
n = float(len(y))
for b in range(n_bins):
lo, hi = edges[b], edges[b + 1]
if b == n_bins - 1:
mask = (p >= lo) & (p <= hi)
else:
mask = (p >= lo) & (p < hi)
cnt = int(np.sum(mask))
if cnt > 0:
ece += (cnt / n) * abs(float(np.mean(y[mask])) - float(np.mean(p[mask])))
return float(ece)
def compute_pit_features(
user_id: int,
query_ts: float,
ctx_items: tuple[int, int],
candidate_ids: IntArray,
stage1_scores: FloatArray,
history_df: pd.DataFrame,
items_df: pd.DataFrame,
item_emb: FloatArray,
covis_matrix: FloatArray,
prior_ctr: float = 0.08,
prior_strength: float = 8.0,
) -> FloatArray:
"""Build strictly causal Point-in-Time (t < query_ts) ranking features."""
# STRICT ANTI-LEAKAGE BOUNDARY: only read events strictly BEFORE query_ts!
past_df = history_df[history_df["event_ts"] < query_ts]
user_past = past_df[past_df["user_id"] == user_id]
c1, c2 = ctx_items
ctx_vec = item_emb[c1] + item_emb[c2]
ctx_vec /= max(float(np.linalg.norm(ctx_vec)), 1e-12)
item_cats = items_df["category_id"].to_numpy(dtype=np.int64)
item_log_prices = np.log(np.maximum(items_df["price_usd"].to_numpy(dtype=np.float64), 1.0))
if len(user_past) > 0:
past_c1 = user_past["ctx_item_1"].to_numpy(dtype=np.int64)
past_c2 = user_past["ctx_item_2"].to_numpy(dtype=np.int64)
past_tgt = user_past["target_item_id"].to_numpy(dtype=np.int64)
past_ts = user_past["event_ts"].to_numpy(dtype=np.float64)
recency_w = np.exp(-0.002 * np.maximum(query_ts - past_ts, 0.0))
all_past_items = np.concatenate([past_c1, past_c2, past_tgt])
all_past_w = np.concatenate([0.6 * recency_w, 0.6 * recency_w, recency_w])
u_pit_vec = np.sum(item_emb[all_past_items] * all_past_w[:, None], axis=0)
u_pit_vec /= max(float(np.linalg.norm(u_pit_vec)), 1e-12)
u_mean_log_price = float(np.average(item_log_prices[all_past_items], weights=all_past_w))
past_cats = item_cats[all_past_items]
cat_counts = np.bincount(
past_cats, weights=all_past_w, minlength=int(np.max(item_cats)) + 1
)
cat_aff = cat_counts / max(float(np.sum(cat_counts)), 1e-12)
else:
u_pit_vec = ctx_vec
u_mean_log_price = float(0.5 * (item_log_prices[c1] + item_log_prices[c2]))
n_cats = int(np.max(item_cats)) + 1
cat_aff = np.full(n_cats, 1.0 / float(n_cats), dtype=np.float64)
# Empirical-Bayes smoothed item conversion rate strictly prior to query_ts
n_items = item_emb.shape[0]
imp_cnt = np.zeros(n_items, dtype=np.float64)
buy_cnt = np.zeros(n_items, dtype=np.float64)
if len(past_df) > 0:
p_tids = past_df["target_item_id"].to_numpy(dtype=np.int64)
p_buys = past_df["purchased"].to_numpy(dtype=np.float64)
np.add.at(imp_cnt, p_tids, 1.0)
np.add.at(buy_cnt, p_tids, p_buys)
eb_ctr = (buy_cnt + prior_strength * prior_ctr) / (imp_cnt + prior_strength)
cand_embs = item_emb[candidate_ids]
f_user_cos = cand_embs @ u_pit_vec
f_ctx_cos = cand_embs @ ctx_vec
f_user_ctx_prod = f_user_cos * f_ctx_cos
f_covis = 0.5 * (covis_matrix[c1, candidate_ids] + covis_matrix[c2, candidate_ids])
f_cat_match = cat_aff[item_cats[candidate_ids]]
f_price_match = -np.abs(item_log_prices[candidate_ids] - u_mean_log_price)
f_eb_ctr = eb_ctr[candidate_ids]
f_s1 = stage1_scores
return np.column_stack(
[
f_user_cos,
f_ctx_cos,
f_user_ctx_prod,
f_covis,
f_cat_match,
f_price_match,
f_eb_ctr,
f_s1,
]
).astype(np.float64)
class PointInTimeRanker:
"""Stage 2 Feature Ranker with class-balanced Logistic Regression + D_cal Platt Calibration."""
def __init__(self, config: RankerConfig | None = None, seed: int = 42) -> None:
self.config = config or RankerConfig()
self.seed = seed
# Balanced class weights skew raw log-odds -> requires Platt calibration on D_cal!
self.model_ = LogisticRegression(
C=self.config.l2_c, class_weight="balanced", max_iter=300, random_state=seed
)
self.calibrator_ = PlattCalibrator()
self.feat_mean_: FloatArray | None = None
self.feat_scale_: FloatArray | None = None
def _build_training_matrix(
self,
sessions_df: pd.DataFrame,
retriever: MultiSourceRetriever,
history_df: pd.DataFrame,
items_df: pd.DataFrame,
item_emb: FloatArray,
) -> tuple[FloatArray, IntArray, IntArray]:
rng = np.random.default_rng(self.seed)
assert retriever.covis_scores_ is not None
X_rows: list[FloatArray] = []
y_rel_rows: list[IntArray] = []
y_buy_rows: list[IntArray] = []
for row in sessions_df.itertuples(index=False):
cands, s1_scores = retriever.retrieve(
int(row.user_id), (int(row.ctx_item_1), int(row.ctx_item_2)), mode="ips_covis", k=80
)
rel_set = set(row.relevant_items)
tgt = int(row.target_item_id)
if tgt not in set(cands.tolist()):
cands = np.append(cands[:-1], tgt)
s1_scores = np.append(s1_scores[:-1], float(np.min(s1_scores)))
# Subsample negatives for fast balanced training
pos_mask = np.isin(cands, list(rel_set))
pos_idx = np.flatnonzero(pos_mask)
neg_idx = np.flatnonzero(~pos_mask)
n_neg = min(self.config.neg_samples_per_session, len(neg_idx))
chosen_neg = (
rng.choice(neg_idx, size=n_neg, replace=False)
if n_neg > 0
else np.empty(0, dtype=np.int64)
)
sel = np.concatenate([pos_idx, chosen_neg])
sel_cands = cands[sel]
sel_s1 = s1_scores[sel]
feats = compute_pit_features(
user_id=int(row.user_id),
query_ts=float(row.event_ts),
ctx_items=(int(row.ctx_item_1), int(row.ctx_item_2)),
candidate_ids=sel_cands,
stage1_scores=sel_s1,
history_df=history_df,
items_df=items_df,
item_emb=item_emb,
covis_matrix=retriever.covis_scores_,
prior_ctr=self.config.prior_ctr,
prior_strength=self.config.prior_strength,
)
y_rel = np.isin(sel_cands, list(rel_set)).astype(np.int64)
y_buy = (sel_cands == tgt).astype(np.int64) & int(row.purchased)
X_rows.append(feats)
y_rel_rows.append(y_rel)
y_buy_rows.append(y_buy)
return np.vstack(X_rows), np.concatenate(y_rel_rows), np.concatenate(y_buy_rows)
def fit(
self,
train_df: pd.DataFrame,
cal_df: pd.DataFrame,
retriever: MultiSourceRetriever,
items_df: pd.DataFrame,
item_emb: FloatArray,
) -> PointInTimeRanker:
# Train ranker strictly on train_df
X_tr, y_tr, _ = self._build_training_matrix(train_df, retriever, train_df, items_df, item_emb)
self.feat_mean_ = np.mean(X_tr, axis=0)
std = np.std(X_tr, axis=0)
self.feat_scale_ = np.where(std > 1e-12, std, 1.0)
X_tr_std = (X_tr - self.feat_mean_) / self.feat_scale_
self.model_.fit(X_tr_std, y_tr)
# Fit Platt calibrator strictly on D_cal (using train + prior cal rows up to t < query_ts)
hist_cal = pd.concat([train_df, cal_df], ignore_index=True)
X_cal, y_cal, _ = self._build_training_matrix(cal_df, retriever, hist_cal, items_df, item_emb)
X_cal_std = (X_cal - self.feat_mean_) / self.feat_scale_
cal_logits = self.model_.decision_function(X_cal_std)
self.calibrator_.fit(cal_logits, y_cal)
return self
def score_candidates(
self,
user_id: int,
query_ts: float,
ctx_items: tuple[int, int],
candidate_ids: IntArray,
stage1_scores: FloatArray,
history_df: pd.DataFrame,
items_df: pd.DataFrame,
item_emb: FloatArray,
covis_matrix: FloatArray,
) -> tuple[FloatArray, FloatArray]:
assert self.feat_mean_ is not None and self.feat_scale_ is not None
feats = compute_pit_features(
user_id=user_id,
query_ts=query_ts,
ctx_items=ctx_items,
candidate_ids=candidate_ids,
stage1_scores=stage1_scores,
history_df=history_df,
items_df=items_df,
item_emb=item_emb,
covis_matrix=covis_matrix,
prior_ctr=self.config.prior_ctr,
prior_strength=self.config.prior_strength,
)
X_std = (feats - self.feat_mean_) / self.feat_scale_
logits = self.model_.decision_function(X_std)
probs_uncal = np.asarray(self.model_.predict_proba(X_std)[:, 1], dtype=np.float64)
probs_cal = self.calibrator_.predict_proba(logits)
return probs_uncal, probs_cal
# ---------------------------------------------------------------------------
# 4. Stage 3 MMR Re-Ranking & Ranking Metrics
# ---------------------------------------------------------------------------
def compute_ndcg_and_ap(ranked_ids: IntArray, rel_set: set[int], k: int = 10) -> tuple[float, float]:
top = ranked_ids[:k].tolist()
dcg = 0.0
hits = 0
ap_sum = 0.0
for rank_idx, iid in enumerate(top):
if iid in rel_set:
hits += 1
dcg += 1.0 / math.log2(rank_idx + 2.0)
ap_sum += hits / float(rank_idx + 1)
n_ideal = min(len(rel_set), k)
idcg = sum(1.0 / math.log2(r + 2.0) for r in range(n_ideal))
ndcg = dcg / idcg if idcg > 0 else 0.0
ap = ap_sum / float(max(n_ideal, 1))
return ndcg, ap
def compute_ild(ranked_ids: IntArray, item_emb: FloatArray) -> float:
"""Intra-List Diversity: average pairwise (1 - cosine similarity) across slate."""
k = ranked_ids.shape[0]
if k < 2:
return 0.0
embs = item_emb[ranked_ids]
sim = embs @ embs.T
triu_i, triu_j = np.triu_indices(k, k=1)
return float(np.mean(1.0 - np.clip(sim[triu_i, triu_j], -1.0, 1.0)))
def mmr_rerank(
candidate_ids: IntArray,
relevance_probs: FloatArray,
item_margins: FloatArray,
item_emb: FloatArray,
config: MMRConfig | None = None,
) -> IntArray:
"""Greedy Maximal Marginal Relevance balancing relevance/margin vs inter-item redundancy."""
cfg = config or MMRConfig()
pool_sz = min(cfg.candidate_pool_size, candidate_ids.shape[0])
# Select top pool_sz candidates by calibrated utility
expected_margin = relevance_probs * item_margins[candidate_ids]
r_norm = (relevance_probs - np.min(relevance_probs)) / max(float(np.ptp(relevance_probs)), 1e-12)
m_norm = (expected_margin - np.min(expected_margin)) / max(float(np.ptp(expected_margin)), 1e-12)
utility = (1.0 - cfg.margin_blend) * r_norm + cfg.margin_blend * m_norm
pool_order = np.argsort(-utility)[:pool_sz]
pool_ids = candidate_ids[pool_order]
pool_util = utility[pool_order]
pool_emb = item_emb[pool_ids]
sim_mat = np.maximum(0.0, pool_emb @ pool_emb.T)
k_out = min(cfg.top_k, pool_sz)
selected_pos: list[int] = []
remaining = set(range(pool_sz))
# Pick top-1 purely by utility
first = int(np.argmax(pool_util))
selected_pos.append(first)
remaining.remove(first)
lam = cfg.mmr_lambda
while len(selected_pos) < k_out and remaining:
best_p = -1
best_score = -1e18
for p in remaining:
max_sim = max(float(sim_mat[p, s]) for s in selected_pos)
mmr_score = lam * float(pool_util[p]) - (1.0 - lam) * max_sim
if mmr_score > best_score:
best_score = mmr_score
best_p = p
selected_pos.append(best_p)
remaining.remove(best_p)
return pool_ids[np.array(selected_pos, dtype=np.int64)]
# ---------------------------------------------------------------------------
# 5. Leakage Audit & Full End-to-End Benchmark Runner
# ---------------------------------------------------------------------------
def audit_temporal_vs_loo_leakage(
ds: ECommerceDataset,
seed: int = 42,
) -> dict[str, Any]:
"""Contrast strict Global Temporal Split vs leaky per-user Leave-One-Out co-visitation."""
train_gt, cal_gt, test_gt = split_global_temporal(ds.interactions_df)
train_loo, test_loo = split_leave_one_out_leaky(ds.interactions_df)
max_tr_gt = float(train_gt["event_ts"].max())
min_cal_gt = float(cal_gt["event_ts"].min())
max_cal_gt = float(cal_gt["event_ts"].max())
min_te_gt = float(test_gt["event_ts"].min())
max_tr_loo = float(train_loo["event_ts"].max())
min_te_loo = float(test_loo["event_ts"].min())
# Evaluate Stage 1 recall@40 on late-window queries under Global Temporal vs LOO
ret_cfg_audit = RetrievalConfig(
top_k_candidates=40, use_hnsw=False, pop_penalty=0.0, covis_weight=1.2
)
ret_gt = MultiSourceRetriever(ret_cfg_audit, seed=seed).fit(
train_gt, ds.item_embeddings, ds.user_embeddings.shape[0]
)
ret_loo = MultiSourceRetriever(ret_cfg_audit, seed=seed).fit(
train_loo, ds.item_embeddings, ds.user_embeddings.shape[0]
)
late_test_gt = test_gt[test_gt["is_late_trend"]]
late_test_loo = test_loo[test_loo["is_late_trend"]]
eval_gt = late_test_gt if len(late_test_gt) >= 5 else test_gt
eval_loo = late_test_loo if len(late_test_loo) >= 5 else test_loo
m_gt = ret_gt.evaluate_recall_and_coverage(eval_gt, mode="covis_only", k=40)
m_loo = ret_loo.evaluate_recall_and_coverage(eval_loo, mode="covis_only", k=40)
return {
"global_temporal_max_train_ts": max_tr_gt,
"global_temporal_min_cal_ts": min_cal_gt,
"global_temporal_max_cal_ts": max_cal_gt,
"global_temporal_min_test_ts": min_te_gt,
"global_temporal_is_strict": bool(max_tr_gt < min_cal_gt and max_cal_gt < min_te_gt),
"loo_max_train_ts": max_tr_loo,
"loo_min_test_ts": min_te_loo,
"loo_has_future_leakage": bool(max_tr_loo > min_te_loo),
"global_temporal_late_recall_at_40": float(m_gt["recall_at_40"]),
"loo_leaky_late_recall_at_40": float(m_loo["recall_at_40"]),
"loo_inflation_delta": float(m_loo["recall_at_40"] - m_gt["recall_at_40"]),
}
def evaluate_multistage_pipeline(
seed: int = 42,
quick: bool = False,
) -> dict[str, Any]:
"""Run complete 3-Stage E-Commerce RecSys evaluation on Global Temporal Split."""
ds_cfg = RecSysDatasetConfig(
n_users=140 if quick else 240,
n_items=450 if quick else 800,
n_sessions=750 if quick else 1500,
dim=16,
)
ds = generate_ecommerce_sessions(ds_cfg, seed=seed)
train_df, cal_df, test_df = split_global_temporal(ds.interactions_df)
leak_audit = audit_temporal_vs_loo_leakage(ds, seed=seed)
# Stage 1 Retrieval Comparison
ret_cfg = RetrievalConfig(top_k_candidates=140 if quick else 200, use_hnsw=True)
retriever = MultiSourceRetriever(ret_cfg, seed=seed).fit(
train_df, ds.item_embeddings, ds_cfg.n_users
)
k_ret = ret_cfg.top_k_candidates
s1_pop = retriever.evaluate_recall_and_coverage(test_df, mode="popularity_biased", k=k_ret)
s1_ips = retriever.evaluate_recall_and_coverage(test_df, mode="ips_covis", k=k_ret)
# Stage 2 Point-in-Time Feature Ranker + Platt Calibration
ranker = PointInTimeRanker(RankerConfig(neg_samples_per_session=16 if quick else 24), seed=seed).fit(
train_df, cal_df, retriever, ds.items_df, ds.item_embeddings
)
hist_all = pd.concat([train_df, cal_df, test_df], ignore_index=True)
margins = ds.items_df["margin_usd"].to_numpy(dtype=np.float64)
assert retriever.covis_scores_ is not None
s1_ndcg, s1_ap = [], []
s2_ndcg, s2_ap = [], []
mmr_ndcg, mmr_ap = [], []
pure_ild, mmr_ild = [], []
pure_margin, mmr_margin = [], []
pure_served: set[int] = set()
mmr_served: set[int] = set()
cal_y_list: list[IntArray] = []
p_uncal_list: list[FloatArray] = []
p_cal_list: list[FloatArray] = []
mmr_cfg = MMRConfig(top_k=10, candidate_pool_size=60, mmr_lambda=0.58, margin_blend=0.35)
pure_cfg = MMRConfig(top_k=10, candidate_pool_size=60, mmr_lambda=1.0, margin_blend=0.0)
for row in test_df.itertuples(index=False):
cands, s1_sc = retriever.retrieve(
int(row.user_id), (int(row.ctx_item_1), int(row.ctx_item_2)), mode="ips_covis", k=k_ret
)
rel_set = set(row.relevant_items)
nd1, ap1 = compute_ndcg_and_ap(cands, rel_set, k=10)
s1_ndcg.append(nd1)
s1_ap.append(ap1)
p_uncal, p_cal = ranker.score_candidates(
user_id=int(row.user_id),
query_ts=float(row.event_ts),
ctx_items=(int(row.ctx_item_1), int(row.ctx_item_2)),
candidate_ids=cands,
stage1_scores=s1_sc,
history_df=hist_all,
items_df=ds.items_df,
item_emb=ds.item_embeddings,
covis_matrix=retriever.covis_scores_,
)
y_cand = np.isin(cands, list(rel_set)).astype(np.int64)
cal_y_list.append(y_cand)
p_uncal_list.append(p_uncal)
p_cal_list.append(p_cal)
# Stage 2 Pure Calibrated Probability Ranking
s2_order = np.argsort(-p_cal)
s2_top_all = cands[s2_order]
nd2, ap2 = compute_ndcg_and_ap(s2_top_all, rel_set, k=10)
s2_ndcg.append(nd2)
s2_ap.append(ap2)
pure_slate = mmr_rerank(cands, p_cal, margins, ds.item_embeddings, config=pure_cfg)
mmr_slate = mmr_rerank(cands, p_cal, margins, ds.item_embeddings, config=mmr_cfg)
nd_m, ap_m = compute_ndcg_and_ap(mmr_slate, rel_set, k=10)
mmr_ndcg.append(nd_m)
mmr_ap.append(ap_m)
pure_ild.append(compute_ild(pure_slate, ds.item_embeddings))
mmr_ild.append(compute_ild(mmr_slate, ds.item_embeddings))
pure_served.update(pure_slate.tolist())
mmr_served.update(mmr_slate.tolist())
# Expected calibrated gross margin across top-10 slate
c_pos_map = {int(cid): idx for idx, cid in enumerate(cands.tolist())}
pure_margin.append(float(np.sum([p_cal[c_pos_map[int(x)]] * margins[int(x)] for x in pure_slate])))
mmr_margin.append(float(np.sum([p_cal[c_pos_map[int(x)]] * margins[int(x)] for x in mmr_slate])))
y_all = np.concatenate(cal_y_list)
pu_all = np.concatenate(p_uncal_list)
pc_all = np.concatenate(p_cal_list)
return {
"n_train": int(len(train_df)),
"n_cal": int(len(cal_df)),
"n_test": int(len(test_df)),
"n_items": int(ds_cfg.n_items),
"k_retrieval": k_ret,
"temporal_vs_loo": leak_audit,
"stage1_pop_biased_recall": float(s1_pop[f"recall_at_{k_ret}"]),
"stage1_pop_biased_cov20": float(s1_pop["catalog_coverage_top20"]),
"stage1_ips_covis_recall": float(s1_ips[f"recall_at_{k_ret}"]),
"stage1_ips_covis_cov20": float(s1_ips["catalog_coverage_top20"]),
"stage1_ndcg_at_10": float(np.mean(s1_ndcg)),
"stage1_map_at_10": float(np.mean(s1_ap)),
"stage2_ndcg_at_10": float(np.mean(s2_ndcg)),
"stage2_map_at_10": float(np.mean(s2_ap)),
"uncalibrated_brier": float(brier_score_loss(y_all, pu_all)),
"calibrated_brier": float(brier_score_loss(y_all, pc_all)),
"uncalibrated_ece": compute_ece(y_all, pu_all),
"calibrated_ece": compute_ece(y_all, pc_all),
"pure_top10_ild": float(np.mean(pure_ild)),
"mmr_top10_ild": float(np.mean(mmr_ild)),
"pure_top10_coverage": float(len(pure_served) / float(ds_cfg.n_items)),
"mmr_top10_coverage": float(len(mmr_served) / float(ds_cfg.n_items)),
"mmr_ndcg_at_10": float(np.mean(mmr_ndcg)),
"pure_expected_margin_usd": float(np.mean(pure_margin)),
"mmr_expected_margin_usd": float(np.mean(mmr_margin)),
}
def run_full_ch11_lab05_benchmarks(seed: int = 42, quick: bool = False) -> dict[str, Any]:
"""Run all Ch 11 + Lab 05 benchmarks and build structured workbench_panels."""
curse = analyze_curse_of_dimensionality(seed=seed)
scale_trap = benchmark_scale_trap_mahalanobis(seed=seed, quick=quick)
kdtree = benchmark_kdtree_collapse(seed=seed, quick=quick)
hnsw = benchmark_hnsw_ef_pareto(seed=seed, quick=quick)
ivfpq = benchmark_ivf_pq_adc(seed=seed, quick=quick)
scann = scann_anisotropic_mips_demo(seed=seed, quick=quick)
filtered = verify_filtered_search_selectivity(selectivity=0.02, seed=seed, quick=quick)
recsys = evaluate_multistage_pipeline(seed=seed, quick=quick)
hnsw_best = hnsw["pareto_sweep"][-1]
ivf_best = ivfpq["sweep"][-1]
cv_k = scale_trap["cv_k_selection"]
k_ret = recsys["k_retrieval"]
kpis = [
{
"id": "kpi_curse_and_mahalanobis",
"label": "Curse Contrast & Mahalanobis Rescue",
"value": (
f"{curse[-1]['iso_contrast_ratio']:.2f} vs "
f"{curse[0]['iso_contrast_ratio']:.1f} | {scale_trap['mahalanobis_acc']:.1%}"
),
"unit": "d=512 vs d=2 | Acc",
"status": "ok",
"detail": (
f"Isotropic contrast collapses {curse[0]['iso_contrast_ratio']:.2f}->"
f"{curse[-1]['iso_contrast_ratio']:.2f}; unscaled L2 "
f"{scale_trap['raw_l2_acc']:.1%} rescued to "
f"{scale_trap['mahalanobis_acc']:.1%} by Mahalanobis."
),
},
{
"id": "kpi_kdtree_vs_hnsw_recall",
"label": "KD-Tree Collapse vs HNSW Recall@10",
"value": f"KD {kdtree['d64']['mean_visit_frac']:.0%} | HNSW {hnsw_best['recall_at_10']:.1%}",
"unit": "Scan% | Recall@10",
"status": "ok",
"detail": (
f"KD-Tree visits {kdtree['d4']['mean_visit_frac']:.1%} at d=4 vs "
f"{kdtree['d64']['mean_visit_frac']:.1%} at d=64; HNSW achieves "
f"{hnsw_best['recall_at_10']:.1%} Recall@10 scanning {hnsw_best['scan_frac']:.1%}."
),
},
{
"id": "kpi_ivfpq_compression_and_scann",
"label": "IVF-PQ Compression & ScaNN MIPS",
"value": f"{ivfpq['compression_ratio']:.0f}x RAM | Rec {ivf_best['recall_at_10']:.1%}",
"unit": f"ScaNN {scann['anisotropic_mips_recall_at_10']:.1%}",
"status": "ok",
"detail": (
f"IVF-PQ compresses {ivfpq['raw_fp32_bytes']:.0f}B->"
f"{ivfpq['pq_code_bytes']:.0f}B/vec; ScaNN cuts top-20 MIPS MSE "
f"{scann['isotropic_top20_mips_mse']:.3f}->"
f"{scann['anisotropic_top20_mips_mse']:.3f}."
),
},
{
"id": "kpi_filtered_ann_selectivity",
"label": "Filtered ANN (s=2%) Iterative Scan",
"value": (
f"{filtered['post_filter_recall_at_10']:.1%} -> "
f"{filtered['iterative_scan_recall_at_10']:.1%}"
),
"unit": "Recall@10",
"status": "warn",
"detail": (
f"Naive post-filter returns {filtered['post_filter_avg_returned']:.1f}/10 items "
f"(Pre-filter {filtered['pre_filter_graph_recall_at_10']:.1%}); "
f"iterative scan restores {filtered['iterative_scan_recall_at_10']:.1%}."
),
},
{
"id": "kpi_recsys_temporal_stage2_lift",
"label": "Temporal RecSys Stage 1 -> Stage 2",
"value": (
f"R@{k_ret} {recsys['stage1_ips_covis_recall']:.1%} | "
f"NDCG {recsys['stage1_ndcg_at_10']:.3f}->{recsys['stage2_ndcg_at_10']:.3f}"
),
"unit": f"LOO Leak +{recsys['temporal_vs_loo']['loo_inflation_delta']:.1%}",
"status": "critical",
"detail": (
f"Platt ECE drops {recsys['uncalibrated_ece']:.3f}->"
f"{recsys['calibrated_ece']:.3f}; IPS+Covis lifts R@{k_ret} "
f"{recsys['stage1_pop_biased_recall']:.1%}->"
f"{recsys['stage1_ips_covis_recall']:.1%}."
),
},
{
"id": "kpi_mmr_diversity_and_margin",
"label": "Stage 3 MMR Diversity & Coverage",
"value": (
f"ILD {recsys['pure_top10_ild']:.3f}->{recsys['mmr_top10_ild']:.3f} | "
f"Cov {recsys['mmr_top10_coverage']:.1%}"
),
"unit": f"Margin ${recsys['mmr_expected_margin_usd']:.2f}",
"status": "ok",
"detail": (
f"MMR raises catalog coverage {recsys['pure_top10_coverage']:.1%}->"
f"{recsys['mmr_top10_coverage']:.1%} and expected margin "
f"${recsys['pure_expected_margin_usd']:.2f}->"
f"${recsys['mmr_expected_margin_usd']:.2f}."
),
},
]
bars = [
{
"id": "bar_curse_contrast_decay",
"title": "Curse of Dimensionality: Isotropic Contrast Ratio (D_max-D_min)/D_min across Dim d",
"metric_label": "Contrast Ratio",
"items": [
{
"label": f"d={int(r['dim'])}",
"value": max(r["iso_contrast_ratio"], 1e-4),
"display": f"{r['iso_contrast_ratio']:.3f} (shell {r['shell_volume_frac']:.1%})",
"css_class": (
"is-fast" if r["dim"] <= 8 else ("is-mid" if r["dim"] <= 32 else "is-slow")
),
}
for r in curse[:4]
],
},
{
"id": "bar_knn_scale_trap_metrics",
"title": "Exact k-NN Metric Accuracy under Mixed Feature Units & Correlated Ellipses",
"metric_label": "Test Accuracy",
"items": [
{
"label": "unweighted_l2_raw",
"value": scale_trap["raw_l2_acc"],
"display": f"{scale_trap['raw_l2_acc']:.1%}",
"css_class": "is-slow",
},
{
"label": "standardized_l1",
"value": scale_trap["std_l1_acc"],
"display": f"{scale_trap['std_l1_acc']:.1%}",
"css_class": "is-mid",
},
{
"label": "standardized_l2",
"value": scale_trap["std_l2_acc"],
"display": f"{scale_trap['std_l2_acc']:.1%}",
"css_class": "is-mid",
},
{
"label": "mahalanobis_whitened",
"value": scale_trap["mahalanobis_acc"],
"display": f"{scale_trap['mahalanobis_acc']:.1%}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_filtered_ann_selectivity",
"title": "Filtered Vector Search at Selectivity s=2% (Recall@10)",
"metric_label": "Recall@10",
"items": [
{
"label": "post_filter_starvation",
"value": max(filtered["post_filter_recall_at_10"], 1e-4),
"display": (
f"{filtered['post_filter_recall_at_10']:.1%} "
f"({filtered['post_filter_avg_returned']:.1f}/10)"
),
"css_class": "is-slow",
},
{
"label": "pre_filter_graph_disconnect",
"value": max(filtered["pre_filter_graph_recall_at_10"], 1e-4),
"display": f"{filtered['pre_filter_graph_recall_at_10']:.1%}",
"css_class": "is-slow",
},
{
"label": "iterative_scan_pgvector_08",
"value": filtered["iterative_scan_recall_at_10"],
"display": f"{filtered['iterative_scan_recall_at_10']:.1%}",
"css_class": "is-fast",
},
{
"label": "hnsw_unfiltered_ef96",
"value": hnsw_best["recall_at_10"],
"display": f"{hnsw_best['recall_at_10']:.1%}",
"css_class": "is-fast",
},
],
},
{
"id": "bar_recsys_funnel_uplift",
"title": "E-Commerce Multi-Stage RecSys: NDCG@10, Diversity (ILD) & Catalog Coverage",
"metric_label": "Score",
"items": [
{
"label": "stage1_ndcg10",
"value": recsys["stage1_ndcg_at_10"],
"display": f"NDCG {recsys['stage1_ndcg_at_10']:.3f}",
"css_class": "is-mid",
},
{
"label": "stage2_pit_ndcg10",
"value": recsys["stage2_ndcg_at_10"],
"display": f"NDCG {recsys['stage2_ndcg_at_10']:.3f}",
"css_class": "is-fast",
},
{
"label": "pure_top10_ild",
"value": recsys["pure_top10_ild"],
"display": f"ILD {recsys['pure_top10_ild']:.3f}",
"css_class": "is-slow",
},
{
"label": "mmr_reranked_ild",
"value": recsys["mmr_top10_ild"],
"display": f"ILD {recsys['mmr_top10_ild']:.3f}",
"css_class": "is-fast",
},
],
},
]
tables = [
{
"id": "tbl_curse_and_kdtree",
"title": "Curse of Dimensionality (Isotropic vs 8D Manifold) & KD-Tree Scan Collapse",
"columns": ["Dim d", "Shell (5%) Vol", "Iso Contrast", "Manifold Contrast", "KD-Tree Scan%"],
"rows": [
[
str(int(r["dim"])),
f"{r['shell_volume_frac']:.2%}",
f"{r['iso_contrast_ratio']:.3f}",
f"{r['manifold_contrast_ratio']:.3f}",
f"{kdtree['d4']['mean_visit_frac']:.1%}"
if int(r["dim"]) == 2
else (
f"{kdtree['d64']['mean_visit_frac']:.1%}"
if int(r["dim"]) >= 32
else "—"
),
]
for r in curse
],
},
{
"id": "tbl_hnsw_pareto",
"title": "HNSW efSearch Pareto Frontier vs IVF-PQ ADC Compression",
"columns": ["Index / Mode", "Param", "Recall@10", "Visited / Scanned", "Bytes / Vec"],
"rows": [
[
"HNSW (M=12)",
f"efSearch={int(r['ef_search'])}",
f"{r['recall_at_10']:.3f}",
f"{r['mean_dist_evals']:.1f} ({r['scan_frac']:.1%})",
f"{hnsw['bytes_per_vector']:.0f} B",
]
for r in hnsw["pareto_sweep"][1::2]
]
+ [
[
"IVF-PQ (ADC)",
f"nprobe={int(r['nprobe'])}, rescore={int(r['rescore_top_m'])}",
f"{r['recall_at_10']:.3f}",
f"{r['mean_scanned']:.1f} cands",
f"{ivfpq['pq_code_bytes']:.0f} B ({ivfpq['compression_ratio']:.0f}x)",
]
for r in (ivfpq["sweep"][1], ivfpq["sweep"][-1])
],
},
{
"id": "tbl_cv_elbow_and_scann",
"title": "Exact k-NN CV Elbow Trap (k=1 Train 0.0) & ScaNN Anisotropic MIPS",
"columns": ["Experiment", "Setting", "Metric A", "Metric B", "Takeaway"],
"rows": [
[
"kNN Elbow Trap",
"k=1 (In-Sample)",
f"Train Err={cv_k['k1_train_error']:.3f}",
f"CV Err={cv_k['k1_cv_error']:.3f}",
f"Best CV k={cv_k['best_k']} ({cv_k['best_cv_error']:.3f})",
],
[
"Cover-Hart Bound",
"Bayes R* Check",
f"R*={scale_trap['bayes_risk_est']:.3f}",
f"2R*(1-R*)={scale_trap['cover_hart_upper_bound']:.3f}",
f"1-NN CV={cv_k['k1_cv_error']:.3f} <= Bound",
],
[
"ScaNN MIPS Quant",
"Isotropic vs Aniso",
f"Iso MSE={scann['isotropic_top20_mips_mse']:.3f}",
f"Aniso MSE={scann['anisotropic_top20_mips_mse']:.3f}",
(
f"Recall@10 {scann['isotropic_mips_recall_at_10']:.3f}->"
f"{scann['anisotropic_mips_recall_at_10']:.3f}"
),
],
],
},
{
"id": "tbl_multistage_recsys",
"title": "E-Commerce Multi-Stage RecSys (Global Temporal Split vs LOO & MMR)",
"columns": ["Stage / Method", "Recall / NDCG", "MAP@10 / ECE", "ILD@10 / Cov", "Margin (USD)"],
"rows": [
[
"Stage 1 (Pop-Biased)",
f"R@{k_ret}={recsys['stage1_pop_biased_recall']:.3f}",
"—",
f"Cov20={recsys['stage1_pop_biased_cov20']:.1%}",
"—",
],
[
"Stage 1 (IPS + CoVis HNSW)",
f"R@{k_ret}={recsys['stage1_ips_covis_recall']:.3f}",
f"NDCG={recsys['stage1_ndcg_at_10']:.3f}",
f"Cov20={recsys['stage1_ips_covis_cov20']:.1%}",
"—",
],
[
"Stage 2 (PIT + Platt)",
f"NDCG@10={recsys['stage2_ndcg_at_10']:.3f}",
f"MAP={recsys['stage2_map_at_10']:.3f} | ECE={recsys['calibrated_ece']:.3f}",
f"Cov10={recsys['pure_top10_coverage']:.1%}",
f"${recsys['pure_expected_margin_usd']:.2f}",
],
[
"Stage 3 (MMR Re-rank)",
f"NDCG@10={recsys['mmr_ndcg_at_10']:.3f}",
f"MAP={recsys['stage2_map_at_10']:.3f} | Uncal={recsys['uncalibrated_ece']:.3f}",
f"ILD={recsys['mmr_top10_ild']:.3f} | Cov={recsys['mmr_top10_coverage']:.1%}",
f"${recsys['mmr_expected_margin_usd']:.2f}",
],
],
},
]
return {
"config": {"seed": seed, "quick": quick},
"workbench_panels": {"kpis": kpis, "bars": bars, "tables": tables},
"distance_and_ann": {
"curse_of_dimensionality": curse,
"scale_trap_and_cv": scale_trap,
"kdtree_collapse": kdtree,
"hnsw_pareto": hnsw,
"ivfpq_adc": ivfpq,
"scann_mips": scann,
"filtered_search": filtered,
},
"multistage_recsys": recsys,
}
"""End-to-end CLI benchmark runner for Lab 05: kNN/ANN & E-Commerce Multi-Stage RecSys."""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
try:
import recsys_ann_lab # noqa: F401
except ImportError:
_SRC_DIR = Path(__file__).resolve().parents[1] / "src"
if str(_SRC_DIR) not in sys.path:
sys.path.insert(0, str(_SRC_DIR))
from recsys_ann_lab.multistage_recsys import run_full_ch11_lab05_benchmarks # noqa: E402
def parse_args(argv: list[str] | None = None) -> argparse.Namespace:
"""Parse CLI arguments for Lab 05 RecSys & Vector Retrieval benchmark."""
parser = argparse.ArgumentParser(
description="Run Ch 11 + Lab 05: kNN/ANN Vector Retrieval & E-Commerce Multi-Stage RecSys."
)
parser.add_argument("--seed", type=int, default=42, help="Deterministic RNG seed.")
parser.add_argument(
"--quick",
action="store_true",
help="Run lighter sample sizes for fast CI verification.",
)
parser.add_argument(
"--output",
type=str,
default="artifacts/ch11_lab05_results.json",
help="Output JSON artifact path.",
)
return parser.parse_args(argv)
def main(argv: list[str] | None = None) -> int:
"""Execute benchmarks, print formatted summary telemetry, and save JSON artifact."""
args = parse_args(argv)
payload = run_full_ch11_lab05_benchmarks(seed=args.seed, quick=args.quick)
payload["config"]["output"] = args.output
da = payload["distance_and_ann"]
cd = da["curse_of_dimensionality"]
st = da["scale_trap_and_cv"]
kd = da["kdtree_collapse"]
hs = da["hnsw_pareto"]
pq = da["ivfpq_adc"]
sc = da["scann_mips"]
fl = da["filtered_search"]
rs = payload["multistage_recsys"]
k_ret = rs["k_retrieval"]
print("=== Ch 11 + Lab 05: Vector Retrieval (ANN) & E-Commerce Multi-Stage RecSys ===")
print(
f"[1] Curse & Metrics: Contrast d=2 {cd[0]['iso_contrast_ratio']:.2f} -> "
f"d=512 {cd[-1]['iso_contrast_ratio']:.3f} "
f"| Raw L2={st['raw_l2_acc']:.1%} -> Mahalanobis={st['mahalanobis_acc']:.1%}"
)
print(
f"[2] KD-Tree vs HNSW/IVF-PQ/ScaNN: KD d=4 {kd['d4']['mean_visit_frac']:.1%} -> "
f"d=64 {kd['d64']['mean_visit_frac']:.1%} "
f"| HNSW R@10={hs['pareto_sweep'][-1]['recall_at_10']:.3f} "
f"| IVF-PQ {pq['compression_ratio']:.0f}x (R@10={pq['sweep'][-1]['recall_at_10']:.3f}) "
f"| ScaNN MSE {sc['isotropic_top20_mips_mse']:.3f}->"
f"{sc['anisotropic_top20_mips_mse']:.3f}"
)
print(
f"[3] Filtered Search (s={fl['selectivity']:.1%}): "
f"Post={fl['post_filter_recall_at_10']:.3f} ({fl['post_filter_avg_returned']:.1f}/10) "
f"| Pre={fl['pre_filter_graph_recall_at_10']:.3f} "
f"-> Iterative={fl['iterative_scan_recall_at_10']:.3f}"
)
print(
f"[4] RecSys (Temporal Split, LOO Leak=+{rs['temporal_vs_loo']['loo_inflation_delta']:.3f}): "
f"S1 R@{k_ret} {rs['stage1_pop_biased_recall']:.3f}->"
f"{rs['stage1_ips_covis_recall']:.3f} "
f"| S2 NDCG={rs['stage2_ndcg_at_10']:.3f} "
f"(ECE {rs['uncalibrated_ece']:.3f}->{rs['calibrated_ece']:.3f}) "
f"| S3 MMR ILD {rs['pure_top10_ild']:.3f}->{rs['mmr_top10_ild']:.3f}, "
f"Cov {rs['pure_top10_coverage']:.1%}->{rs['mmr_top10_coverage']:.1%}"
)
out_path = Path(args.output)
out_path.parent.mkdir(parents=True, exist_ok=True)
out_path.write_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n", encoding="utf-8")
return 0
if __name__ == "__main__":
raise SystemExit(main())
"""16 automated unit, mathematical, anti-leakage & security AST tests for Lab 05 (recsys_ann_lab)."""
from __future__ import annotations
import ast
import json
import math
import subprocess
import sys
from pathlib import Path
import numpy as np
import pandas as pd
import pytest
from pydantic import ValidationError
from scipy.spatial.distance import cdist
from sklearn.neighbors import KDTree as SklearnKDTree
from sklearn.neighbors import KNeighborsClassifier
from recsys_ann_lab.distance_and_ann import (
ExactKNNClassifier,
HNSWConfig,
IVFPQConfig,
KDTreeConfig,
KDTreeIndex,
KNNConfig,
analyze_curse_of_dimensionality,
benchmark_hnsw_ef_pareto,
benchmark_ivf_pq_adc,
benchmark_kdtree_collapse,
benchmark_scale_trap_mahalanobis,
scann_anisotropic_mips_demo,
verify_filtered_search_selectivity,
)
from recsys_ann_lab.multistage_recsys import (
MMRConfig,
MultiSourceRetriever,
PointInTimeRanker,
RankerConfig,
RecSysDatasetConfig,
RetrievalConfig,
audit_temporal_vs_loo_leakage,
compute_ece,
compute_ild,
compute_ndcg_and_ap,
compute_pit_features,
generate_ecommerce_sessions,
mmr_rerank,
split_global_temporal,
)
LAB_ROOT = Path(__file__).resolve().parents[1]
FORBIDDEN_UNSAFE_IMPORTS = {
"pickle",
"_pickle",
"cPickle",
"joblib",
"cloudpickle",
"dill",
"shelve",
"marshal",
}
# ---------------------------------------------------------------------------
# Test 1: Pydantic Extra-Forbid Contracts & Curse of Dimensionality Decay
# ---------------------------------------------------------------------------
def test_01_pydantic_configs_and_curse_of_dimensionality() -> None:
with pytest.raises(ValidationError):
KNNConfig(unknown_param=123) # type: ignore[call-arg]
with pytest.raises(ValidationError):
HNSWConfig(m_links=1)
with pytest.raises(ValidationError):
IVFPQConfig(n_centroids=512) # exceeds 256 (uint8)
with pytest.raises(ValidationError):
MMRConfig(mmr_lambda=1.5)
rows = analyze_curse_of_dimensionality(dims=(2, 8, 32, 128, 512), n_points=300, seed=42)
shells = [r["shell_volume_frac"] for r in rows]
contrasts = [r["iso_contrast_ratio"] for r in rows]
ratios = [r["iso_d_min_over_d_max"] for r in rows]
assert all(shells[i] < shells[i + 1] for i in range(len(shells) - 1))
assert shells[-1] > 0.999
assert contrasts[0] > contrasts[2] > contrasts[-1]
assert ratios[-1] > ratios[0]
# Low-intrinsic manifold preserves strictly higher contrast than isotropic Gaussian at d=512
assert rows[-1]["manifold_contrast_ratio"] > rows[-1]["iso_contrast_ratio"]
# ---------------------------------------------------------------------------
# Test 2: Exact k-NN Metrics, Cosine=L2 Equivalence, Scale Trap & CV Elbow
# ---------------------------------------------------------------------------
def test_02_exact_knn_metrics_scale_trap_and_mahalanobis_rescue() -> None:
rng = np.random.default_rng(7)
X_raw = rng.normal(0.0, 1.0, size=(60, 8))
Q_raw = rng.normal(0.0, 1.0, size=(10, 8))
X_unit = X_raw / np.linalg.norm(X_raw, axis=1, keepdims=True)
Q_unit = Q_raw / np.linalg.norm(Q_raw, axis=1, keepdims=True)
knn_cos = ExactKNNClassifier(KNNConfig(k=5, metric="cosine")).fit(X_raw, np.zeros(60, dtype=np.int64))
knn_l2u = ExactKNNClassifier(KNNConfig(k=5, metric="l2")).fit(X_unit, np.zeros(60, dtype=np.int64))
_, idx_cos = knn_cos.kneighbors(Q_raw, k=5)
_, idx_l2u = knn_l2u.kneighbors(Q_unit, k=5)
assert np.array_equal(idx_cos, idx_l2u)
res = benchmark_scale_trap_mahalanobis(seed=42, quick=True)
assert res["std_l2_acc"] > res["raw_l2_acc"] + 0.10
assert res["mahalanobis_acc"] > res["std_l2_acc"]
assert res["mahalanobis_acc"] > 0.85
cv = res["cv_k_selection"]
assert cv["k1_train_error"] == 0.0
assert cv["best_k"] > 1
assert cv["best_cv_error"] < cv["k1_cv_error"]
assert cv["k1_cv_error"] <= res["cover_hart_upper_bound"] + 0.05
# ---------------------------------------------------------------------------
# Test 3: Tier 1 KD-Tree Exact Parity with sklearn & High-Dim Collapse
# ---------------------------------------------------------------------------
def test_03_kdtree_exact_parity_with_sklearn_and_high_dim_collapse() -> None:
rng = np.random.default_rng(42)
X4 = rng.normal(0.0, 1.0, size=(300, 4))
Q4 = rng.normal(0.0, 1.0, size=(10, 4))
kd = KDTreeIndex(KDTreeConfig(leaf_size=16)).build(X4)
sk_kd = SklearnKDTree(X4, leaf_size=16)
sk_dists, sk_idx = sk_kd.query(Q4, k=10)
for i in range(10):
idx_got, d_got, _ = kd.query(Q4[i], k=10)
assert np.array_equal(idx_got, sk_idx[i])
assert np.allclose(d_got, sk_dists[i], atol=1e-10)
collapse = benchmark_kdtree_collapse(seed=42, quick=True)
assert collapse["d4"]["exact_recall_at_10"] == 1.0
assert collapse["d64"]["exact_recall_at_10"] == 1.0
assert collapse["d4"]["mean_visit_frac"] < 0.30
assert collapse["d64"]["mean_visit_frac"] > 0.85
# ---------------------------------------------------------------------------
# Test 4: HNSW ef_search Pareto Recall Lift & Memory Accounting
# ---------------------------------------------------------------------------
def test_04_hnsw_pareto_ef_search_lifts_recall_and_memory_formula() -> None:
res = benchmark_hnsw_ef_pareto(seed=42, quick=True)
sweep = res["pareto_sweep"]
assert sweep[-1]["recall_at_10"] >= sweep[0]["recall_at_10"]
assert sweep[-1]["recall_at_10"] >= 0.90
assert sweep[-1]["scan_frac"] < 0.70
# 4*d + 8*M + upper overhead
assert res["bytes_per_vector"] >= 4 * res["dim"] + 8 * res["m_links"]
# ---------------------------------------------------------------------------
# Test 5: IVF-PQ Compression Ratio & ADC + Rescoring Recall
# ---------------------------------------------------------------------------
def test_05_ivf_pq_adc_compression_and_recall_tradeoff() -> None:
res = benchmark_ivf_pq_adc(seed=42, quick=True)
assert res["compression_ratio"] >= 8.0
sweep = res["sweep"]
# Rescoring & higher nprobe lifts recall@10 strictly above coarse low-probe
assert sweep[-1]["recall_at_10"] > sweep[0]["recall_at_10"]
assert sweep[-1]["recall_at_10"] >= 0.80
# ---------------------------------------------------------------------------
# Test 6: ScaNN Anisotropic Quantization Beats Isotropic on MIPS
# ---------------------------------------------------------------------------
def test_06_scann_anisotropic_quantization_beats_isotropic_on_mips() -> None:
sc = scann_anisotropic_mips_demo(seed=42, quick=True)
assert sc["anisotropic_top20_mips_mse"] < sc["isotropic_top20_mips_mse"]
assert sc["anisotropic_mips_recall_at_10"] >= sc["isotropic_mips_recall_at_10"]
# ---------------------------------------------------------------------------
# Test 7: Filtered ANN 2% Selectivity Starvation vs Iterative Scan Rescue
# ---------------------------------------------------------------------------
def test_07_filtered_ann_selectivity_collapse_and_iterative_scan_rescue() -> None:
fl = verify_filtered_search_selectivity(selectivity=0.02, seed=42, quick=True)
assert fl["post_filter_recall_at_10"] < 0.45
assert fl["pre_filter_graph_recall_at_10"] < 0.60
assert fl["iterative_scan_recall_at_10"] >= 0.90
# ---------------------------------------------------------------------------
# Test 8: Global Temporal Split Strictness vs Leave-One-Out Future Leakage
# ---------------------------------------------------------------------------
def test_08_global_temporal_split_strict_vs_leave_one_out_leakage() -> None:
ds = generate_ecommerce_sessions(
RecSysDatasetConfig(n_users=140, n_items=240, n_sessions=750, dim=16), seed=42
)
train_df, cal_df, test_df = split_global_temporal(ds.interactions_df)
assert float(train_df["event_ts"].max()) < float(cal_df["event_ts"].min())
assert float(cal_df["event_ts"].max()) < float(test_df["event_ts"].min())
audit = audit_temporal_vs_loo_leakage(ds, seed=42)
assert audit["global_temporal_is_strict"] is True
assert audit["loo_has_future_leakage"] is True
assert audit["loo_leaky_late_recall_at_40"] > audit["global_temporal_late_recall_at_40"]
# ---------------------------------------------------------------------------
# Test 9: Stage 1 IPS Debiasing & Co-Visitation Beat Popularity Bias
# ---------------------------------------------------------------------------
def test_09_stage1_ips_debiasing_and_covisitation_beat_popularity_baseline() -> None:
ds = generate_ecommerce_sessions(
RecSysDatasetConfig(n_users=140, n_items=240, n_sessions=750, dim=16), seed=42
)
train_df, _, test_df = split_global_temporal(ds.interactions_df)
ret = MultiSourceRetriever(RetrievalConfig(top_k_candidates=120, use_hnsw=True), seed=42).fit(
train_df, ds.item_embeddings, 140
)
m_pop = ret.evaluate_recall_and_coverage(test_df, mode="popularity_biased", k=120)
m_ips = ret.evaluate_recall_and_coverage(test_df, mode="ips_covis", k=120)
assert m_ips["recall_at_120"] > m_pop["recall_at_120"]
assert m_ips["catalog_coverage_top20"] > m_pop["catalog_coverage_top20"]
# ---------------------------------------------------------------------------
# Test 10: Stage 2 PIT Feature Ranker Beats Stage 1 NDCG@10 & MAP@10
# ---------------------------------------------------------------------------
def test_10_stage2_pit_ranker_beats_stage1_ndcg_and_map() -> None:
ds = generate_ecommerce_sessions(
RecSysDatasetConfig(n_users=140, n_items=240, n_sessions=750, dim=16), seed=42
)
train_df, cal_df, test_df = split_global_temporal(ds.interactions_df)
ret = MultiSourceRetriever(RetrievalConfig(top_k_candidates=120, use_hnsw=True), seed=42).fit(
train_df, ds.item_embeddings, 140
)
ranker = PointInTimeRanker(RankerConfig(neg_samples_per_session=16), seed=42).fit(
train_df, cal_df, ret, ds.items_df, ds.item_embeddings
)
hist_all = pd.concat([train_df, cal_df, test_df], ignore_index=True)
assert ret.covis_scores_ is not None
s1_nd, s2_nd, s1_ap, s2_ap = [], [], [], []
for row in test_df.iloc[:80].itertuples(index=False):
cands, s1_sc = ret.retrieve(int(row.user_id), (int(row.ctx_item_1), int(row.ctx_item_2)), k=120)
rel_set = set(row.relevant_items)
n1, a1 = compute_ndcg_and_ap(cands, rel_set, k=10)
s1_nd.append(n1)
s1_ap.append(a1)
_, p_cal = ranker.score_candidates(
int(row.user_id),
float(row.event_ts),
(int(row.ctx_item_1), int(row.ctx_item_2)),
cands,
s1_sc,
hist_all,
ds.items_df,
ds.item_embeddings,
ret.covis_scores_,
)
ranked = cands[np.argsort(-p_cal)]
n2, a2 = compute_ndcg_and_ap(ranked, rel_set, k=10)
s2_nd.append(n2)
s2_ap.append(a2)
assert float(np.mean(s2_nd)) > float(np.mean(s1_nd))
assert float(np.mean(s2_ap)) > float(np.mean(s1_ap))
# ---------------------------------------------------------------------------
# Test 11: Platt Calibration on D_cal Strictly Reduces Test ECE & Brier
# ---------------------------------------------------------------------------
def test_11_platt_calibration_improves_ece_and_brier() -> None:
ds = generate_ecommerce_sessions(
RecSysDatasetConfig(n_users=140, n_items=240, n_sessions=750, dim=16), seed=42
)
train_df, cal_df, test_df = split_global_temporal(ds.interactions_df)
ret = MultiSourceRetriever(RetrievalConfig(top_k_candidates=100, use_hnsw=False), seed=42).fit(
train_df, ds.item_embeddings, 140
)
ranker = PointInTimeRanker(RankerConfig(neg_samples_per_session=16), seed=42).fit(
train_df, cal_df, ret, ds.items_df, ds.item_embeddings
)
hist_all = pd.concat([train_df, cal_df, test_df], ignore_index=True)
assert ret.covis_scores_ is not None
ys, pu, pc = [], [], []
for row in test_df.iloc[:100].itertuples(index=False):
cands, s1_sc = ret.retrieve(int(row.user_id), (int(row.ctx_item_1), int(row.ctx_item_2)), k=100)
p_uncal, p_cal = ranker.score_candidates(
int(row.user_id),
float(row.event_ts),
(int(row.ctx_item_1), int(row.ctx_item_2)),
cands,
s1_sc,
hist_all,
ds.items_df,
ds.item_embeddings,
ret.covis_scores_,
)
ys.append(np.isin(cands, list(row.relevant_items)).astype(np.int64))
pu.append(p_uncal)
pc.append(p_cal)
y_all = np.concatenate(ys)
pu_all = np.concatenate(pu)
pc_all = np.concatenate(pc)
assert compute_ece(y_all, pc_all) < compute_ece(y_all, pu_all) * 0.5
brier_uncal = float(np.mean((pu_all - y_all) ** 2))
brier_cal = float(np.mean((pc_all - y_all) ** 2))
assert brier_cal < brier_uncal
# ---------------------------------------------------------------------------
# Test 12: Stage 3 MMR Re-Ranking Lifts Intra-List Diversity (ILD) & Coverage
# ---------------------------------------------------------------------------
def test_12_stage3_mmr_reranking_raises_ild_and_catalog_coverage() -> None:
ds = generate_ecommerce_sessions(
RecSysDatasetConfig(n_users=140, n_items=420, n_sessions=600, dim=16), seed=42
)
margins = ds.items_df["margin_usd"].to_numpy(dtype=np.float64)
train_df, cal_df, test_df = split_global_temporal(ds.interactions_df)
ret = MultiSourceRetriever(RetrievalConfig(top_k_candidates=120, use_hnsw=False), seed=42).fit(
train_df, ds.item_embeddings, 140
)
ranker = PointInTimeRanker(RankerConfig(neg_samples_per_session=16), seed=42).fit(
train_df, cal_df, ret, ds.items_df, ds.item_embeddings
)
hist_all = pd.concat([train_df, cal_df, test_df], ignore_index=True)
assert ret.covis_scores_ is not None
pure_ild, mmr_ild = [], []
pure_cov, mmr_cov = set(), set()
pure_cfg = MMRConfig(top_k=10, candidate_pool_size=60, mmr_lambda=1.0, margin_blend=0.0)
mmr_cfg = MMRConfig(top_k=10, candidate_pool_size=60, mmr_lambda=0.55, margin_blend=0.25)
for row in test_df.itertuples(index=False):
cands, s1_sc = ret.retrieve(int(row.user_id), (int(row.ctx_item_1), int(row.ctx_item_2)), k=120)
_, p_cal = ranker.score_candidates(
int(row.user_id),
float(row.event_ts),
(int(row.ctx_item_1), int(row.ctx_item_2)),
cands,
s1_sc,
hist_all,
ds.items_df,
ds.item_embeddings,
ret.covis_scores_,
)
p_sl = mmr_rerank(cands, p_cal, margins, ds.item_embeddings, config=pure_cfg)
m_sl = mmr_rerank(cands, p_cal, margins, ds.item_embeddings, config=mmr_cfg)
pure_ild.append(compute_ild(p_sl, ds.item_embeddings))
mmr_ild.append(compute_ild(m_sl, ds.item_embeddings))
pure_cov.update(p_sl.tolist())
mmr_cov.update(m_sl.tolist())
assert float(np.mean(mmr_ild)) > float(np.mean(pure_ild)) + 0.05
assert len(mmr_cov) > len(pure_cov)
# ---------------------------------------------------------------------------
# Test 13: Point-in-Time Feature Causality Canary (Zero Future Look-Ahead)
# ---------------------------------------------------------------------------
def test_13_point_in_time_feature_causality_canary() -> None:
ds = generate_ecommerce_sessions(
RecSysDatasetConfig(n_users=60, n_items=100, n_sessions=300, dim=16), seed=42
)
train_df, _, test_df = split_global_temporal(ds.interactions_df)
ret = MultiSourceRetriever(RetrievalConfig(top_k_candidates=40, use_hnsw=False), seed=42).fit(
train_df, ds.item_embeddings, 60
)
assert ret.covis_scores_ is not None
row = test_df.iloc[10]
q_ts = float(row["event_ts"])
cands, s1_sc = ret.retrieve(int(row["user_id"]), (int(row["ctx_item_1"]), int(row["ctx_item_2"])), k=40)
hist_clean = ds.interactions_df.copy()
feats_clean = compute_pit_features(
int(row["user_id"]),
q_ts,
(int(row["ctx_item_1"]), int(row["ctx_item_2"])),
cands,
s1_sc,
hist_clean,
ds.items_df,
ds.item_embeddings,
ret.covis_scores_,
)
# Corrupt ALL future rows (event_ts >= q_ts) in history_df
hist_poisoned = hist_clean.copy()
future_mask = hist_poisoned["event_ts"] >= q_ts
hist_poisoned.loc[future_mask, "purchased"] = 1
hist_poisoned.loc[future_mask, "target_item_id"] = int(cands[0])
feats_poisoned = compute_pit_features(
int(row["user_id"]),
q_ts,
(int(row["ctx_item_1"]), int(row["ctx_item_2"])),
cands,
s1_sc,
hist_poisoned,
ds.items_df,
ds.item_embeddings,
ret.covis_scores_,
)
assert np.array_equal(feats_clean, feats_poisoned)
# ---------------------------------------------------------------------------
# Test 14: CLI Demo Quick Flag, Output Contract & Finite workbench_panels
# ---------------------------------------------------------------------------
def test_14_cli_demo_quick_flag_and_workbench_panels_contract(tmp_path: Path) -> None:
out_quick = tmp_path / "quick.json"
script_path = LAB_ROOT / "scripts" / "run_lab_demo.py"
proc = subprocess.run(
[sys.executable, str(script_path), "--seed", "42", "--quick", "--output", str(out_quick)],
cwd=str(LAB_ROOT),
capture_output=True,
text=True,
encoding="utf-8",
check=False,
)
assert proc.returncode == 0, f"CLI failed:\n{proc.stdout}\n{proc.stderr}"
payload = json.loads(out_quick.read_text(encoding="utf-8"))
assert payload["config"]["quick"] is True
assert payload["config"]["seed"] == 42
for key in ("config", "workbench_panels", "distance_and_ann", "multistage_recsys"):
assert key in payload
panels = payload["workbench_panels"]
assert len(panels["kpis"]) == 6
for kpi in panels["kpis"]:
assert kpi["status"] in {"ok", "warn", "critical"}
assert isinstance(kpi["value"], str) and len(kpi["value"]) > 0
assert len(panels["bars"]) == 4
for bar in panels["bars"]:
assert len(bar["items"]) == 4
for item in bar["items"]:
assert item["css_class"] in {"is-fast", "is-mid", "is-slow"}
val = item["value"]
assert isinstance(val, (int, float)) and math.isfinite(val) and val > 0.0
assert len(panels["tables"]) == 4
for tbl in panels["tables"]:
assert len(tbl["columns"]) >= 4
assert len(tbl["rows"]) >= 3
# ---------------------------------------------------------------------------
# Test 15: Tier 2 SciPy & Scikit-Learn Exact Numerical Parity
# ---------------------------------------------------------------------------
def test_15_tier2_sklearn_scipy_parity_exact_knn_and_distance() -> None:
rng = np.random.default_rng(99)
X_tr = rng.normal(0.0, 1.0, size=(120, 6))
y_tr = (X_tr[:, 0] + 0.5 * X_tr[:, 1] > 0.0).astype(np.int64)
X_te = rng.normal(0.0, 1.0, size=(25, 6))
# Compare pairwise L1 and L2 against scipy.spatial.distance.cdist
knn_l1 = ExactKNNClassifier(KNNConfig(k=5, metric="l1")).fit(X_tr, y_tr)
assert np.allclose(knn_l1.pairwise_distances(X_te), cdist(X_te, X_tr, metric="cityblock"), atol=1e-10)
knn_l2 = ExactKNNClassifier(KNNConfig(k=5, metric="l2")).fit(X_tr, y_tr)
assert np.allclose(knn_l2.pairwise_distances(X_te), cdist(X_te, X_tr, metric="euclidean"), atol=1e-10)
sk_knn = KNeighborsClassifier(n_neighbors=5, metric="euclidean").fit(X_tr, y_tr)
assert np.array_equal(knn_l2.predict(X_te), sk_knn.predict(X_te))
# ---------------------------------------------------------------------------
# Test 16: Security-Only AST Deserialization Guard (Allow SOTA Libraries!)
# ---------------------------------------------------------------------------
def test_16_security_only_ast_deserialization_guard() -> None:
py_files = (
sorted((LAB_ROOT / "src").rglob("*.py"))
+ sorted((LAB_ROOT / "scripts").rglob("*.py"))
+ sorted((LAB_ROOT / "tests").rglob("*.py"))
)
assert len(py_files) >= 5
for py_file in py_files:
tree = ast.parse(py_file.read_text(encoding="utf-8"), filename=str(py_file))
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
root_mod = alias.name.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, (
f"Unsafe deserialization import '{alias.name}' in {py_file}"
)
elif isinstance(node, ast.ImportFrom) and node.module is not None:
root_mod = node.module.split(".")[0]
assert root_mod not in FORBIDDEN_UNSAFE_IMPORTS, (
f"Unsafe deserialization from-import '{node.module}' in {py_file}"
)
sigma ~ 2500) với các tỷ lệ hành vi tương quan (rho = 0.88). Phát biểu nào ĐÚNG về chuẩn hóa, độ đo Cosine và khoảng cách Mahalanobis?2 - 2<x_hat, y_hat>, đồng nhất thứ hạng với Cosine và MIPS. Trong Lab 05 (benchmark_scale_trap_mahalanobis), L2 thô bị nhiễu tỷ lệ kéo xuống 53.1%, chuẩn hóa nội nếp nâng lên 82.7%, và làm trắng Mahalanobis đạt 86.5%.
k trong recsys_ann_lab (rủi ro Bayes \(R^* = 0.232\)), khẳng định nào ĐÚNG?r_1NN(x) = 2*r*(x)(1-r*(x)) và lấy kỳ vọng theo hàm lõm cho cận 2R*(1-R*) (0.356 tại R*=0.232, 1-NN CV = 0.298 <= 0.356). Tính nhất quán Stone (1977) đòi hỏi k -> inf đồng thời k/n -> 0.
d = 2 lên d = 512, điều gì xảy ra với thể tích vỏ siêu cầu (\(\epsilon = 5\%\)), tỷ lệ tương phản Beyer và hiệu năng tỉa nhánh của KD-Tree?O(d^(-1/2)) làm khoảng cách co cụm, khiến siêu cầu truy vấn chạm gần như toàn bộ 2^d ô hộp của KD-Tree (21.1% tại d=4 vọt lên 100.0% tại d=64).
HNSW lưu N vector fp32 d chiều với bậc tối đa tầng trên M (M_max0 = 2M), phát biểu nào ĐÚNG về cấu trúc và bộ ba tham số (M, efConstruction, efSearch)?HNSW chứa toàn bộ N nút với bậc tối đa 2M (2M * 4B = 8M byte ID int32), cộng 4d byte vector fp32 (4d + 8M). Tham số efSearch thay đổi hoàn toàn động tại thời điểm truy vấn.
IVF-PQ dùng Asymmetric Distance Computation (ADC) với bảng tra cứu (LUT) lại đạt tỷ lệ nén bộ nhớ khổng lồ mà vẫn giữ Recall@10 cao sau khi tái chấm điểm (rescore)?ADC loại bỏ hoàn toàn sai số lượng tử hóa phía truy vấn q và chỉ tốn M_pq phép tra bảng + cộng cho mỗi vector. Khi ghép thêm rescore_top_m=30 trên đĩa hoặc RAM, IVF-PQ trong Lab 05 vọt từ 0.631 lên 0.969 Recall@10 ở mức nén 16x.
MIPS hoặc quy mô 1 tỷ vector vượt dung lượng RAM máy chủ, đóng góp cốt lõi của ScaNN và DiskANN là gì?<q, x> >= T) phụ thuộc chủ yếu vào sai số song song r_par. Subramanya et al. (NeurIPS 2019) thiết kế đồ thị Vamana đơn tầng thân thiện IOPS NVMe cho 1B vector trên 1 máy 64 GB RAM.
selectivity = 2%, ACORN & pgvector 0.8+)
WHERE brand='X' AND in_stock=1 chỉ khớp s = 2% danh mục (LIMIT 10), vì sao lọc hậu kỳ (Post-Filter) và lọc tiền kỳ trên cạnh đồ thị (Pre-Filter Graph) đều thất bại và giải pháp nào khắc phục?verify_filtered_search_selectivity) tái hiện chính xác sự sụp đổ: Post-filter đạt 7.6% (0.8/10 dòng), Pre-filter graph đạt 5.6%, còn Iterative Scan bắc cầu toàn đồ thị khôi phục trọn 100.0% Recall@10.
recsys_ann_lab), chuỗi phát hiện thực nghiệm nào ĐÚNG?t < t_q (Test 13 Canary), hiệu chuẩn Platt trên D_cal (Test 11), và cân bằng đa dạng-lợi nhuận bằng MMR (Test 12).
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 — Chứng minh Tập trung Vỏ Siêu cầu, Định lý Beyer (1999) & Phục hồi Bẫy Tỷ lệ 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Tính tỷ lệ \((V_d(R) - V_d((1-\epsilon)R))/V_d(R)\) dùng \(V_d(r) \propto r^d\), và áp dụng Delta Method cho \(\|\mathbf{X}-\mathbf{Q}\|_2 = \sqrt{\sum_{j=1}^d Z_j}\) để suy ra \(\operatorname{Std}(D_2)/\mathbb{E}[D_2] = \mathcal{O}(d^{-1/2})\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Gọi analyze_curse_of_dimensionality() trên d=(2,8,32,128,512) và benchmark_scale_trap_mahalanobis() kiểm tra tương quan làm trắng \(\mathbf{R}_s^{-1/2}\tilde{\mathbf{x}}\).
Tiêu chí Đáp án & Số đối chứng
Vỏ 5% tăng 9.75% -> 100.00%, tương phản đẳng hướng tụt 51.520 -> 0.172 (đa tạp 8D giữ 17.472), và Mahalanobis cứu độ chính xác từ 53.1% (L2 thô) lên 86.5%.
Bài tập 2 — Chứng minh Cận Cover–Hart (1967), Consistency Stone & Bẫy Elbow k=1 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết xác suất lỗi có điều kiện tại x khi nhãn truy vấn và nhãn láng giềng độc lập Bernoulli(\(\eta(x)\)): \(2\eta(1-\eta) = 2r^*(1-r^*)\), rồi áp dụng bất đẳng thức Jensen cho hàm lõm \(g(r)=2r(1-r)\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy select_k_via_cv() đối chiếu train_resub_error tại k=1 với cv_error across k=(1,3,5,9,15,25) và kiểm chứng bất đẳng thức Cover–Hart.
Tiêu chí Đáp án & Số đối chứng
k=1 cho train_err = 0.000 (ảo giác ghi nhớ) nhưng CV err = 0.298; OOF CV chọn k=9 (CV err = 0.254), và 0.298 <= 2 * 0.232 * (1 - 0.232) = 0.356.
Bài tập 3 — Sụp đổ KD-Tree (d=4 vs d=64), Đồ thị HNSW & Ngân sách Bộ nhớ 4d+8M 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Chứng minh hình cầu bán kính \(\tau_k\) chạm khoảng \(2^d\) hộp trục AABB khi \(n \ll 2^d\), và lập công thức RAM HNSW gồm 4d byte vector fp32 + 2M * 4 byte tầng 0 + liên kết tầng trên.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy KDTreeIndex (đối chiếu 100% sklearn.neighbors.KDTree) trong benchmark_kdtree_collapse() và quét benchmark_hnsw_ef_pareto().
Tiêu chí Đáp án & Số đối chứng
KD-Tree khớp sklearn 100%, quét 21.1% ở d=4 nhưng vọt lên 100.0% ở d=64. HNSW (M=12, 228 B/vec) đạt 100.0% Recall@10 khi chỉ quét 9.3%–35.8%.
Bài tập 4 — Nén IVF-PQ ADC LUT, Tối ưu Bất đẳng hướng ScaNN & Lọc Metadata s=2% 20%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Viết công thức nghiệm đóng của Guo et al. (2020) cho tâm cụm bất đẳng hướng \(\mathbf{A}\mathbf{c}^* = h_\parallel\bar{\mathbf{x}}\) với \(\mathbf{A} = h_\perp\mathbf{I} + (h_\parallel - h_\perp)\frac{1}{|C|}\sum \hat{\mathbf{x}}_i\hat{\mathbf{x}}_i^\top\).
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy benchmark_ivf_pq_adc(), scann_anisotropic_mips_demo(), và verify_filtered_search_selectivity(selectivity=0.02).
Tiêu chí Đáp án & Số đối chứng
IVF-PQ nén 16x (256B -> 16B) đạt 0.969 Recall@10 khi rescore top-30; ScaNN giảm top-20 MIPS MSE -60.0% (0.284 -> 0.114) và tăng R@10 (0.513 -> 0.543); Iterative Scan cứu lọc 2% từ 7.6% (0.8/10 dòng) về 100.0%.
Bài tập 5 — Kiểm toán Rò rỉ Leave-One-Out vs. Global Temporal Split & PIT Feature Causality 15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Vẽ trục thời gian toàn cục chứng minh vì sao giữ lại giao dịch cuối của từng user cho phép cạnh đồng truy cập từ tương lai của user khác rò vào tập train.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy audit_temporal_vs_loo_leakage() và kiểm thử Canary test_13_point_in_time_feature_causality_canary thay đổi toàn bộ nhãn tương lai t >= q_ts.
Tiêu chí Đáp án & Số đối chứng
Global Temporal giữ 974 < 975 <= 1199 < 1200, còn LOO có max_train_ts = 1478 > min_test_ts = 305 gây thổi phồng giả +32.1% (0.090 -> 0.411). Canary PIT đạt chênh lệch bằng 0.0.
Bài tập 6 — Phễu 3 Tầng E-Commerce (IPS + CoVis -> PIT + Platt -> MMR) & Cổng Bảo mật AST
15%
Gợi ý Bước 1 (Định hướng Nguyên lý)
Kết hợp propensity clipped IPS \(p_i^{-\alpha}\) khử thiên lệch MNAR ở Tầng 1, Platt Scaling trên D_cal ở Tầng 2, và hàm mục tiêu tham lam MMR \(\lambda_{\text{mmr}}\tilde{r}_i - (1-\lambda_{\text{mmr}})\max_{j\in S}\operatorname{sim}(\mathbf{e}_i,\mathbf{e}_j)\) ở Tầng 3.
Gợi ý Bước 2 (Chi tiết Kỹ thuật)
Chạy scripts/run_lab_demo.py --output artifacts/ch11_lab05_results.json, ruff check, và pytest -p no:cacheprovider -v vượt qua toàn bộ 16/16 kiểm thử.
Tiêu chí Đáp án & Số đối chứng
Stage 1 IPS+Covis nâng R@200 50.4% -> 73.1% (Cov20 11.4% -> 85.9%); Stage 2 nâng NDCG@10 0.119 -> 0.169 & hạ ECE 0.147 -> 0.051; Stage 3 MMR nâng ILD 0.551 -> 0.632 và biên lợi nhuận $22.18 -> $25.44, đạt 16/16 pytest và 0 import deserialization bị cấm.