Embeddings 101 tìm theo nghĩasearch by meaning

Gần nghĩa thì gần nhau.Similar meaning, nearby points.

Embedding biến văn bản thành toạ độ. Tìm kiếm, phân loại, gom cụm, khử trùng lặp đều chỉ là những cách khác nhau để hỏi cùng một câu: cái gì đang nằm gần cái gì.

Embeddings turn text into coordinates. Search, classification, clustering and deduplication are all different ways of asking one question: what sits near what.

Phần nền cho rag-101. Ở đó embedding là một bước trong quy trình; ở đây nó là toàn bộ câu chuyện.

The groundwork for rag-101. There, embeddings are one step in a pipeline; here, they are the whole story.

θ
Gần truy vấn nhất theo cosine:Nearest to the query by cosine:
    Bấm, kéo, hoặc dùng phím mũi tên trên biểu đồ để xoay truy vấn. Mô hình thật dùng hàng trăm đến hàng nghìn chiều; hai chiều ở đây chỉ để nhìn thấy được. Để ý: độ dài mũi tên của từng câu không ảnh hưởng cosine, chỉ có góc. Click, drag or use the arrow keys on the chart to rotate the query. Real models use hundreds to thousands of dimensions; two are shown only so you can see them. Notice that each sentence's distance from the origin does not affect cosine. Only the angle does.

    Chọn cái nàoWhich one to use

    Đọc từ trên xuống và dừng ở dòng đầu tiên đúng với bạn. Năm dòng đầu không cần embedding, và thường là câu trả lời đúng.

    Read from the top and stop at the first line that fits. The first five lines need no embeddings, and they are often the right answer.

    • Thử trước: không cần embeddingTry first: no embeddings needed
    • Người dùng tìm mã đơn, SKU, mã lỗi, tên riêngUsers search order IDs, SKUs, error codes, proper names Full-text search (BM25)Full-text search (BM25)
    • Lọc theo giá, ngày, danh mục, trạng tháiFiltering by price, date, category, status SQL WHERE
    • Toàn bộ dữ liệu vừa trong context của LLMThe whole dataset fits in an LLM's context Đưa hết vào promptPut it all in the prompt
    • Trùng từng ký tự, hoặc chỉ khác vài từByte-for-byte duplicates, or a few words changed Hash, rồi MinHashHash, then MinHash
    • Phân loại vài trăm mục mỗi ngày, nhãn hay thay đổiClassifying a few hundred items a day, labels change often Gọi LLM trực tiếpCall an LLM directly
    • Khi chữ không bắt được nghĩaWhen words don't capture meaning
    • Người dùng hỏi bằng lời của họ: đồng nghĩa, diễn đạt khác, khác ngôn ngữUsers ask in their own words: synonyms, rephrasing, other languages R1 Tìm theo nghĩaR1 Semantic search
    • Như trên, nhưng truy vấn có lẫn cả mã và tên riêngAs above, but queries also contain IDs and names R1 + BM25 (hybrid)R1 + BM25 (hybrid)
    • Có tập nhãn cố định, khối lượng lớn đều đặnA fixed label set and steady high volume O1 Phân loạiO1 Classification
    • Nhiều dữ liệu nhưng chưa biết nó gồm những gìLots of data and no idea yet what it contains O2 Gom cụmO2 Clustering
    • Cùng một ý lặp lại nhiều lần với chữ khác nhauThe same idea repeated many times in different words O3 Khử trùng lặpO3 Deduplication
    Phép thử năm phútThe five-minute test Lấy 20 truy vấn thật, chạy BM25. Nếu kết quả đúng nằm trong top 5 ở gần như mọi truy vấn, embedding chỉ thêm chi phí. Nếu các truy vấn trượt đều là do người dùng diễn đạt khác với tài liệu, đó mới là lúc cần embedding. Take 20 real queries and run BM25. If the right result is in the top 5 for almost every query, embeddings only add cost. If the misses all come from users phrasing things differently from the documents, that is when you need embeddings.

    Sáu khái niệmSix concepts

    F là nền móng, cần cho mọi thứ còn lại. R là khi có người hỏi. O là khi dữ liệu được đem so với chính nó; ba thẻ O chỉ điểm qua để bạn nhận ra khi nào cần. Mã chỉ để tra cứu, không phải thứ tự học.

    F is the foundation everything else needs. R is when someone asks a question. O is when the data is compared with itself; the three O cards are a quick tour so you recognise when one fits. Codes are for lookup, not a learning order.

    F1

    Embedding

    Nền móngFoundations

    Một hàm biến văn bản thành vector vài trăm đến vài nghìn chiều, sao cho hai đoạn cùng nghĩa nằm gần nhau. "Gần" nghĩa là model đã thấy những thứ như vậy đi cùng nhau, không phải "đúng" hay "giống từng chữ".

    A function that turns text into a vector of a few hundred to a few thousand dimensions, so that passages with the same meaning land close together. "Close" means the model has seen such things go together, not "correct" or "same words".

    Chọn embedding là đổi khả năng khớp chữ chính xác và khả năng giải thích lấy khả năng nhận ra cùng một ý dù được diễn đạt khác đi.

    Choosing embeddings trades exact lexical matching and explainability for the ability to recognise the same idea expressed in different words.

    Dùng choUse for
    FAQ hỗ trợ khách hàng, gợi ý nội dung liên quan, tìm ảnh bằng chữ, đầu vào cho R1 và O1 đến O3.Support FAQs, related-content suggestions, image search by text, input to R1 and O1 through O3.
    ĐượcGain
    Embed một lần, dùng cho nhiều việc. Rẻ hơn nhiều so với gọi LLM (xem trang giá của nhà cung cấp). Model đa ngôn ngữ đặt "con mèo" cạnh "cat".Embed once, reuse for many jobs. Far cheaper than an LLM call (check the vendor's pricing page). Multilingual models place "con mèo" next to "cat".
    Lấy ở đâuWhere from
    API của OpenAI, Voyage AI, Cohere, Google…, hoặc model open-weight tự chạy (BGE, E5). Anthropic không có model embedding riêng; tài liệu của Anthropic giới thiệu Voyage AI.APIs from OpenAI, Voyage AI, Cohere, Google…, or an open-weight model you run yourself (BGE, E5). Anthropic has no embedding model of its own; its docs point to Voyage AI.
    MấtLose
    Đổi model là embed lại toàn bộ. Mù với phủ định và con số. Một triệu vector 1.536 chiều float32 chiếm khoảng 6,1 GB.Switching models means re-embedding everything. Blind to negation and numbers. One million 1,536-dim float32 vectors take about 6.1 GB.

    Dấu hiệu nhận biết:Telltale sign: người dùng diễn đạt cùng một ý theo nhiều cách khác nhau.users express the same idea in many different ways.

    F2

    Độ đo tương đồngSimilarity measures

    Nền móngFoundations

    Một con số cho biết hai vector giống nhau đến đâu. Khi mọi vector đã chuẩn hoá về độ dài 1, cosine, dot product và khoảng cách L2 cho ra cùng một thứ hạng, vì |a−b|² = 2 − 2·cos θ.

    A number that says how alike two vectors are. Once every vector is normalised to length 1, cosine, dot product and L2 distance give the same ranking, because |a−b|² = 2 − 2·cos θ.

    Chọn một độ đo tương đồng đơn lẻ là đổi toàn bộ sắc thái của quan hệ (hỏi–đáp, bao hàm, mâu thuẫn) lấy một con số rẻ và nhanh để xếp hạng.

    Choosing a single similarity measure trades away every nuance of the relationship (question–answer, entailment, contradiction) for one cheap, fast number to rank by.

    Dùng choUse for
    Xếp hạng top-k, ngưỡng "đủ giống", chấm eval theo nghĩa, theo dõi drift.Top-k ranking, "similar enough" thresholds, meaning-based eval scoring, drift monitoring.
    ĐượcGain
    Không cần huấn luyện. So một truy vấn với 100.000 vector mất vài mili giây. Cosine bỏ qua độ dài văn bản.No training needed. One query against 100,000 vectors takes a few milliseconds. Cosine ignores text length.
    MấtLose
    Điểm không so được giữa các model. Không phải xác suất. Hai câu mâu thuẫn về cùng chủ đề vẫn được điểm cao.Scores aren't comparable across models. Not a probability. Two contradicting sentences on one topic still score high.

    Dấu hiệu nhận biết:Telltale sign: cần một con số để nói hai thứ giống nhau đến đâu.you need a number for how alike two things are.

    R1

    Tìm kiếm theo nghĩaSemantic search

    Truy vấn ↔ dữ liệuQuery ↔ corpus

    Embed kho dữ liệu từ trước, embed truy vấn lúc chạy, lấy k vector gần nhất. Bản chạy được trong thực tế thường chạy song song với BM25, trộn bằng RRF, rồi rerank.

    Embed the corpus in advance, embed the query at runtime, fetch the k nearest vectors. Real-world versions usually run alongside BM25, merge with RRF, then rerank.

    Chọn tìm kiếm theo nghĩa là đổi sự chắc chắn của khớp chữ chính xác lấy khả năng hiểu câu hỏi được viết theo cách người dùng nghĩ.

    Choosing semantic search trades the certainty of exact lexical matching for the ability to understand questions written the way users think.

    Dùng choUse for
    Tìm tài liệu nội bộ, tìm sản phẩm theo nhu cầu, gợi ý câu hỏi tương tự, tìm xuyên ngôn ngữ, bước retrieval trong RAG.Internal doc search, product search by need, similar-question suggestions, cross-language search, the retrieval step in RAG.
    ĐượcGain
    Bắt được đồng nghĩa và cách diễn đạt khác. Vài mili giây trên hàng triệu vector với index ANN. Ghép được với BM25 và reranker.Catches synonyms and rephrasing. Milliseconds over millions of vectors with an ANN index. Combines with BM25 and a reranker.
    MấtLose
    Trượt mã, SKU, tên hiếm. Luôn trả về k kết quả kể cả khi không có gì liên quan. ANN bỏ sót nhiều hơn khi lọc metadata chặt.Misses IDs, SKUs, rare names. Always returns k results, even when nothing is relevant. ANN misses more under strict metadata filters.

    Dấu hiệu nhận biết:Telltale sign: log tìm kiếm đầy truy vấn trả về 0 kết quả dù tài liệu có tồn tại.search logs full of zero-result queries for content that exists.

    O1

    Phân loạiClassification

    Dữ liệu ↔ dữ liệuCorpus ↔ corpus

    Dùng vector làm đặc trưng để gán nhãn: kNN, tâm nhãn, hoặc logistic regression trên vài chục ví dụ mỗi nhãn. Model embedding giữ nguyên, không cần fine-tune.

    Use vectors as features to assign labels: kNN, label centroids, or logistic regression on a few dozen examples per label. The embedding model stays frozen; no fine-tuning.

    Chọn phân loại bằng embedding là đổi khả năng suy luận trên từng mục lấy chi phí gần bằng không khi khối lượng lớn.

    Choosing embedding-based classification trades per-item reasoning for near-zero cost at high volume.

    Dùng choUse for
    Định tuyến ticket, nhận diện intent trong chatbot, gắn tag chủ đề, lọc spam sơ bộ, cảm xúc review theo khía cạnh.Ticket routing, chatbot intent detection, topic tagging, first-pass spam filtering, aspect-level review sentiment.
    ĐượcGain
    Dự đoán chỉ là một phép nhân ma trận. Huấn luyện lại trong vài giây. Có xác suất để chuyển ca khó cho người.Prediction is one matrix multiply. Retrains in seconds. Outputs probabilities so hard cases go to a human.
    MấtLose
    Kém khi nhãn phụ thuộc phủ định hoặc con số. Nhãn chồng lấn bị lẫn. Đổi model embedding là huấn luyện lại.Weak when labels hinge on negation or numbers. Overlapping labels blur. A new embedding model means retraining.

    Dấu hiệu nhận biết:Telltale sign: tập nhãn cố định và khối lượng lớn đều đặn.a fixed label set and steady high volume.

    O2

    Gom cụmClustering

    Dữ liệu ↔ dữ liệuCorpus ↔ corpus

    Nhóm các vector gần nhau mà không cần nhãn, rồi đọc mẫu trong từng nhóm để đặt tên. Dùng khi có hàng nghìn mục văn bản tự do chưa ai đọc. Không có đáp án đúng: coi các cụm là giả thuyết và kiểm tra bằng mục thật.

    Group nearby vectors with no labels, then read samples from each group to name it. Use it when thousands of free-text items have never been read. There is no right answer: treat clusters as a hypothesis and check them against real items.

    Dấu hiệu nhận biết:Telltale sign: có nhiều dữ liệu nhưng chưa biết nó gồm những loại gì.lots of data and no idea what kinds of things it contains.

    O3

    Khử trùng lặp theo nghĩaSemantic deduplication

    Dữ liệu ↔ dữ liệuCorpus ↔ corpus

    Coi hai mục là trùng khi điểm giữa hai vector vượt ngưỡng. Chạy hash và MinHash trước vì rẻ hơn nhiều. Ngưỡng quá thấp sẽ gộp nhầm những mục thật sự khác nhau, như hai phiên bản chính sách chỉ khác số tiền.

    Treat two items as duplicates when their vectors score above a threshold. Run hashing and MinHash first; they are far cheaper. A threshold set too low merges items that really differ, such as two policy versions that differ only in an amount.

    Dấu hiệu nhận biết:Telltale sign: cùng một ý xuất hiện nhiều lần với cách viết khác nhau.the same idea appears many times, written differently.

    Bảng đánh đổiTrade-off table

    Cột quan trọng nhất là "hỏng âm thầm khi": embedding hiếm khi báo lỗi, nó chỉ trả về kết quả sai trông có vẻ hợp lý.

    The column that matters most is "fails silently when": embeddings rarely throw errors, they just return wrong results that look plausible.

    Đầu vào bắt buộcRequired input Chi phí lúc chạyRuntime cost Phải tự hiệu chỉnhYou must calibrate Hỏng âm thầm khiFails silently when Thay thế rẻ hơnCheaper alternative
    F1 Embedding Văn bản đã cắt chunkChunked text Một lần gọi model mỗi mụcOne model call per item Model, kích thước chunk, số chiềuModel, chunk size, dimensions Đổi model mà không embed lạiModels switched without re-embedding TF-IDF
    F2 Độ đoSimilarity Hai vector cùng modelTwo vectors, same model Rất nhỏ, tỷ lệ với số chiềuTiny, scales with dimensions NgưỡngThreshold So điểm giữa hai modelScores compared across models Jaccard trên tập từJaccard over word sets
    R1 Tìm theo nghĩaSemantic search Kho dữ liệu + truy vấnCorpus + query Một lần embed + tìm ANN, mili giâyOne embed + ANN lookup, milliseconds k, điểm tối thiểu, trọng số hybridk, minimum score, hybrid weights Truy vấn chứa mã, tên hiếm, phủ địnhQueries with IDs, rare names, negation BM25
    O1 Phân loạiClassification Ví dụ đã gán nhãnLabelled examples Một lần embed + một phép nhân ma trậnOne embed + one matrix multiply Ngưỡng tin cậyConfidence threshold Nhãn phụ thuộc phủ định hoặc con sốLabels hinge on negation or numbers Rule, LLM trực tiếpRules, direct LLM call

    Anti-patterns

    Những lỗi này đều không gây crash. Chúng làm kết quả tệ đi từ từ, cho đến khi ai đó hỏi vì sao tìm kiếm "ngu" thế.

    None of these crash anything. They make results quietly worse until someone asks why search is so dumb.

    Sai lầmMistake Vì sao saiWhy it's wrong Sửa thế nàoFix
    Dựng vector database khi mới có vài nghìn tài liệuA vector database for a few thousand documents Tìm chính xác bằng NumPy đã đủ nhanh. Thêm hệ thống là thêm việc vận hành.Exact search in NumPy is fast enough. Another system is more to operate. NumPy, FAISS trong tiến trình, hoặc pgvector. Chuyển khi đo được là chậm.NumPy, in-process FAISS, or pgvector. Move when you can measure slowness.
    Lấy ngưỡng 0,8 từ một bài blogCopying a 0.8 threshold from a blog Phân phối điểm khác nhau theo model và loại dữ liệu.Score distributions differ by model and data type. Hiệu chỉnh trên 100–200 cặp tự gán nhãn.Calibrate on 100–200 pairs you labelled.
    Trộn vector của hai model trong một indexMixing two models' vectors in one index Hai không gian khác nhau. Kết quả vô nghĩa, không có lỗi nào.Two different spaces. Meaningless results, no errors. Lưu mã model cạnh mỗi vector. Đổi model thì embed lại vào index mới, chạy song song rồi chuyển.Store the model ID with each vector. Re-embed into a new index, run both, then cut over.
    Chỉ tìm bằng vector khi người dùng hay gõ mã sản phẩmVector-only search when users type product codes Embedding làm mờ chuỗi ký tự kiểu mã.Embeddings blur code-like strings. Hybrid BM25 + vector, trộn bằng RRF.Hybrid BM25 + vectors, fused with RRF.
    Embed cả tài liệu 50 trang thành một vectorOne vector for a 50-page document Bị cắt ở giới hạn token, hoặc bị pha loãng thành trung bình mọi ý.Truncated at the token limit, or diluted into an average of every idea. Cắt chunk theo cấu trúc tài liệu, mỗi chunk một ý.Chunk along document structure, one idea per chunk.
    Chọn model theo hạng MTEBPicking a model by MTEB rank MTEB là trung bình trên nhiều tác vụ và miền dữ liệu không phải của bạn.MTEB averages tasks and domains that aren't yours. Dùng MTEB lọc 3–4 ứng viên, rồi đo trên 50–100 truy vấn thật.Shortlist 3–4 with MTEB, then measure on 50–100 real queries.
    Quên tiền tố truy vấn / tài liệuForgetting query / document prefixes Chất lượng giảm âm thầm.Quality drops silently. Đọc model card. Viết riêng embed_query và embed_doc.Read the model card. Write separate embed_query and embed_doc.
    Hiển thị cosine thành "% phù hợp"Showing cosine as "% match" Cosine không phải xác suất.Cosine is not a probability. Hiển thị thứ hạng, hoặc nhãn định tính đã hiệu chỉnh.Show rank, or a calibrated qualitative label.
    Coi vector là đã ẩn danhTreating vectors as anonymised Embedding có thể bị đảo ngược để khôi phục phần lớn văn bản gốc.Embeddings can be inverted to recover much of the source text. Phân quyền, mã hoá và xoá vector giống hệt dữ liệu gốc.Access-control, encrypt and delete vectors exactly like the source.

    Ba câu cần nhớThree things to remember

    Giống về nghĩa không phải là đúng.Embedding không đo "đúng", "trả lời được" hay "giống từng chữ". Phần lớn lỗi nghiêm trọng đến từ việc nhầm bốn thứ này.

    Similar in meaning is not correct.Embeddings don't measure "correct", "answers the question" or "same words". Most serious failures come from confusing these four.

    Điểm cosine chỉ có nghĩa trong một model, trên dữ liệu của bạn.Ngưỡng tự hiệu chỉnh, model tự đánh giá, đổi model là embed lại tất cả.

    A cosine score only means something within one model, on your data.Calibrate your own thresholds, evaluate your own models, and re-embed everything when you switch.

    Thử từ khoá, hash và SQL trước.Embedding là lớp thêm vào cho phần mà chữ không bắt được, không phải lớp thay thế.

    Try keywords, hashing and SQL first.Embeddings are a layer for what words can't catch, not a replacement.