<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Thang Dinh on Medium]]></title>
        <description><![CDATA[Stories by Thang Dinh on Medium]]></description>
        <link>https://medium.com/@tdinh_30671?source=rss-7a7719d2ac90------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BI8X4RdlzZSoiXh_</url>
            <title>Stories by Thang Dinh on Medium</title>
            <link>https://medium.com/@tdinh_30671?source=rss-7a7719d2ac90------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 09:45:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tdinh_30671/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Document Similarities: A Continuous Loop Between POCs and Production]]></title>
            <link>https://medium.com/weborama/document-similarities-a-continuous-loop-between-pocs-and-production-db3acdc019a5?source=rss-7a7719d2ac90------2</link>
            <guid isPermaLink="false">https://medium.com/p/db3acdc019a5</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[faiss]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <dc:creator><![CDATA[Thang Dinh]]></dc:creator>
            <pubDate>Tue, 07 Jan 2025 09:37:07 GMT</pubDate>
            <atom:updated>2025-01-07T09:37:07.506Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we would like to share an overview of our system from two perspectives: POC (Proof Of Concept) and Production. Our aim is to identify a large number of relevant documents using vector similarities.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*av9YD_2s8V-ws9sHoJF2Ng.jpeg" /><figcaption>Exploring document similarity in a digital matrix (generated with DALL-E).</figcaption></figure><h3>Problem and context</h3><p>We handle a variety of data types, including text, audio, and images, which come from multiple sources like URLs, videos, or customer data. For simplicity, we’ll focus on text-based documents. Our challenge can be described as follows:</p><ul><li><strong>Inputs</strong>: a document or a set of documents,</li><li><strong>Output</strong>: Quickly identify the top_k documents that are similar to the input document(s), even when dealing with up to billions of documents.</li></ul><p>Meeting the near-real-time response requirement while managing large volumes is both crucial and challenging for our system.</p><p>At first glance, our task might seem like a recommendation problem. However, recommendation systems typically aim to find a small set of items or documents similar to the target, rather than handling large volumes. For common recommendation scenarios, like music, a user is satisfied if a few of the top 10 songs are relevant, allowing them to continue listening. But at Weborama, all recommended elements must be positive since we’re dealing with an activation use case (boosting the overall performance of a marketing campaign vs. picking the next song). Maximizing the number of high-quality recommended elements is more critical for us.</p><p>Our problem also relates to re-ranking, where the goal is to provide better results — a topic we’re exploring in our roadmap. In this article, though, we’re focusing on similarity.</p><p>The key question is: <strong><em>from our data, how do we define the similarity to choose the top_k?</em></strong> In other words, <strong><em>how can we score documents to compare them effectively?</em></strong></p><p>In this piece, we’re detailing our method based on vector similarities. For additional context on our work with vector embeddings, check out our earlier article “<a href="https://medium.com/weborama/boosting-semantic-categorization-with-recent-ai-paradigm-9357324da74a">Boosting Semantic Categorization with recent AI paradigm</a>”.</p><h3>Vectors and embeddings</h3><p>Unstructured data contains rich semantics, making it tough to analyze. With the rise of Machine Learning (ML) and Deep Learning (DL), embeddings were developed to transform unstructured data into numerical vectors, helping us manage the complexity of these rich semantics. Embeddings are techniques for representing data as vectors to capture meaningful information, semantic relationships, or contextual characteristics.</p><p>While embeddings emphasize the meaningfulness and structure of data representation, a vector refers to the numerical form itself. In the context of vector embeddings, “embeddings” and “vectors” can be used interchangeably, referring to the numerical representations of data where each point is represented by a vector in a high-dimensional space. These representations enable machines to understand and process data more effectively.</p><p>For text data, we have specific types of embeddings: <strong><em>word embeddings</em></strong> for words, <strong><em>sentence embeddings</em></strong> for sentences, and <strong><em>document embeddings</em></strong> for documents, turning them into vectors.</p><p>Vector embeddings can be applied in various areas, boosting efficiency and accuracy in numerous applications. Common use cases include finding similar documents, recommender systems, anomaly detection, improving search relevance with semantic search, and accelerating drug discovery, among others. Brief descriptions of these use cases are available in <a href="https://milvus.io/intro">this document</a>. We’re specifically focusing on using document embeddings to search for similar content by comparing these embedded representations using distance metrics, like <a href="https://en.wikipedia.org/wiki/Cosine_similarity"><em>cosine similarity</em></a>.</p><p>In the remainder of this article, we’ll briefly introduce the architectural design of our system and explain how we handle our pre-production and production environments.</p><h3>Architecture</h3><p>This figure below illustrates a simplified architecture of our production system:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*WiQNecxSknXdSus5LR4UpQ.png" /><figcaption>Simplified Architecture</figcaption></figure><p><strong>Incoming data: </strong>In real-time, our message queue (RabbitMQ), contains documents along with their content. Behind the scenes, we use <a href="https://hbase.apache.org/">HBase</a> to store a large number of document contents.</p><p><strong>Document embedding service (DocEmbService)</strong>:</p><ul><li><strong><em>Read from the message queue</em></strong> to identify which document needs embedding. Document fetching, parsing, preprocessing, and synchronization steps, although critical, are not covered in this article.</li><li><strong>Document embedding<br>- </strong>We leverage a well-suited open multilingual embedding model as the foundation of our system. This model selection stems from ongoing, crucial efforts at Weborama to answer questions like “How to choose a good open embedding model for each kind of data?” and “When and how to upgrade the system with a new embedding model?”.<br>- Every document is swiftly transformed into a vector in near real-time. This service is deployed on a GPU-based cluster to enhance computation speeds, and our code is optimized to maximize GPU capacity utilization.</li></ul><p><strong>Vector database</strong>: Milvus serves as the core database supporting our similarity search.</p><p><strong><em>VectorSimilarService</em></strong> and <strong><em>VectorSimilarAPI</em></strong>: Built upon Milvus, these components can function either as a Batch Service or a <a href="https://www.techtarget.com/searchapparchitecture/definition/RESTful-API#:~:text=A%20RESTful%20API%20is%20an,deleting%20operations%20related%20to%20resources.">REST API</a>. Our batch <strong><em>VectorSimilarService</em></strong> handles large volumes of data.</p><p>During our analysis, we identified a vector database as the core technology for our service. We invite readers to explore the next section for more on this choice. For our tech stack, we use Python-based ecosystems, including Python 3.11, RabbitMQ, FastAPI, Transformers, HuggingFace, Docker, and Kubernetes.</p><h3>Vector database and Milvus</h3><p>To shed light on the concept of a vector database, I’ll summarize some key points from <a href="https://milvus.io/intro">this source</a> that explains it well.</p><p><strong>Vector database</strong></p><ul><li>Are specialized systems designed for managing and retrieving unstructured data through vector embeddings and numerical representations.</li><li>Unlike traditional relational databases that handle structured data with precise search operations, vector databases excel in semantic similarity searches using techniques such as the Approximate Nearest Neighbor (ANN) algorithm.</li></ul><p><strong>Vector Search Library</strong></p><ul><li>Vector search libraries like <a href="https://github.com/facebookresearch/faiss">Faiss</a>, <a href="https://github.com/google-research/google-research/tree/master/scann">ScaNN</a>, and <a href="https://github.com/nmslib/hnswlib">HNSW</a> offer foundational tools for building prototype systems capable of performing efficient similarity searches and dense vector clustering. These libraries, while powerful and open-source, are designed primarily for vector retrieval and offer rapid setup with capabilities like handling large vector collections and providing interfaces for evaluation and parameter tuning. However, they fall short in terms of scalability, multi-tenancy, and dynamic data modification, making them less suitable for larger, more complex datasets and growing user bases.</li></ul><p><strong>Vector search plugins for traditional databases</strong></p><ul><li>Plugins offer vector search capabilities within existing database architectures, functioning as enhancements rather than comprehensive solutions. These plugins lack a full-stack approach to embedding management and vector search, resulting in limitations and suboptimal performance for unstructured data applications.</li></ul><p>Once we established the overall architecture, our next task was to decide “Which vector database should we use in our system?”. Our criteria at Weborama were clear:</p><ul><li><strong>Open-Source</strong>: It should be an open-source solution, aligning with our global policy.</li><li><strong>Big-Volume Support</strong>: It needs to effectively manage our data volume and traffic, up to billions of vectors.</li><li><strong>Batch and Near Real-Time Response</strong>: It should accommodate both use cases.</li><li><strong>Full Maintenance</strong>: It should offer full features like scalability, multi-tenancy, dynamic data modification, and easy maintenance with fault tolerance.</li></ul><p>We conducted a survey focusing on technology and identified some potential candidates among existing solutions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vXmRRdHH8-967EEE" /><figcaption>Vector databases</figcaption></figure><p>We decided to conduct our preliminary experimental study with the following:</p><ul><li><strong>Plugins</strong>: Since our tech stack includes ElasticSearch and Couchbase, we:<br>- First tested the KNN with ElasticSearch version 7.8.0,<br>- Later tried the similarity search feature with Couchbase (mid 2023).</li><li><strong>Vector databases</strong>: We explored open-source options, including Quadrant, Vespa, Weaviate, and Milvus.</li><li><strong>Data</strong>: Our tests involved up to 100 million vectors.</li></ul><p><strong>During this stage, we were focusing on measuring 5 above criteria and having two big results:</strong></p><ul><li><strong>Understanding Vector Database Methods:<br>- </strong>We enhanced our grasp of the state-of-the-art methods used in vector databases. For large datasets, similarity searches are typically <strong><em>approximated</em></strong> using a data structure called an <strong><em>index</em></strong>. <strong><em>Indexing</em></strong> is the process of building this data structure from input vectors. More details on this will be provided in the next section.</li><li><strong>Choosing </strong><a href="https://milvus.io/"><strong>Milvus</strong></a>: Milvus largely meets our criteria for long-term development.<br>- Plugins within ElasticSearch and Couchbase revealed limitations with increasing volume and response times.<br>- Qdrant, Vespa, and Weaviate, which rely solely on HNSW (tested early 2023), struggled with large data.<br>- Our experimental benchmarks and SRE evaluations ultimately led us to choose Milvus.</li></ul><p>Our SRE team has worked to build Milvus clusters with:</p><ul><li>Separate data nodes for indexing and searching to enhance scalability.</li><li>Integration with our Kubernetes cluster.</li><li>Distinct pre-production and production clusters.</li></ul><p>Document vectors are progressively computed, inserted, and indexed into Milvus. It adapts well to scaling up and down based on our traffic input. We’ve resolved quantitative data challenges with our VectorSimilarService by:</p><ul><li>Utilizing Milvus’s <a href="https://milvus.io/docs/v2.3.x/within_range.md">range_search</a> feature to iterate from the largest distance to smaller distances until achieving the desired volume.</li></ul><p>Experimenting with the new <a href="https://milvus.io/api-reference/pymilvus/v2.4.x/ORM/Collection/search_iterator.md">search_iterator</a> feature in Milvus, which improves performance and caching compared to multiple repeated range_search operations. However, as of version 2.4.x, this feature only supports a single input vector, while we often work with multiple vectors. We await future Milvus updates to improve this aspect.</p><p>We also face qualitative data questions, such as:</p><ul><li>Since similarity is calculated approximately, how do we measure effective recall? If the recall is insufficient, how can we optimize our Milvus cluster?</li><li>When and how should we apply different indexing methods to different datasets for optimal performance?</li></ul><p>For answers to these qualitative questions, we invite readers to explore our next article (coming soon) on our experiments with Milvus.</p><h3>Methods used in Vector databases</h3><p>To delve deeper into the methods used for similarity search, we recognize that there exists many similarity search algorithms, which can be applied in diverse domains and can be classed into different categories. Some of these categories include:</p><ul><li>E<strong><em>xact algorithms</em></strong> such as Linear Search, Binary Search etc.,</li><li><strong><em>Distance-based algorithms</em></strong> such as Euclidean, Cosine etc.,</li><li><strong><em>Approximate Algorithm</em></strong> such as Product Quantization, Hierarchical Navigable Small-World (HNSW) Graphs etc,</li></ul><p>For a complete list of these algorithms, you can refer to <a href="https://crucialbits.com/blog/a-comprehensive-list-of-similarity-search-algorithms/">this document</a>.</p><p>In the realm of vector search — especially with massive datasets — libraries often rely on vector similarity scores and Approximate Nearest Neighbors (<strong><em>ANN</em></strong>) algorithms. These leverage Approximate Nearest Neighbors to trade off perfect accuracy for efficiency in high-dimensional embedding spaces at scale. The foundational structure here is an index that stores numerous database vectors, which are gradually added. At search time, a query vector is submitted, and the index returns database vectors closest to the query vector in terms of distance.</p><p>In practical applications, building an index requires prioritizing between recall, latency, and memory usage. For optimal performance, <strong><em>composite indexes</em></strong> are typically used.</p><p>A composite index can be thought of as a series of vector transformations and one or more indexing methods, akin to assembling Lego blocks. This approach allows for stacking multiple indexes and processing steps to create our ‘ideal’ index. However, customization brings a risk of creating indexes with poor recall, latency, or memory usage.</p><p>In summary, a <a href="https://www.pinecone.io/learn/series/faiss/composite-indexes/">composite index may consist</a> of:</p><ul><li><strong>Vector transform</strong>: a pre-processing step applied to vectors before indexing (PCA, OPQ).</li><li><strong>Coarse quantizer</strong>: rough organization of vectors to sub-domains for restricting search scope, including IVF, IMI, and HNSW. It refers to the clustering of vectors to enable non-exhaustive search by limiting the search scope.</li><li><strong>Fine quantizer</strong>: a finer compression of vectors into smaller domains for compressing index size. It describes the compression of vectors into codes (as with PQ). The purpose of this is to reduce the memory usage of the index.</li><li><strong>Refinement</strong>: a final step at search-time which re-orders results using distance calculations on the original flat vectors. Alternatively, another index (non-flat) index can be used.</li></ul><p>For more detailed information about potential components in a composite index, refer to the table and further reading available on this <a href="https://www.pinecone.io/learn/series/faiss/composite-indexes/">page</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jIIooGf_fvDyEaiu" /></figure><p>In Milvus, when dealing with smaller datasets (fewer than 10 million vectors) we utilize the IVF-SQ8 indexing method. For exact similarity searches, we occasionally employ the IVF-FLAT approach. For handling large datasets, we rely on the IVF-PQ. However, from the <a href="https://github.com/zilliztech/attu">Attu UI</a> or with Milvus client, while indexing, we are limited to the usage of params: the number of coarse clusters (‘nlist’), the ‘m’ and ‘nbits’ for the PQ.</p><h3>Faiss, auto-faiss and ElasticSearch for POCs</h3><p>With Milvus set up in our pre-production and production environments, we have confirmed two points we discovered during our vector database selection phase:</p><ul><li><strong>Cost</strong>: Full cluster installations can be quite expensive, so we must approach our Preprod cluster setup prudently.</li><li><strong>Fixed Index Parameters</strong>: It is challenging to benchmark further, especially when comparing different indexing composites as we need multiple indexes of the same data.</li></ul><p>In the data science development cycle at Weborama, we typically investigate:</p><ul><li><strong>Embedding Models</strong>: Evaluation of new open-source embedding models for quality.</li><li><strong>Embedding Strategy</strong>: We focus on both sentence and document embeddings.</li><li><strong>Document Embedding</strong>: Various strategies for selecting text to embed.</li><li><strong>Comparison</strong>: We compare approximate methods with exact methods.</li></ul><p>For our POCs, data is often fixed to facilitate model and method comparisons, meaning real-time data updates aren’t necessary. However, managing multiple versions of the same data becomes expensive with a Milvus cluster. Thus, we decided to use Faiss and ElasticSearch for our POCs. A significant advantage of Faiss is the ability to later control index components to meet dynamic needs.</p><p><a href="https://github.com/facebookresearch/faiss"><strong>Faiss</strong></a><strong> and </strong><a href="https://github.com/criteo/autofaiss"><strong>Autofaiss</strong></a></p><p><a href="https://arxiv.org/pdf/2401.08281">The Faiss library</a>, developed by Facebook (Meta), is one of the first libraries for ANNs. Milvus later uses its<a href="https://milvus.io/docs/knowhere.md"> Knowhere</a> library, which relies on Faiss as one of its core engines. Faiss introduces also the<a href="https://github.com/facebookresearch/faiss/wiki/The-index-factory"> index_factory</a>, allowing for the construction of composite indexes in a clear, elegant manner.</p><p><a href="https://github.com/criteo/autofaiss">Autofaiss</a>, developed by Criteo, automatically creates Faiss indices with optimal similarity search parameters. It selects the best indexing parameters to achieve the highest recall, considering memory and query speed constraints. Specifically, using the<a href="https://github.com/facebookresearch/faiss/wiki/The-index-factory"> Faiss bench-marking</a> and Faiss index_factory, Auto-Faiss provides parameters to identify the best index components and parameters for each component. For instance, it determines optimal batch size, quantization, and minimum values for best neighbors coverage. Details are available in the<a href="https://github.com/criteo/autofaiss/blob/master/autofaiss/external/optimize.py"> autofaiss optimize code</a>. At the end of training index with autofaiss, we obtain metadata information such as:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/0*g_OqNiSkxBcVUDJ0" /></figure><p>Given arbitrary documents as input, we subsequently measure recall in a separate process. It’s important to note that Faiss indexes contain only vectors and their corresponding IDs; they do not integrate or manage document metadata like URLs, titles, descriptions, or content. To achieve this mapping alongside Faiss indexes, we use ElasticSearch.</p><p><a href="https://www.elastic.co/elasticsearch"><strong>Elasticsearch</strong></a></p><p>ElasticSearch is an open-source, distributed, RESTful search and analytics engine. At Weborama, it supports various production services, ranging from log and infrastructure monitoring to our search-based applications. When working with Faiss indexes, which only allow retrieval of vector IDs, ElasticSearch becomes essential for storing associated document information. Specifically, it facilitates:</p><ul><li><strong>Document ID Mapping</strong>: We utilize the same IDs in both ElasticSearch and Faiss indexes to map document content to vectors.</li><li><strong>Document Content Retrieval</strong>: This can be directly observed via ElasticSearch requests.</li></ul><p><strong>Handling Large Corpora</strong>: Faiss indexes can return a large number of IDs, but ElasticSearch queries are limited to returning no more than 10,000 rows at once. To manage this, we developed wrappers that progressively retrieve document contents, querying up to 10,000 documents at a time, until the expected volume is achieved.</p><h3>Conclusions</h3><ul><li>In the nature of our data science work with numerous proof-of-concept projects where only the best results move to production, it’s crucial to have tailored environments and solutions:<br>- <strong>Flexibility in POC Phase</strong>: Utilizing the Faiss library and ElasticSearch gives us flexibility during the POC phase, allowing a comprehensive understanding of index components. This approach is also more cost-effective. Filtering data with ElasticSearch is simpler, more visible, and practical compared to using the <a href="https://github.com/zilliztech/attu">Attu UI</a> with Milvus.<br>- <strong>Milvus in Production</strong>: Milvus proves to be an excellent vector database for our production needs. We have gained experience in managing and scaling the production cluster effectively.</li><li>Our production environment is robust and well-scaled, while the POC process has become more streamlined and efficient:<br>- <strong>Experimentation and validation: </strong>We’ve worked on document embedding across multiple markets and languages (8 languages and about 20 countries) using various embedding models.<br>- <strong>Sentence-based studies</strong>: We have handled databases with up to 115 million vectors.<br>- <strong>Document-based studies</strong>: We have explored different strategies for selecting text to embed.</li></ul><p>This article offers an overview of our approach to tackling the challenge of finding similarities in large volumes. Our system continues to evolve and improve.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db3acdc019a5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/weborama/document-similarities-a-continuous-loop-between-pocs-and-production-db3acdc019a5">Document Similarities: A Continuous Loop Between POCs and Production</a> was originally published in <a href="https://medium.com/weborama">Weborama</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>