Lesson 07 — Vector Database + RAG
Bốn component tương tác: Brute force vs IVF để thấy lợi ích của cluster index, HNSW visualizer mô phỏng greedy search nhiều tầng, Product Quantization minh họa compression + sai số, và RAG pipeline demo chạy retrieve + augment + generate trên 5 chunk pre-set.
1. Brute force vs IVF — đếm phép tính, đo recall
200 điểm 2D phân thành c = 10 cluster bằng k-means. Query đặt ở một điểm bất kỳ.
Kéo slider nprobe để xem trade-off: tăng nprobe → recall tăng nhưng số distance computation cũng tăng.
- Brute force luôn đúng 100% nhưng phải compare với toàn bộ
N = 200điểm. - IVF chỉ compare với
nprobe × N/cđiểm +ccentroid. - Tăng nprobe → recall ↑, FLOP ↑.
2. HNSW — multi-layer graph search
Graph 3 tầng. Tầng cao ít node, edge dài (đường cao tốc). Tầng thấp nhiều node, edge ngắn (đường nội đô). Bấm ▶ Search để thấy animation greedy từ entry point top-down tới target.
- Search bắt đầu ở entry point của top layer (cam).
- Greedy: di chuyển sang neighbor gần target hơn, dừng khi không có cải thiện.
- Khi dừng ở tầng N → entry point cho tầng N-1.
- Ở layer 0 (xanh): expand
efcandidate quanh greedy result.
3. Product Quantization — nén 8D thành 2 byte
Vector 8 chiều chia thành 2 sub-vector chiều 4. Mỗi sub-vector quantize bằng 1 byte (chọn centroid gần nhất trong codebook 4 entry để dễ nhìn — production dùng 256 entry). Sửa vector input để thấy quá trình encode + sai số reconstruct.
Sub-vector 1 (chiều 0-3) — codebook A
Sub-vector 2 (chiều 4-7) — codebook B
- Codebook 4 entry → 2 bit/sub-vector (production 256 → 8 bit).
- Vector gốc: 8 × 4 = 32 byte (float32).
- PQ encode: 2 sub-vector × 1 byte = 2 byte.
- Compression demo: 16×. Production (768D, m=8): 384×.
4. RAG pipeline — retrieve, augment, generate
5 chunk pre-set về Python. Nhập câu hỏi (tiếng Anh hoặc Việt). System dùng fake embedding dựa trên keyword overlap để mô phỏng cosine similarity — đủ để minh họa pipeline. Click ▶ Run RAG để thấy 4 bước.