<?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 Lester Solbakken on Medium]]></title>
        <description><![CDATA[Stories by Lester Solbakken on Medium]]></description>
        <link>https://medium.com/@lester.solbakken?source=rss-344c89cb19cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ddzY76k6UkdsiMrV</url>
            <title>Stories by Lester Solbakken on Medium</title>
            <link>https://medium.com/@lester.solbakken?source=rss-344c89cb19cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:58:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@lester.solbakken/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[Machine-learned model serving at scale]]></title>
            <link>https://medium.com/data-science/machine-learned-model-serving-at-scale-86f6220132c8?source=rss-344c89cb19cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/86f6220132c8</guid>
            <category><![CDATA[mlops]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[tensorflow]]></category>
            <dc:creator><![CDATA[Lester Solbakken]]></dc:creator>
            <pubDate>Tue, 04 Jan 2022 16:26:24 GMT</pubDate>
            <atom:updated>2022-01-04T16:26:24.876Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*poNDDpG9rx4Ud6uA" /><figcaption>Photo by <a href="https://unsplash.com/@tateisimikito?utm_source=medium&amp;utm_medium=referral">Jukan Tateisi</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Imagine you have a machine-learned model that you would like to use in some application, for instance, a transformer model to generate vector representations from text. You measure the time it takes for a single model evaluation. Then, satisfied that the model can be evaluated quickly enough, you deploy this model to production in some model server. Traffic increases, and suddenly the model is executing much slower and can’t sustain the expected traffic at all, severely missing SLAs. What could have happened?</p><p>You see, most libraries and platforms for evaluating machine-learned models are by default tuned to use all available resources on the machine for model inference. This means parallel execution utilizing a number of threads equal to the number of available cores, or CPUs, on the machine. This is great for a single model evaluation.</p><p>Unfortunately, this breaks down for concurrent evaluations. This is an under-communicated and important point.</p><p>Let’s take a look at what happens. In the following, we serve a transformer model using <a href="https://vespa.ai/">Vespa.ai</a>. Vespa is a highly performant and web-scalable open-source platform for applications that perform real-time data processing over large data sets. Vespa.ai uses <a href="https://onnxruntime.ai/">ONNX Runtime</a> under the hood for model acceleration. We’ll use the original <a href="https://huggingface.co/bert-base-uncased">BERT-base</a> model, a 12-layer, 109 million parameter transformer neural network. We test the performance of this model on a 32-core Xeon Gold 2.6GHz machine. Initially, this model can be evaluated on this particular machine in around 24 milliseconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*Nv0nbbPMq-2utf1e5ju5VA.png" /><figcaption>Concurrency vs latency and throughput. Image by author.</figcaption></figure><p>Here, the blue line is the 95th percentile latency, meaning that 95% of all requests have latency lower than this. The red line is the throughput: the requests per second the machine can handle. The horizontal axis is the number of concurrent connections (clients).</p><p>As the number of simultaneous connections increases, the latency increases drastically. The maximum throughput is reached at around 10 concurrent requests. At that point, the 95th percentile latency is around 150ms, pretty far off from the expected 24ms. The result is a highly variable and poor experience.</p><p>The type of application dictates the optimal balance between low latency and high throughput. For instance, if the model is used for an end-user query, (predictably) low latency is important for a given level of expected traffic. On the other hand, if the model generates embeddings before ingestion in some data store, high throughput might be more important. The driving force for both is cost: how much hardware is needed to support the required throughput. As an extreme example, if your application serves 10 000 queries per second with a 95% latency requirement of 50ms, you would need around 200 machines with the setup above.</p><p>Of course, if you expect only a minimal amount of traffic, this might be totally fine. However, if you are scaling up to thousands of requests per second, this is a real problem. So, we’ll see what we can do to scale this up in the following.</p><h3>Parallel execution of models</h3><p>We need to explain the threading model used during model inference to see what is happening here. In general, there are 3 types of threads: inference (application), inter-operation, and intra-operation threads. This is a common feature among multiple frameworks, such as TensorFlow, PyTorch, and ONNX Runtime.</p><p>The <strong>inference threads</strong> are the threads of the main application. Each request gets handled in its own inference thread, which is ultimately responsible for delivering the result of the model evaluation given the request.</p><p>The <strong>intra-operation threads</strong> evaluate single operations with multi-threaded implementations. This is useful for many operations, such as element-wise operations on large tensors, general matrix multiplications, embedding lookups, and so on. Also, many frameworks chunk together several operations into a higher-level one that can be executed in parallel for performance.</p><p>The <strong>inter-operation threads</strong> are used to evaluate independent parts of the model in parallel. For instance, a model containing two distinct paths joined in the end might benefit from this form of parallel execution. Examples are Wide and Deep models or two-tower encoder architectures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/1*Si-ovhgQvA5LsEv1MGS-gQ.png" /><figcaption>Various thread pools in inference. Image by author.</figcaption></figure><p>In the example above, which uses ONNX Runtime, the default disables the inter-operation threads. However, the number of intra-operation threads is equal to the number of CPUs on the machine. In this case, 32. So, each concurrent request is handled in its own inference thread. Some operations, however, are executed in parallel by employing threads from the intra-operation thread pool. Since this pool is shared between requests, concurrent requests need to wait for available threads to progress in the execution. This is why the latency increases.</p><p>The model contains operations that are run both sequentially and in parallel. That is why throughput increases to a certain level even as latency increases. After that, however, throughput starts decreasing as we have a situation where more threads are performing CPU-bound work than physical cores in the machine. This is obviously detrimental to performance due to excessive thread swapping.</p><h3>Scaling up</h3><p>To avoid this thread over-subscription, we can ensure that each model runs sequentially in its own inference thread. This avoids the competition between concurrent evaluations for the intra-op threads. Unfortunately, it also avoids the benefits of speeding up a single model evaluation using parallel execution.</p><p>Let’s see what happens when we set the number of intra-op threads to 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*tizuGPp3Tbh-OpcnKISt2w.png" /><figcaption>Concurrency vs latency and throughput with 1 intra-op thread. Image by author.</figcaption></figure><p>As seen, the latency is relatively stable up to a concurrency equalling the number of cores on the machine (around 32). After that, latency increases due to the greater number of threads than actual cores to execute them. The throughput also increases to this point, reaching a maximum of around 120 requests per second, which is a 40% improvement. However, the 95th percentile latency is now around 250ms, far from expectations.</p><p>So, the model that initially seemed promising might not be suitable for efficient serving after all.</p><p>The first generation of transformer models, like BERT-base used above, are relatively large and slow to evaluate. As a result, more efficient models that can be used as drop-in replacements using the same tokenizer and vocabulary have been developed. One example is the <a href="https://arxiv.org/abs/2106.04563">XtremeDistilTransformers</a> family. These are distilled from BERT and have similar accuracy as BERT-base on many different tasks with significantly lower computational complexity.</p><p>In the following, we will use the <a href="https://huggingface.co/microsoft/xtremedistil-l6-h256-uncased">XtremeDistil-l6-h256</a> model, which only has around 13M parameters compared to BERT-base’s 109M. Despite having only 12% of the parameter count, the accuracy of this model is very comparable to the full BERT-base model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/652/1*KQYZKMBM0iYk9Oh6kThIgg.png" /><figcaption>Distilled models accuracy. From <a href="https://huggingface.co/microsoft/xtremedistil-l6-h256-uncased">https://huggingface.co/microsoft/xtremedistil-l6-h256-uncased</a>.</figcaption></figure><p>Using the default number of threads (same as available on the system), this model can be evaluated on the CPU is around 4ms. However, it still suffers from the same scaling issue as above with multiple concurrent requests. So, let’s see how this scales with concurrent requests with single-threaded execution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/614/1*l2m-UokU7nf63l_5eawfww.png" /><figcaption>Concurrency vs latency and throughput with 1 intra-op thread on distilled model. Image by author.</figcaption></figure><p>As expected, the latency is much more stable until we reach concurrency levels equalling the number of cores on the machine. This gives a much better and predictable experience. The throughput now tops out at around 1600 requests per second, vastly superior to the other model, which topped out at roughly 120 requests per second. This results in much less hardware needed to achieve wanted levels of performance.</p><h3>Experiment details</h3><p>To measure the effects of scaling, we’ve used Vespa.ai, an open-source platform for building applications that do real-time data processing over large data sets. Designed to be highly performant and web-scalable, it is used for diverse tasks such as search, personalization, recommendation, ads, auto-complete, image and similarity search, comment ranking, and even <a href="https://tech.okcupid.com/vespa-vs-elasticsearch/">finding love</a>.</p><p>Vespa.ai has many integrated <a href="https://docs.vespa.ai/en/features.html">features</a> and supports many use cases right out of the box. Thus, it offers a simplified path to deployment in production without the complexity of maintaining many different subsystems. We’ve used Vespa.ai as an <a href="https://docs.vespa.ai/en/stateless-model-evaluation.html">easy-to-use model server</a> in this post. In Vespa.ai, it is straightforward to tune the <a href="https://docs.vespa.ai/en/stateless-model-evaluation.html">threading model to use</a> for each model:</p><pre>&lt;model-evaluation&gt;<br>  &lt;onnx&gt;<br>    &lt;models&gt;<br>      &lt;model name=&quot;reranker_margin_loss_v4&quot;&gt;<br>        &lt;intraop-threads&gt; number &lt;/intraop-threads&gt;<br>        &lt;interop-threads&gt; number &lt;/interop-threads&gt;<br>        &lt;execution-mode&gt; parallel | sequential &lt;/execution-mode&gt;<br>      &lt;/model&gt;<br>    &lt;/models&gt;<br>  &lt;/onnx&gt;<br>&lt;/model-evaluation&gt;</pre><p>Also, it is easy to scale out horizontally to use additional nodes for model evaluation. We have not explored that in this post.</p><p>The data in this post has been collected using Vespa’s <a href="https://docs.vespa.ai/en/performance/vespa-benchmarking.html">fbench</a> tool, which drives load to a system for benchmarking. Fbench provides detailed and accurate information on how well the system manages the workload.</p><h3>Summary</h3><p>In this post, we’ve seen that the default thread settings are not suitable for model serving in production, particularly for applications with a high degree of concurrent requests. The competition for available threads between parallel model evaluations leads to thread oversubscription and performance suffers. The latency also becomes highly variable.</p><p>The problem is the shared intra-operation thread pool. Perhaps a different threading model should be considered, which allows for utilizing multiple threads in low traffic situations, but degrades to sequential evaluation when high concurrency is required.</p><p>Currently however, the solution is to ensure that models are running in their own threads. To manage the increased latency, we turned to model distillation, which effectively lowers the computational complexity without sacrificing accuracy. There are additional optimizations available which we did not touch upon here, such as <a href="https://blog.vespa.ai/from-research-to-production-scaling-a-state-of-the-art-machine-learning-system/">model quantization</a>. Another one that is important for transformer models is limiting input length as evaluation time is quadratic to the input length.</p><p>We have not considered GPU evaluation here, which can significantly accelerate execution. However, cost at scale is a genuine concern here as well.</p><p>The under-communicated point here is that platforms that promise very low latencies for inference are only telling part of the story. As an example, consider a platform promising 1ms latency for a given model. Naively, this can support 1000 queries per second. However, consider what happens if 1000 requests arrive at almost the same time: the last request would have had to wait almost 1 second before returning. This is far off from the expected 1ms.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86f6220132c8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/machine-learned-model-serving-at-scale-86f6220132c8">Machine-learned model serving at scale</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using approximate nearest neighbor search in real world applications]]></title>
            <link>https://medium.com/data-science/using-approximate-nearest-neighbor-search-in-real-world-applications-a75c351445d?source=rss-344c89cb19cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a75c351445d</guid>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[search]]></category>
            <dc:creator><![CDATA[Lester Solbakken]]></dc:creator>
            <pubDate>Thu, 17 Dec 2020 16:34:32 GMT</pubDate>
            <atom:updated>2020-12-17T16:34:32.375Z</atom:updated>
            <content:encoded><![CDATA[<h4>From text search and recommendation to ads and online dating, ANN search rarely works in isolation</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ys7irAqaj07DWoVX" /><figcaption>Photo by <a href="https://unsplash.com/@patschrei?utm_source=medium&amp;utm_medium=referral">Patrick Schreiber</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Anything can be represented by a list of numbers.</p><p>For instance, text can be represented by a list of numbers describing the text’s meaning. Images can be represented by the objects it contains. Users of a system can be represented by their interests and preferences. Even time-based entities such as video, sound, or user interactions can be represented by a single list of numbers.</p><p>These vector representations describe content or meaning: the original, containing thousands of characters or pixels, is compressed to a much smaller representation of a few hundred numbers.</p><p>Most often, we are interested in finding the most similar vectors. This is called k-nearest neighbor (KNN) search or similarity search and has all kinds of useful applications. Examples here are model-free classification, pattern recognition, collaborative filtering for recommendation, and data compression, to name but a few. We’ll see some more examples later in this post.</p><p>However, a nearest neighbor search is only a part of the process for many applications. For applications doing search and recommendation, the potential candidates from the KNN search are often combined with other facets of the query or request, such as some form of filtering, to refine the results.</p><p>This can severely limit the quality of the end result, as post-filtering can prevent otherwise relevant results from surfacing. The solution is to integrate the nearest neighbor search with filtering, however most libraries for nearest neighbor search work in isolation and do not support this. To my knowledge, the only open-source platform that does is <a href="https://vespa.ai/">Vespa.ai</a>.</p><p>In this post, we’ll take a closer look at approximate neighbor search, explore some real cases combining this with filtering, and delve into how Vespa.ai solves this problem.</p><h3>Finding the (approximate) nearest neighbors</h3><p>The representations can be visualized as points in a high-dimension space, even though it’s kind of difficult to envision a space with hundreds of dimensions. This allows us to think of these points as vectors, sometimes called thought vectors, and we can use various distance metrics to measure the likeness or similarity between them. Examples are the dot (or inner) product, cosine angle, or euclidean distance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/926/1*KTTZc3E8UyTMO7ePmxNeDQ.png" /><figcaption>The 5 nearest neighbors (image by author)</figcaption></figure><p>Finding the nearest neighbors of a point is reasonably straight-forward: just compute the similarity using the distance metric between the point and all other points. Unfortunately, this brute-force approach doesn’t scale very well, particularly in time-critical settings such as online serving, where you have a large number of points to consider.</p><p>There are no known exact methods for finding nearest neighbors efficiently. As both the number of points increases and the number of dimensions increase, we fall victim to the curse of dimensionality. In high dimensions, all points are almost equally distant from each other. A good enough solution for many applications is to trade accuracy for efficiency. In approximately nearest neighbors (ANN), we build index structures that narrow down the search space. The implicit neighborhoods in such indexes also help reduce the problem of high dimensions.</p><p>You can roughly divide the approaches used for ANNs into whether or not they can be implemented using an inverse index. The inverse index originates from information retrieval and is comparable to the index often found at many books’ back. This index points from a word (or term) to the documents containing it. This can be used for ANNs as well. Using k-means clustering, one can cluster all points and index them by which cluster they belong to. A related approach is product quantization (and its relatives), which splits the vectors into products of lower-dimensional spaces. Yet another is locality-sensitive hashing, which uses hash functions to group similar vectors together. These approaches index the centroids or buckets.</p><p>A method that is not compatible with inverted indexes is HNSW (hierarchical navigable small world). HNSW is based on graph structures, is very efficient, and lets the graph be incrementally built at runtime. This is in contrast to most other methods that require offline, batch-oriented index building.</p><p>As approximate nearest neighbor search has many applications, quite a few tools and libraries exist. A few examples are:</p><ul><li><a href="https://github.com/google-research/google-research/tree/master/scann">ScaNN</a></li><li><a href="https://github.com/facebookresearch/faiss">FAISS</a></li><li><a href="https://github.com/spotify/annoy">Annoy</a></li></ul><p>A good overview of tradeoffs for these can be found at <a href="http://ann-benchmarks.com/">http://ann-benchmarks.com/.</a></p><h3>Nearest neighbors in search and recommendation</h3><p>In many applications, such as search and recommendation, the results of the nearest neighbor search is combined with additional facets of the request. In this section, we’ll provide some examples of when this becomes problematic.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*a_cBeeW4s1CMJfkZ8BKevw.png" /><figcaption>Only 2 of the 5 nearest neighbors remain after filtering (image by author)</figcaption></figure><h4>Text search</h4><p>Modern text search increasingly uses representation vectors, often called text embeddings or embedding vectors. Word2vec was an early example. More recently, sophisticated language understanding models such as BERT and other Transformer-based models are increasingly used. These are capable of assigning different representations for a word depending upon the context. For text search, the current state-of-the-art uses different models to encode query vectors and document vectors. These representations are trained so that the inner product of these vectors is maximized for relevant results.</p><p>Using embedding vectors in text search is often called semantic search. For many text search applications, we would like to combine this semantic search with other filters. For instance, we can combine a query for “approximate nearest neighbor” with a date filter such as “2020”. The naive approach here is to use one of the ANN libraries mentioned above to perform a nearest neighbor search and then filter out the results.</p><p>However, this is problematic. Imagine that 1000 documents are relevant to the query “approximate nearest neighbor”, with 100 added each year over the past 10 years. Assume they all are approximately equally likely to be retrieved from the ANN. So, retrieving the top 100 will result in about 10 documents from each year. Applying the filter “2020” will result in only 10 documents. That means the other 90 relevant documents from 2020 are missed.</p><h4>Recommendation</h4><p>Recommender systems, such as YouTube and TikTok, are built to provide continually interesting content to all users. As such, it’s essential to learn the interests or preferences of the user. Such user profiles are represented by one or more vectors, as are the items that should be recommended.</p><p>These vectors are often generated by using some form of collaborative filtering. One method is matrix factorization, where the maximum inner product is used as a distance function. Deep learning approaches have recently shown great promise, trained explicitly for the distance function between the user and item vector.</p><p>Recommendation systems employ filters to a great degree. Examples are filters for age-appropriate content, NSFW labels, availability of content in various regions due to distribution rights, and user-specified filters blocking certain content. These are examples of direct filters. More indirect filters come in the form of business rules such as diversity and de-duplication, which filters out content that has already been recommended.</p><p>The problem of filtering is more evident for recommendation systems than for text search. These filters’ quantity and strength lead to a greater probability that items retrieved from the ANN search are filtered away. So, only a few of the relevant items are actually recommended.</p><h4>Serving ads</h4><p>Ad serving systems work very much like recommender systems. Given a user profile and a context such as a search query or page content, the system should provide an advertisement relevant to the user. The advertisements are stored with advertiser-specific rules, for instance, who the ad or campaign should target. One such rule is to not exceed the budget of the campaign.</p><p>These rules function as filters. Like with text search and recommendation, if these filters are applied after the user-profile based retrieval, there is a probability that an appropriate advertisement is not retrieved. This is particularly important regarding the budget. Income is lost if there are no results retrieved with an available spending budget.</p><h4>Online dating</h4><p>In the world of online dating, people have a set of preferences. These can be binary such as gender, age range, location, height, and so on. Interests might be less absolute, such as hiking, loves pets, traveling, and exercise. These interests and preferences can be represented by a vector, and at least parts can be compressed to a representation vector as well.</p><p>Suppose retrieval is based on an ANN over interests, and the preferences are applied as a filter afterward. In that case, it’s clear why online dating is hard. As we retrieve the best matches from the ANN, there is a significant probability that all or most of these are filtered out, for instance, by location or by profiles already seen.</p><h4>Local search</h4><p>Local search and recommendation is based on geographical location. Given longitude and latitude coordinates, we can find places or businesses within certain distances from a point: finding restaurants near a user is a typical case. Imagine that we have the dining preferences of a user represented as a vector. Likewise, all restaurants are represented by vectors. Then, by performing an ANN search followed by a location filter, we could retrieve the restaurants preferred by the user in their local area.</p><p>However, this would not work. Of all the restaurants in the world, only a small fraction are close to the user. The location filter is much stronger than the ANN retrieval. So with a high probability, no results would be produced at all.</p><h3>Solution</h3><p>The naive approach to the problems above is simply to request more candidates from the ANN search. This obviously hurts performance, as the workload of both the ANN and post-filtering increases. Besides, this is not guaranteed to work. If you have a strong filter independent of the ANN, there is a real chance of not producing any results at all. The local restaurant case is an example of this, where the location is a very strong filter independent of the user profile.</p><p>The real solution here is to integrate the filters into the ANN search. Such an algorithm would be able to reject candidates early that don’t pass the filters. This effectively increases the search area from the query point dynamically until enough candidates are found. This guarantees that the requested number of candidates are produced.</p><p><strong>Unfortunately, for most ANN libraries, this is not an option as they work in isolation.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/824/1*JHXsljztyPHKJqXg71vW2g.png" /><figcaption>The 5 nearest neighbors with integrated filtering (image by author)</figcaption></figure><p>Vespa.ai is to my knowledge the only implementation of ANN that supports integrated filtering. The implementation is based on a modified HNSW graph algorithm, and Vespa.ai innovates in 3 main areas:</p><ul><li>Dynamic modification of the graph. Most ANN algorithms require the index to be built offline, but HNSW supports incremental building of the index. Vespa takes advantage of this and supports both adding and removing items in real-time while serving.</li><li>Multi-threaded indexing using lock-free data structures and copy-on-write semantics drastically increase the performance of building the index.</li><li>Metadata filtering modifies the algorithm to skip non-eligible candidates.</li></ul><p>To support filtering, Vespa.ai first evaluates the filters to create a list of eligible candidates. During the ANN search, a point close to the query point is selected and the graph is explored by following each node’s edge to its neighbors. Candidates not in the eligibility list are skipped, and the search continues until we have produced enough candidates.</p><p>There is a small problem here however. If the eligibility list is small in relation to the number of items in the graph, skipping occurs with a high probability. This means that the algorithm needs to consider an exponentially increasing number of candidates, slowing down the search significantly. To solve this, Vespa.ai switches over to a brute-force search when this occurs. The result is a very efficient ANN search when combined with filters.</p><p>For more information about how this is implemented please check out <a href="https://docs.vespa.ai/documentation/approximate-nn-hnsw.html">approximate nearest neighbor search using HNSW index</a>.</p><p>To summarize, a common approach for using nearest neighbor search in conjunction with other features is to apply filters after the NN search. This post shows why this is not a feasible solution, and filters should be properly integrated into the NN search. Unfortunately, most libraries for ANN search do not provide this option. To my knowledge, the only open-source platform that does is <a href="https://vespa.ai/">Vespa.ai</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a75c351445d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/using-approximate-nearest-neighbor-search-in-real-world-applications-a75c351445d">Using approximate nearest neighbor search in real world applications</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateful model serving: how we accelerate inference using ONNX Runtime]]></title>
            <link>https://medium.com/data-science/stateful-model-serving-how-we-accelerate-inference-using-onnx-runtime-a2875a77478d?source=rss-344c89cb19cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2875a77478d</guid>
            <category><![CDATA[search]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Lester Solbakken]]></dc:creator>
            <pubDate>Mon, 14 Dec 2020 14:54:50 GMT</pubDate>
            <atom:updated>2020-12-14T14:54:50.849Z</atom:updated>
            <content:encoded><![CDATA[<h4>There’s a difference between stateless and stateful machine-learned model serving</h4><p><em>By </em><a href="https://medium.com/@lester.solbakken"><em>Lester Solbakken</em></a><em> from Verizon Media and </em><a href="https://medium.com/@sharmapranav"><em>Pranav Sharma</em></a><em> from Microsoft.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*r5ur4tNJO04U14J12Rt7Fg.png" /><figcaption>Stateless vs stateful machine-learned model serving (image by author)</figcaption></figure><p>There’s a difference between stateless and stateful machine-learned model serving.</p><p>Stateless model serving is what one usually thinks about when using a machine-learned model in production. For instance, a web application handling live traffic can call out to a model server from somewhere in the serving stack. The output of this model service depends purely on the input. This is fine for many tasks, such as classification, text generation, object detection, and translation, where the model is evaluated once per query.</p><p>There are, however, some applications where the input is combined with stored or persisted data to generate a result. We call this stateful model evaluation. Applications such as search and recommendation need to evaluate models with a potentially large number of items for each query. A model server <a href="https://blog.vespa.ai/the-hardest-problem-in-computing/">can quickly become a scalability bottleneck</a> in these cases, regardless of how efficient the model inference is.</p><p>In other words, stateless model serving requires sending all necessary input data to the model. In stateful model serving, the model should be computed where the data is stored.</p><p>At <a href="https://vespa.ai/">Vespa.ai</a>, we are concerned with efficient stateful model evaluation. Vespa.ai is an open-source platform for building applications that do real-time data processing over large data sets. Designed to be highly performant and web-scalable, it is used for such diverse tasks as search, personalization, recommendation, ads, auto-complete, image and similarity search, comment ranking, and <a href="https://tech.okcupid.com/vespa-vs-elasticsearch/">even for finding love</a>.</p><p>It has become increasingly important for us to be able to evaluate complex machine-learned models efficiently. Delivering low latency, fast inference and low serving cost is challenging while at the same time providing support for the various model training frameworks.</p><p>We eventually chose to leverage <a href="https://github.com/microsoft/onnxruntime">ONNX Runtime</a> (ORT) for this task. ONNX Runtime is an accelerator for model inference. It has vastly increased Vespa.ai’s capacity for evaluating large models, both in performance and model types we support. ONNX Runtime’s capabilities within hardware acceleration and model optimizations, such as quantization, has enabled efficient evaluation of large NLP models like BERT and other Transformer models in Vespa.ai.</p><p>In this post, we’ll share our journey on why and how we eventually chose ONNX Runtime and share some of our experiences with it.</p><h4>About Vespa.ai</h4><p>Vespa.ai has a rich history. Its lineage comes from a search engine born in 1997. Initially powering the web search at alltheweb.com, it was flexible enough to be used in various more specialized products, or verticals, such as document search, mobile search, yellow pages, and banking. This flexibility in being a vertical search platform eventually gave rise to its name, Vespa.</p><p>The technology was acquired by Yahoo in 2003. There, Vespa cemented itself as a core piece of technology that powers hundreds of applications, including many of Yahoo’s most essential services. We open-sourced Vespa in 2017 and today it serves hundreds of thousands of queries per second worldwide at any given time, with billions of content items for hundreds of millions of users.</p><p>Although Yahoo was eventually acquired by Verizon, it is interesting to note that our team has stayed remarkably stable over the years. Indeed, a few of the engineers that started working on that initial engine over 20 years ago are still here. Our team counts about 30 developers, and we are situated in Trondheim in Norway.</p><p>Building upon experience gained over many years, Vespa.ai has evolved substantially to become what it is today. It now stands as a battle-proven general engine for real-time computation over large data sets. It has <a href="https://docs.vespa.ai/documentation/features.html">many features</a> that make it suitable for web-scale applications. It stores and indexes data with instant writes so that queries, selection, and processing over the data can be performed efficiently at serving time. It’s elastic and fault-tolerant, so nodes can be added, removed, or replaced live without losing data. It’s easy to configure, operate, and add custom logic. Importantly, it contains built-in capabilities for advanced computation, including machine learned models.</p><h4>Vespa.ai applications</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wiMARkJS14g3jmfgObORbw.png" /><figcaption>Vespa.ai architecture (image by author)</figcaption></figure><p>Vespa.ai is a distributed application consisting of stateless nodes and a set of stateful content nodes containing the data. A Vespa.ai application is fully defined in an application package. This is a single unit containing everything needed to set up an application, including all configuration, custom components, schemas, and machine-learned models. When the application package is deployed, the admin layer takes care of configuring all the services across all the system’s nodes. This includes distributing all models to all content nodes.</p><p>Application packages contain one or more document schemas. The schema primarily consists of:</p><ul><li>The data fields for each document and how they should be stored and indexed.</li><li>The ranking profiles which define how each document should be scored during query handling.</li></ul><p>The ranking profiles contain ranking expressions, which are mathematical expressions combining <a href="https://docs.vespa.ai/documentation/ranking-expressions-features.html">ranking features</a>. Some features retrieve data from sources such as the query, stored data, or constants. Others compute or aggregate data in various ways. Ranking profiles support multi-phased evaluation, so a cheap model can be evaluated in the first phase and a more expensive model for the second. Both sparse and dense <a href="https://docs.vespa.ai/documentation/tensor-user-guide.html">tensors</a> are supported for more advanced computation.</p><p>After the application is deployed, it is ready to handle data writes and queries. Data feeds are first processed on the stateless layer before content is distributed (with redundancy) to the content nodes. Similarly, queries go through the stateless layer before being fanned out to the content nodes where data-dependent computation is handled. They return their results back to the stateless layer, where the globally best results are determined, and a response is ultimately returned.</p><p>A guiding principle in Vespa.ai is to move computation to the data rather than the other way around. Machine-learned models are automatically deployed to all content nodes and evaluated there for each query. This alleviates the cost of query-time data transportation. Also, as Vespa.ai takes care of distributing data to the content nodes and redistributing elastically, one can scale up computationally by adding more content nodes, thus distributing computation as well.</p><p>In summary, Vespa.ai offers ease of deployment, flexibility in combining many types of models and computations out of the box without any plugins or extensions, efficient evaluation without moving data around and a less complex system to maintain. This makes Vespa.ai an attractive platform.</p><h4>ONNX in Vespa.ai</h4><p>In the last few years, it has become increasingly important for Vespa.ai to support various types of machine learned models from different frameworks. This led to us introducing initial support for ONNX models in 2018.</p><p>The Open Neural Network Exchange (ONNX) is an open standard for distributing machine learned models between different systems. The goal of ONNX is interoperability between model training frameworks and inference engines, avoiding any vendor lock-in. For instance, HuggingFace’s Transformer library includes export to ONNX, PyTorch has native ONNX export, and TensorFlow models can be converted to ONNX. From our perspective, supporting ONNX is obviously interesting as it would maximize the range of models we could support.</p><p>To support ONNX in Vespa.ai, we introduced a special onnx ranking feature. When used in a ranking expression this would instruct the framework to evaluate the ONNX model. This is one of the unique features of Vespa.ai, as one has the flexibility to combine results from various features and string models together. For instance, one could use a small, fast model in an early phase, and a more complex and computationally expensive model that only runs on the most promising candidates. For instance:</p><pre>document my_document {<br>  field text_embedding type tensor(x[769]) {<br>    indexing: attribute | index  <br>    attribute {<br>      distance-metric: euclidean<br>    }<br>  }<br>  field text_tokens type tensor(d0[256]) {<br>    indexing: summary | attribute<br>  }<br>}</pre><pre>onnx-model my_model {<br>  file: files/my_model.onnx<br>  input input_0: ...<br>  input input_1: ...<br>  output output_0: ...<br>}</pre><pre>rank-profile my_profile {<br>  first-phase {<br>    expression: closeness(field, text_embedding)<br>  }<br>  second-phase {<br>    rerank-count: 10<br>    expression: onnx(my_model)<br>  }<br>}</pre><p>This is an example of configuring Vespa.ai to calculate the euclidean distance between a query vector and the stored text_embedding vector in the first stage. This is usually used together with an approximate nearest neighbor search. The top 10 candidates are sent to the ONNX model in the second stage. Note that this is per content node, so with 10 content nodes, the model is running effectively on 100 candidates.</p><p>The model is set up in the onnx-model section. The file refers to an ONNX model somewhere in the application package. Inputs to the model, while not actually shown here for brevity, can come from various sources such as constants, the query, a document, or some combination expressed through a user-defined function. While the output of models are tensors, the resulting value of a first or second phase expression needs to be a single scalar, as documents are sorted according to this score before being returned.</p><p>Our initial implementation of the onnx ranking feature was to import the ONNX model and convert the entire graph into native Vespa.ai expressions. This was feasible because of the flexibility of the various <a href="https://docs.vespa.ai/documentation/reference/ranking-expressions.html#tensor-functions">tensor operations</a> Vespa.ai supports. For instance, a single neural network layer could be converted like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/894/1*aaNqblQBojHR2OShWiBmvA.png" /><figcaption>Machine-learned model to Vespa.ai expression (image by author)</figcaption></figure><p>Here, weights and bias would be stored as constant tensors, whereas the input tensor could be retrieved either from the query, a document field, or some combination of both.</p><p>Initially, this worked fine. We implemented the various <a href="https://github.com/onnx/onnx/blob/master/docs/Operators.md">ONNX operators</a> using the available tensor operations. However, we only supported a subset of the 150+ ONNX operators at first, as we considered that only certain types of models were viable for use in Vespa.ai due to its low-latency requirement. For instance, the ranking expression language does not support iterations, making it more challenging to implement operators used in convolutional or recurrent neural networks. Instead, we opted to continuously add operator support as new model types were used in Vespa.ai.</p><p>The advantage of this was that the various optimizations we introduced to our tensor evaluation engine to efficiently evaluate the models benefitted all other applications using tensors as well.</p><h4>ONNX Runtime</h4><p>Unfortunately, we ran into problems as we started developing support for Transformer models. Our first attempt at supporting a 12-layer BERT-base model failed. This was a model converted from TensorFlow to ONNX. The evaluation result was incorrect, with relatively poor performance.</p><p>We spent significant efforts on this. Quite a few operators had to be rewritten due to, sometimes very subtle, edge cases. We introduced a dozen or so performance optimizations, to avoid doing silly stuff such as calculating the same expressions multiple times and allocating memory unnecessarily. Ultimately, we were able to increase performance by more than two orders of magnitude.</p><p>During this development we turned to <a href="https://github.com/microsoft/onnxruntime">ONNX Runtime</a> for reference. ONNX Runtime is very easy to use:</p><pre>import onnxruntime as ort<br>session = ort.InferenceSession(“model.onnx”)<br>session.run( output_names=[...], input_feed={...} )</pre><p>This was invaluable, providing us with a reference for correctness and a performance target.</p><p>At one point, we started toying with the idea of actually using ONNX Runtime directly for the model inference instead of converting it to Vespa.ai expressions. The Vespa.ai content node is written in C++, so this entailed integrating with the C++ interface of ONNX Runtime. It should be mentioned that adding dependencies to Vespa.ai is not something we often do, as we prefer to avoid dependencies and thus own the entire stack.</p><p>Within a couple of weeks, we had a proof of concept up and running which showed a lot of promise. So we decided to go ahead and start using ONNX Runtime to evaluate all ONNX models in Vespa.ai.</p><p>This proved to be a game-changer for us. It vastly increases the capabilities of evaluating large deep-learning models in Vespa.ai in terms of model types we support and evaluation performance. We can leverage ONNX Runtime’s use of <a href="https://github.com/microsoft/onnxruntime/tree/master/onnxruntime/core/mlas">MLAS</a>, a compute library containing processor-optimized kernels. ONNX Runtime also contains model-specific optimizations for BERT models (such as multi-head attention node fusion) and makes it easy to evaluate precision-reduced models by quantization for even more efficient inference.</p><h4>ONNX Runtime in Vespa.ai</h4><p>Consider the following:</p><pre>onnx-model my_model {<br>  file: files/my_model.onnx<br>  input input_0: query(my_query_input)<br>  input input_1: attribute(my_doc_field)<br>}</pre><pre>rank-profile my_profile {<br>  first-phase {<br>    expression: sum( onnx(my_model) )<br>  }<br>}</pre><p>Here we have a single ONNX model that has two inputs. During application deployment, Vespa.ai distributes this ONNX model to all content nodes. There, the ranking expressions are parsed, and the feature executors that implement the ranking features are set up in preparation for handling traffic. Here we have 4 features:</p><ul><li>query(...) which retrieves a tensor from the query.</li><li>attribute(...) which retrieves a tensor from a field stored in the document.</li><li>onnx(...) which evaluates the ONNX model.</li><li>sum(...) which reduces and sums the argument tensor to a single scalar value.</li></ul><p>These features are wired together during initialization, so the outputs of query and attribute are used as inputs to onnx, and the output of the onnx feature is the input to the sum feature. The onnx feature basically sets up ONNX Runtime to evaluate the model.</p><p>Vespa.ai’s scoring framework is written in C++, so we use the C/C++ API provided by ONNX Runtime. While the integration with ONNX Runtime worked smoothly out of the box, there are two areas worth mentioning here: multi-threading and input/output tensor allocations.</p><p><strong>Multi-threading</strong></p><p>During setup, we initialize an ONNX Runtime session for each onnx feature and thread:</p><pre>#include &lt;onnxruntime/onnxruntime_cxx_api.h&gt;</pre><pre>Ort::Env shared_env;</pre><pre>Ort::SessionOptions options;<br>options.SetIntraOpNumThreads(1);<br>options.SetInterOpNumThreads(1);<br>options.SetGraphOptimizationLevel(ORT_ENABLE_ALL);</pre><pre>Ort::Session session = Ort::Session(shared_env, “local_file_path”, options);</pre><p>The session includes options for <a href="https://github.com/microsoft/onnxruntime/blob/master/docs/ONNX_Runtime_Perf_Tuning.md#thread-management">thread management</a>. ONNX Runtime supports 2 modes of execution: sequential and parallel. This controls whether the operators in a graph run sequentially or in parallel. Parallel execution of operators is scheduled on an inter-op thread pool. The execution of an individual operator is parallelized using an intra-op thread pool. A heavily home-optimized variant of an Eigen thread pool is used for inter-op parallelism, while OpenMP is used for intra-op.</p><p>Vespa.ai handles several queries in parallel. In addition, Vespa.ai can be configured to use several threads per query. Because of this Vespa.ai needs to tightly manage thread usage. Using additional threads inside an ONNX Runtime session causes system-level throughput to become unpredictable, with large deviations in performance. Since Vespa.ai has thread control outside of ONNX Runtime, we need to instruct ONNX Runtime to only use a single thread. By ensuring that the total number of threads do not exceed the number of physical cores in a machine, we can improve cache utilization. Vespa also supports processor pinning.</p><p>As we instruct ONNX Runtime to in effect run sequentially, inference times increase but total throughput also increases. For instance, we measured a 50% improvement in throughput on a BERT ranking application. We have not yet exposed ONNX Runtime’s thread management settings for cases where users would like to tune this themselves. This is an option we might consider in the future. In that case, each session having their own set of thread pools would be inefficient. However, ONNX Runtime provides an option to share thread pools between sessions. This is achieved using the CreateEnvWithGlobalThreadPools C API to set up the shared_env object, which in Vespa.ai is shared between all feature executors.</p><p>When we started using ONNX Runtime, its C++ distribution was bundled with OpenMP. This was problematic for us as the intra-operation thread setting was overridden by OpenMP, so we ended up compiling our own ONNX Runtime without OpenMP enabled. However, starting from version 1.6, ONNX Runtime ships a version without OpenMP.</p><p><strong>Input and output tensors</strong></p><p>As much as possible, memory allocation and ownership of input and output tensors happen within Vespa.ai. Consider the following types:</p><pre>std::vector&lt;const char *&gt; input_names;<br>std::vector&lt;const char *&gt; output_names;<br>std::vector&lt;Ort::Value&gt;   input_values;<br>std::vector&lt;Ort::Value&gt;   output_values;</pre><p>The input values come from other ranking features using Vespa.ai’s tensor framework. The values in the input vector are wrappers for Vespa.ai tensors. So ONNX Runtime accepts the memory layout from Vespa.ai without copying to internal buffers. The values in the output vector are pre-allocated ONNX Runtime vectors which are wrapped when used subsequently in other ranking features.</p><p>We use these directly when evaluating the model:</p><pre>Ort::RunOptions run_opts(nullptr);<br>session.Run(run_opts,<br>    input_names.data(), input_values.data(), input_values.size(),<br>    output_names.data(), output_values.data(),output_values.size());</pre><p>This zero-copying of tensors is obviously desirable from a performance perspective. This works for outputs as tensors in Vespa.ai currently are fixed size, meaning that the dimensions are known during application deployment. So even though models accept inputs with dynamic sizes, from a Vespa.ai perspective, they must currently be fixed. Supporting dynamic sizes is future work.</p><p>One limitation here is that Vespa.ai currently only supports double and float value types in tensors. If possible, Vespa.ai takes care of converting to the type that ONNX Runtime expects. For instance, inputs to Transformer models are token sequences usually of type int64. Since Vespa.ai does not currently support int types, they must be represented as for instance float32. Converting from float32 to int64 can be lossy, but we haven’t met any inaccuracies yet. Models that accept strings as input are not yet supported in Vespa.ai.</p><h4>Summary</h4><p>Integrating with ONNX Runtime was relatively painless. Even though we initially had to compile our own ONNX Runtime distribution due to OpenMP, we had no significant issues with dependencies. We are looking forward to the next release so we don’t have to have to do this.</p><p>While ONNX Runtime’s C/C++ API documentation is currently relatively scarce we found it to be sufficient. The ONNX Runtime API is concrete, clean and works as one would expect. We didn’t have any issues here at all, really.</p><p>All in all, our experience with ONNX Runtime has been great. It has shown itself to be a fantastic fit for Vespa.ai, delivering superior performance and easy to work with. One example here is the BERT model optimizations in ONNX Runtime. Also of particular note is the evaluation of quantized models, which would have been laborious to implement in Vespa.ai given the current tensor types we support.</p><p>Going forward, there are other features of ONNX Runtime we would like to experiment with. One of these is GPU support. While we are currently unsure if this is beneficial from a ranking point of view, there are other cases where this is interesting. One example is calculating vector representations of documents during data writing from a Transformer model.</p><p>Vespa.ai’s use case so far has mostly been focused on natural language understanding using Transformers such as BERT. <a href="https://medium.com/microsoftazure/accelerate-your-nlp-pipelines-using-hugging-face-transformers-and-onnx-runtime-2443578f4333">Exporting a HuggingFace model to ONNX</a> is easy and using it in Vespa is straightforward. ONNX Runtime was essential for us when implementing an <a href="https://towardsdatascience.com/efficient-open-domain-question-answering-on-vespa-ai-72562121dcd8">open-domain question-answering application</a>. Also, quantization had the effect of <a href="https://towardsdatascience.com/from-research-to-production-scaling-a-state-of-the-art-machine-learning-system-6efad0141865">drastically increasing performance</a> of this application, where a key takeaway there was that a larger model with weights with reduced precision outperformed smaller models with normal precision.</p><p>We’re excited to see what our users will use this for in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2875a77478d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/stateful-model-serving-how-we-accelerate-inference-using-onnx-runtime-a2875a77478d">Stateful model serving: how we accelerate inference using ONNX Runtime</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From research to production: scaling a state-of-the-art machine learning system]]></title>
            <link>https://medium.com/data-science/from-research-to-production-scaling-a-state-of-the-art-machine-learning-system-6efad0141865?source=rss-344c89cb19cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6efad0141865</guid>
            <category><![CDATA[making-sense-of-big-data]]></category>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[big-data]]></category>
            <dc:creator><![CDATA[Lester Solbakken]]></dc:creator>
            <pubDate>Thu, 12 Nov 2020 14:15:03 GMT</pubDate>
            <atom:updated>2020-11-12T14:36:05.771Z</atom:updated>
            <content:encoded><![CDATA[<h4><a href="https://towardsdatascience.com/tagged/making-sense-of-big-data">Making Sense of Big Data</a></h4><h4><strong>How we implemented a production-ready question-answering application and reduced response time by more than two orders of magnitude.</strong></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*f1zh4v6qDbi1WA7-Usb1Mg.png" /><figcaption>(Image by author)</figcaption></figure><p>Imagine you’ve created a machine learning system that surpasses state-of-the-art performance on some task. You’ve optimized for a set of objectives like classification accuracy, F1 scores, or AUC. Now you want to create a web service from it. Other objectives, such as the time or cost of delivering a result to the user, become more important.</p><p>These two sets of objectives are typically in conflict. More accurate models are often large and computationally expensive to evaluate. Various optimizations like reducing the models’ precision and complexity are often introduced to use such models in production. While beneficial for decreasing cost and energy consumption, this, unfortunately, hurts accuracy.</p><p>Obviously, inference time can be drastically lowered if accuracy is not important. Likewise, very accurate responses can be produced at high cost. Which solution to ultimately choose lies somewhere between these extremes. A useful technique for selecting the best solution is to enumerate them in terms of accuracy and cost. The set of solutions not dominated by others is called the <a href="https://en.wikipedia.org/wiki/Pareto_efficiency#Pareto_frontier">Pareto frontier</a> and identifies the best trade-offs between accuracy and cost.</p><p>In a <a href="https://towardsdatascience.com/efficient-open-domain-question-answering-on-vespa-ai-72562121dcd8">previous blog post</a>, we introduced a serving system that reproduces state-of-the-art accuracy in open-domain question-answering. We based this on Facebook’s <a href="https://github.com/facebookresearch/DPR">Dense Passage Retrieval (DPR)</a>, which is a Python-based research system. We built the serving system using <a href="https://vespa.ai/">Vespa.ai</a>, the open-source big data serving engine, which is uniquely suited to tasks like this due to its native support for fast similarity search and machine learned models in search and ranking. The result is a web service taking a single question and returning an exact answer.</p><p>While this system reproduced DPR’s result and thus had excellent accuracy metrics, the response time was initially poor, as measured in end-to-end latency. This post will describe the various optimizations we made to bring performance to acceptable levels for a production system.</p><p>Vespa.ai is built for production and thus has <a href="https://docs.vespa.ai/documentation/performance/sizing-search.html">quite a few options for serving time optimizations</a>. We will particularly use Vespa.ai’s ability to retrieve and rank documents using multiple worker threads per query to significant effect. However, this application’s main cost is in evaluating two BERT models. One of the questions we would like to answer is whether smaller models with full precision are preferable to larger models with quantized parameters. We’ll develop the Pareto frontier to evaluate the merits of the various optimizations.</p><p>We’ll start with an overview of the serving system and identify which parts of the system initially drive the cost. For more details on the implementation, we refer to the <a href="https://towardsdatascience.com/efficient-open-domain-question-answering-on-vespa-ai-72562121dcd8">previous blog post</a> in this series.</p><h3>Question answering</h3><p>The system’s task is to produce a textual answer in response to a question given in natural language. There are primarily three stages involved:</p><ul><li>The encoder generates a representation vector for the question.</li><li>The retriever performs a nearest neighbor search among the 21 million indexed passages.</li><li>The reader finds the most relevant passage and extracts the final answer.</li></ul><p>The following figure illustrates the process:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/1*xFVRvZ7padT1uPbnKo-FOw.png" /><figcaption>Encoder, Retriever and Reader for question-answering (image by author)</figcaption></figure><p>The encoder first creates a tokenized representation from the question. This vector of token IDs is sent as input to the encoder BERT model. This is initially a standard BERT-base model with 12 layers and a hidden layer size of 768. The final hidden layer state is used as a representation vector for the question. As seen in the figure above, this primarily happens in the stateless container layer in Vespa. The token and vector representation is passed down (“scattered”) to all content nodes to perform the query.</p><p>On the content nodes, the passages have been indexed with their own representation vectors. These vectors have been constructed so that the euclidean distance between question and passage vectors indicate similarity. This is used in the HNSW algorithm to perform an approximate nearest neighbor search. The 10 passages with the smallest euclidean distance are sent to the next stage.</p><p>The second-phase ranking stage, also performed on each content node, evaluates the reader BERT model. Like the encoder model, this is initially a BERT-base model with 12 layers and hidden length 768. The token representations from the query and each passage are combined to form the model input. The reader model produces three probability scores: the relevance score and the start and end indices of the answer in the passage’s token sequence. The passage with the best relevance score is selected as the winner, and its token representation is returned to the stateless layer. There, custom code extracts the best span using the start and end indices, de-tokenizes it, and returns the resulting textual answer.</p><p>Now, that’s a lot of work. Here is an example of a response to the question “Who won Tour De France in 2015”, where the most relevant passage is retrieved and the correct answer “Chris Froome” is extracted:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/1*YI-C8_OhzHCCvCsrupZ0Dg.png" /><figcaption>Response from Vespa.ai (image by author)</figcaption></figure><p>To measure performance, we deployed the system on a single machine with an <a href="https://ark.intel.com/content/www/us/en/ark/products/192443/intel-xeon-gold-6240-processor-24-75m-cache-2-60-ghz.html">Intel Xeon Gold 6240 processor</a> with 200 GB RAM and SSD disk. We evaluate the system over 3610 questions and record the average latency and exact-match score. Initially, the system achieves an exact-match score of 40.64. Before any consideration has been made to optimize performance, the time spent in the three stages mentioned above is:</p><ul><li>Encoding model: 300 ms</li><li>Approximate nearest neighbor search: 13 ms</li><li>Top-10 reader ranking: 9085 ms</li></ul><p>Obviously, a total end-to-end latency of 9.4 seconds is not anything close to acceptable as a service. <strong>In the following, we’ll lower this to well below 100 ms.</strong></p><h3>Multi-threaded retrieval ranking</h3><p>Initially, the most expensive step by far is the reader stage. By default, Vespa does all ranking for a query on a single thread. This is a reasonable default to maximize throughput when the computational cost is low. In this case, this means that the reader model is evaluated — in sequence — for each of the top 10 passages. This results in high query latency.</p><p>However, Vespa has an option of using <a href="https://docs.vespa.ai/documentation/reference/services-content.html#requestthreads">multiple threads per search</a>. Setting this value brings the average end-to-end latency down to 2.04 seconds, a more than 4x improvement without affecting the exact match score.</p><p>It is worth clarifying that the reader model is not evaluated batch-wise. This is due to Vespa’s ranking framework, where ranking expressions score a single passage and query pair. For BERT models, however, this is not significant as <a href="https://medium.com/microsoftazure/accelerate-your-nlp-pipelines-using-hugging-face-transformers-and-onnx-runtime-2443578f4333">evaluation time is linear with batch size</a>. One reason is tensor multiplications with tensors of 3 or more dimensions, as these iterate over several hardware-optimized matrix-matrix multiplications anyway.</p><p>In general, Vespa has many options to tune performance, such as easily distributing the workload on additional content nodes. While we don’t explore that here, see the <a href="https://docs.vespa.ai/documentation/performance/sizing-search.html">Vespa serving scaling guide</a> for more information.</p><h3>Token sequence length</h3><p>One of the defining and most prominent features of BERT models is the full-attention layer. While this was a significant breakthrough in language understanding, it has an unfortunate O(n²) effect on evaluation time.</p><p>So, the length of the token sequence input to the BERT model significantly impacts inference time. Initially, the encoder BERT model had an input length of 128. By reducing it to 30, we decrease inference time from 300 ms to 125 ms without loss of accuracy.</p><p>Likewise, the reader model initially had an input length of 380. By reducing this to 128, we reduce average latency from 1.9 seconds to 741 ms, a significant reduction. However, we do get a decrease in accuracy, as some question and passage combinations can result in token sequences longer than 128. This reduced the exact match score to 39.61.</p><p>Both the encoder and reader model support dynamic length inputs, but Vespa currently only supports fixed length inputs. This will be fixed in the near future, however. In summary, shortening token input lengths of the encoder and reader models result in a 3x speedup.</p><h3>Model quantization</h3><p>Neural network models are commonly trained using single-precision floating-point numbers. However, for inference in production, it has been shown that this level of precision is not always necessary. The parameters can be converted to a much smaller integer representation without significant loss in accuracy. Converting the parameters from a 32-bit floating-point to 8-bit integers reduces the model size by 75%. More importantly, integer operations execute much faster. Modern CPUs that support AVX512 Vector Neural Network Instructions (VNNI) are designed to accelerate INT8 inference performance. Additionally, evaluating such quantized models requires less power.</p><p>Quantizing the reader model brings its size down from 435Mb to 109Mb. The latency for the system drops on average to 374 ms. This has a slightly unfortunate effect on accuracy, dropping the exact match to 37.98. Likewise, quantizing the encoder model results in a similar size reduction, and system evaluation time drops to 284 ms. The exact-match score drops to 37.87.</p><p>In summary, model quantization of both reader and encoder models result in another 3x speedup.</p><h3>Miniature models</h3><p>Until this point, both the encoder and reader models are based on pre-trained BERT-base models, containing 12 layers with hidden dimension size of 768 and thus around 110 million parameters. These are reasonably large models, particularly when used in time-constrained environments. However, in the paper <a href="https://arxiv.org/abs/1908.08962">“Well-Read Students Learn Better: On the Importance of Pre-training Compact Models,”</a> the authors show that smaller models can indeed work very well. The “miniature” models referenced in this paper can be found in the <a href="https://huggingface.co/google/bert_uncased_L-12_H-768_A-12">Transformers model repository</a>.</p><p>We trained new reader models as described in the <a href="https://github.com/facebookresearch/DPR#5-reader-training">DPR repository</a>, basing them on the following pre-trained BERT miniature models:</p><ul><li>Medium (8 layers, 512 hidden size)</li><li>Small (4 layers, 512 hidden size)</li><li>Mini (4 layers, 256 hidden size)</li><li>Tiny (2 layers, 128 hidden size)</li></ul><p>We also quantize each model. The full overview of all 20 models (5 reader models, with and without quantization, with and without quantized encoder model) with exact match scores and average latency is given in the table below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/380/1*DhN3KbcfQWBeqN9LyPWuKw.png" /><figcaption>Exact match scores vs latencies for various model types</figcaption></figure><p>Plotting these results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/585/1*N5EXjRpCVeoWXKzxMBX4dQ.png" /><figcaption>Exact match vs latency (image by author)</figcaption></figure><p>In the figure above, the red line represents the Pareto front. The points along this front are also marked in bold in the table above. Recall that these points represent the best trade-offs between exact match and latency, meaning that there are no other points that are superior in both exact match and latency for each point along this front.</p><p>One interesting result that can be seen here is that, in general, quantized models dominate other models with higher precision. For instance, the medium quantized model has better exact match and latency numbers than the small models with higher precision. So, in this case, even though quantization reduces accuracy, it is more beneficial to choose a large model that has been quantized over a smaller model that has not.</p><p>The Pareto front visualizes the objectively best solutions, and our subjective preferences would guide us in finding the optimal solution. The tests above have been run on a single <a href="https://ark.intel.com/content/www/us/en/ark/products/192443/intel-xeon-gold-6240-processor-24-75m-cache-2-60-ghz.html">Intel Xeon Gold 6240</a> machine. More powerful processors would lower the overall latency numbers but not change the overall shape. The exact solution to choose is then based on our latency and hardware budgets. For instance, organizations with considerable resources that can scale up sufficiently can justify moving to the right on this front. The economy of scale can mitigate the cost of hardware investments and energy consumption to make the service viable. Such a solution might be out of reach for others.</p><h3>Putting all this together</h3><p>Please refer to the <a href="https://github.com/vespa-engine/sample-apps/tree/master/dense-passage-retrieval-with-ann/">companion sample application</a> for more details and instructions on how to run this application yourself.</p><h3>Conclusion</h3><p>In summary, we’ve taken a research application with poor performance to levels suitable for production. From 9.4 seconds for the full model down to 70ms for the tiny model, this represents a 130x speedup. Unfortunately, to get down to these levels, we noted a significant drop in exact-match as well. The best choice lies somewhere between these extremes. If we were to bring this application into production, we could use more powerful hardware to bring the latency below 100ms with acceptable exact match metrics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*v0dJaEDLD0CZkW8dgfVaoA.png" /></figure><p>There are quite a few optimizations we didn’t try that are outside the scope of this article. For instance, <a href="https://github.com/microsoft/fastformers">FastFormers: Highly Efficient Transformer Models for Natural Language Understanding</a> includes some additional optimizations for more efficient inference such as model pruning. Also, new generations of BERT models attempt to alleviate the performance problems associated with the full-attention mechanism. For instance, <a href="https://arxiv.org/abs/2007.14062">the Big Bird architecture</a> seems promising.</p><p>We omitted training miniature encoder models. From a latency point of view, using the miniature BERT models in question encoding have an additional benefit as the vector representation for the question and passages are shorter. Thus the approximate nearest neighbor search would become more efficient. However, this would likely result in a significant drop in accuracy and the time spent in the ANN is not a significant driver of latency anyway.</p><p>Adding additional content nodes would allow for distributing the workload. This would likely not reduce latency but would increase the number of passages we can evaluate with the reader model. We will return to this in an upcoming blog post.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6efad0141865" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/from-research-to-production-scaling-a-state-of-the-art-machine-learning-system-6efad0141865">From research to production: scaling a state-of-the-art machine learning system</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient open-domain question-answering on Vespa.ai]]></title>
            <link>https://medium.com/data-science/efficient-open-domain-question-answering-on-vespa-ai-72562121dcd8?source=rss-344c89cb19cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/72562121dcd8</guid>
            <category><![CDATA[nlp]]></category>
            <category><![CDATA[editors-pick]]></category>
            <category><![CDATA[big-data]]></category>
            <category><![CDATA[search]]></category>
            <category><![CDATA[machine-learning]]></category>
            <dc:creator><![CDATA[Lester Solbakken]]></dc:creator>
            <pubDate>Thu, 01 Oct 2020 15:10:04 GMT</pubDate>
            <atom:updated>2020-10-01T15:10:04.600Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Open-domain question-answering has emerged as a benchmark for measuring a system’s capability to read, represent, and retrieve general knowledge. Retrieval-based question-answering systems require connecting various systems and services, such as BM25 text search, vector similarity search, NLP model serving, tokenizers, and middleware to glue all this together. Most of these are core features of Vespa.ai. In this post, we reproduce the state-of-the-art baseline for retrieval-based question-answering systems within a single, scalable production ready application on Vespa.ai.</strong></p><p>By <a href="https://medium.com/u/344c89cb19cc">Lester Solbakken</a> and <a href="https://medium.com/u/ec3f3ebbe4ae">Jo Kristian Bergum</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*L7ezvlF92AGfVOf_" /><figcaption>Photo by <a href="https://unsplash.com/@jontyson?utm_source=medium&amp;utm_medium=referral">Jon Tyson</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>Some of the most effective drivers of scientific progress are benchmarks. Benchmarks provide a common goal, a purpose, for improving the state-of-the-art on datasets that are available to everyone. Leaderboards additionally add a competitive motivation, offering the opportunity to excel among peers. And rather than just endlessly tinkering to improve relevant metrics, competitions add deadlines that spur researchers to actually get things done.</p><p>Within the field of machine learning, benchmarks have been particularly important to stimulate innovation and progress. A new competition, the Efficient Open-Domain Question Answering challenge for NeurIPS 2020, seeks to advance the state-of-the-art in question answering systems. The goal here is to develop a system capable of answering questions without any topic restriction. With all the recent progress in natural language processing, this area has emerged as a benchmark for measuring a system’s capability to read, represent, and retrieve general knowledge.</p><p>The current retrieval-based state-of-the-art is the <a href="https://github.com/facebookresearch/DPR">Dense Passage Retrieval system</a>, as described in the <a href="https://arxiv.org/abs/2004.04906">Dense Passage Retrieval for Open-Domain Question Answering paper</a>. It consists of a set of python scripts, tools, and models developed primarily for research. There are a lot of parts in such a system. These include two BERT-based models for encoding text to embedding vectors, another BERT-based model for extracting answers, approximate nearest-neighbor similarity search and text-based BM25 methods for retrieving candidates, tokenizers, and so on. It’s not trivial to bring such a system to production. We thought it would be interesting to consolidate these different parts and demonstrate how to build an open-domain question-answering serving system with Vespa.ai that achieves state-of-the-art accuracy.</p><p>In case you are not familiar with it, <a href="http://vespa.ai/">Vespa.ai</a> is an engine for low-latency computation over large data sets. It stores and indexes your data so that queries, selection, and processing over the data can be performed efficiently at serving time. Vespa.ai is used for diverse tasks such as search, personalization, recommendation, ads, <a href="https://tech.okcupid.com/vespa-vs-elasticsearch/">even finding love</a>, and many other applications requiring computation at query time. It is serving hundreds of thousands of queries per second around the globe at any given time.</p><p>Most of the components for a question-answering system are core features in Vespa. A while ago, we improved Vespa’s text search support for term-based retrieval and ranking. We recently added efficient approximate nearest neighbors for semantic, dense vector recall. For hybrid retrieval, Vespa supports many types of machine-learned models, for instance neural networks and decision forests. We have also improved our support for TensorFlow and PyTorch models to run larger NLP and Transformer models.</p><p>This is interesting because while this has obvious benefits in a research setting, such systems’ real value lies in their end-use in applications. Vespa is designed as a highly performant and scalable production-ready system. Thus, it offers a simplified path to deployment in production without coping with the complexity of maintaining many different subsystems. That makes Vespa an attractive package.</p><p>During this blog post, we’ll touch upon</p><ul><li>Fast approximate-nearest neighbors for semantic, dense vector retrieval.</li><li>Term-based (BM25) retrieval for sparse vector retrieval.</li><li>Importing of multiple pre-trained BERT-based models in Vespa for encoding embedding vectors and extracting answers.</li><li>Custom logic for tokenization and other things.</li></ul><p>For more details we refer to the <a href="https://github.com/vespa-engine/sample-apps/tree/master/dense-passage-retrieval-with-ann">companion sample application</a>.</p><p>This post’s goal is to recreate the Dense Passage Retrieval (DPR) paper results for the <a href="https://www.mitpressjournals.org/doi/full/10.1162/tacl_a_00276">Natural Questions benchmark</a>. We’ll first go through a high-level overview of how a retrieval-based question-answering system works in the context of this paper. Then we’ll show how this can all be implemented on Vespa without any external services or plugins, and recreate the paper’s state-of-the-art results as measured by the exact match of answers given a set of questions. We’ll wrap up with a look to the future and the next post in this series.</p><h3>Background: the anatomy of a retrieval-based QA system</h3><p>The Natural Questions benchmark consists of natural language questions and answers. How to retrieve and represent the knowledge required to answer the questions is up to each system. There are two main approaches to this: retrieval and parametric. A retrieval-based system uses search terms or semantic representation vectors to recall a set of sentences or paragraphs subsequently evaluated with a machine-learned model to extract the exact answer. A parametric system stores the answers more or less directly in the weights of a large neural network model. There has also been research into hybrid retrieval and parametric systems such as the <a href="https://arxiv.org/abs/2005.11401">Retrieval-Augmented Generation system</a>, which recently improved the state-of-the-art for the natural question benchmark as a whole. We’ll focus here on a retrieval-based system, but will explore parametric and hybrid approaches in later blog posts.</p><p>A retrieval-based question answering system typically stores its “knowledge” in an information retrieval system. This can be sentences, paragraphs, or entire documents. Here we’ll use the Wikipedia dataset where each page is split into passages of 100 words each. The dataset contains 21 million such passages. When answering a question, we first retrieve the passages that most likely include the answer. They are then analyzed with a machine-learned model to extract the spans that most likely results in the correct response. These stages are called the “retriever” and “reader”, respectively.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*TAMeRvRhzwS1SOot4aBH5w.png" /><figcaption>Extracting the answer from passages. (<em>Image by author</em>)</figcaption></figure><h4>The retriever</h4><p>The retriever is responsible for generating a set of candidate passages. Since the subsequent reader component is expensive to evaluate, it is crucial to have an effective retrieval mechanism. There are two main approaches to passage retrieval: term-based (sparse) such as for BM25, and embedding (dense) vectors, which each have their strengths and weaknesses.</p><p><strong>Term-based (sparse) retrieval</strong></p><p>Term-based retrieval is the classic information retrieval method and covers algorithms such as TF-IDF and BM25. Conceptually, the text is represented by a vector where each dimension represents a term in a vocabulary. A non-zero value signifies its presence. As each text only contains a subset of possible terms in the vocabulary, these vectors are large and sparse. The similarity between two texts, for instance, a document and a query, can be computed by a dot product between the sparse vectors with slight modifications (e.g., term importance) for TF-IDF or BM25. Term-based methods rely on inverted index structures for efficient retrieval. This can in some cases be further accelerated by algorithms such as WAND.</p><p>Except for any pre-processing such as lemmatization, stemming, and possibly stop-word removal, terms are matched exactly as found in the text. This can be a strength as well as a weakness. For very salient terms, e.g. names and places, this cuts down the search space significantly. However, potentially relevant documents that don’t contain the exact term will not be retrieved unless one uses query expansion or related techniques. The Dense Passage Retrieval (DPR) paper uses ElasticSearch as the providing system for BM25.</p><p><strong>Embedding-based (dense) retrieval</strong></p><p>The number of potential terms in a vocabulary can be vast indeed. The basic idea behind embedding vectors is to compress this very-high dimensional sparse vector to a much smaller dense vector where most dimensions contain a non-zero value. This has the effect of projecting a query or document vector into a lower-dimensional space. This can be done so that vectors that are close geometrically are also close semantically. The DPR paper uses two BERT models to encode text: one for encoding queries and one for encoding documents. The two models are trained simultaneously in a two-tower configuration to maximize the dot product for passages likely to answer the question.</p><p>In contrast to the sparse representation, there are no exact methods for finding the nearest neighbors efficiently. So we trade accuracy for efficiency in what is called approximate nearest neighbors (ANN). Many different methods for ANN search have been proposed. Some are compatible with inverted index structures so they can be readily implemented in existing information retrieval systems. Examples are k-means clustering, product quantization (and it’s relatives), and locality sensitive hashing, where the centroids or buckets can be indexed. A method that is not compatible with inverted indexes is <a href="https://arxiv.org/abs/1603.09320">HNSW</a> (hierarchical navigable small world). HNSW is based on graph structures, is very efficient, and has an attractive property where the graph can be incrementally built at runtime. This is in contrast to most other methods that require offline, batch oriented index building.</p><p>Retrieval based on semantic embeddings complements term-based retrieval very well. Semantically similar documents can be recalled even though they don’t contain the exact same terms. Unlike the bag-of-words approach for term-based retrieval, word order can provide additional context. Historically, however, term-based retrieval has outperformed semantic embeddings on question answering problems, but the DPR paper shows that dense retrieval can be vastly improved if the encoding has specifically been trained to the task. The DPR paper uses <a href="https://github.com/facebookresearch/faiss">FAISS with an HNSW index</a> for similarity search.</p><h4>The reader</h4><p>While the retriever component’s job is to produce a set of candidate passages that hopefully contain the answer to the question, the reader extracts the passages’ actual answer. This requires some form of natural language understanding model, and BERT (or other Transformer) models are used. These models are typically huge and expensive to evaluate, so only a small number of candidate passages are run through them.</p><p>Transformer models take sequences of tokens as input. The tokenization of text can be done in quite a few different ways to balance vocabulary size and sequence length. Due to BERT models’ full attention mechanism, evaluation time increases quadratically with sequence length. So a reasonable balance must be struck, and BERT-based models use a WordPiece or similar algorithm to split less common words into subwords.</p><p>The reader model’s input is the concatenation of the tokens representing the question, the document’s title, and the passage itself. The model looks up the embedding representation for each token, and through a series of layers, produces a new representation for each token. These representations can then be used for different tasks. For question-answering, an additional layer is added to compute the three necessary outputs: the relevance of the passage to the question, and the start and end indexes of the answer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*6qo4CaQn5FwaGEXL4IJj8A.png" /><figcaption>BERT for question answering (<em>Image by author</em>)</figcaption></figure><p>To extract the final answer, the passage that produced the largest relevance score is used. The two other outputs of the model are probabilities for each token of being a start token and an end token. The final answer is chosen by finding the span with the largest sum of start probability and end probability. This results in a sequence of tokens, which must be converted to words by the tokenizer before returning. The DPR paper <a href="https://huggingface.co/transformers/model_doc/dpr.html#dprreader">uses a BERT-based model</a> to output span predictions.</p><h4>Putting all this together</h4><p>The retrieval-based question-answering system as described above, capable of both term- and embedding-based retrieval, requires at least the following components:</p><ul><li>A BM25 information retrieval system storing the 21 million Wikipedia text passages.</li><li>An efficient vector similarity search system storing the passage embedding vectors.</li><li>A model serving system for the three different BERT-based models: query encoder, document encoder, and reader model.</li><li>A BERT-based tokenizer.</li><li>Middleware to glue this all together.</li></ul><p>The tokenizer generates the token sequence for the text. These tokens are stored for usage in the reader model. They are also used in a document BERT-base encoder model to create the embedding vector for dense retrieval. The text and embedding vectors need to be indexed for fast retrieval.</p><p>A similar process is followed for each query. The tokenizer produces a token sequence used to generate an embedding vector in the query BERT-based encoder. The first stage, retrieval, is done using either term-based retrieval or embedding based retrieval. The top-N passages are passed to the Reader model and ranked accordingly. The best passage is analyzed to extract the best span containing the answer.</p><p>This is a non-trivial list of services that need to be set up to implement a question-answering system. In the next section we show how to implement all this as a single Vespa application.</p><h3>Reproducing the baseline on Vespa</h3><p>Most of the components mentioned above have become core features in Vespa. In the following we’ll present an overview of setting this up in Vespa. The details can be seen in the <a href="https://github.com/vespa-engine/sample-apps/tree/master/dense-passage-retrieval-with-ann">companion sample application</a>.</p><h4>Schema</h4><p>When creating an application with Vespa, one typically starts with a document schema. The schema contains, among other things, the definition of which data should be stored with each document. In our case, each document is a passage from the Wikipedia dataset. So we set up a schema that allows for the different retrieval methods we have discussed:</p><ul><li><strong>Sparse retrieval</strong> using traditional BM25 term-based retrieval.</li><li><strong>Dense retrieval</strong> using vector representations encoded by a trained model.</li><li><strong>Hybrid retrieval</strong> using a combination of the above.</li></ul><p>We set up all of this in a single document schema:</p><pre>schema wiki {<br>  document wiki {</pre><pre>    field title type string {<br>      indexing: summary | index<br>    }</pre><pre>    field text type string {<br>      indexing: summary | index<br>    }</pre><pre>    field title_token_ids type tensor(d0[256]) {<br>      indexing: summary | attribute<br>    }</pre><pre>    field text_token_ids type tensor(d0[256]) {<br>      indexing: summary | attribute<br>    }</pre><pre>    field text_embedding type tensor(x[769]) {<br>      indexing: attribute | index  <br>      attribute {<br>        distance-metric: euclidean<br>      }<br>    }<br>  }<br>}</pre><p>Here, each passage’s title and text content is represented both by a string and a token sequence field. The string fields are indexed to support BM25 and support WAND for accelerated retrieval. The token sequences are represented as tensors and are used as inputs to the reader model.</p><p>The embedding vector of the title and text is precomputed and stored as a tensor. This vector is used for dense retrieval, so we <a href="https://docs.vespa.ai/documentation/approximate-nn-hnsw.html">enable the HNSW index</a> on this field for approximate nearest neighbor matching. A very nice feature of Vespa is that the HNSW index is not pre-built offline; it is constructed online as data is indexed. This allows for applications that are much more responsive to new data being fed into the system.</p><h4>Retrieval and ranking</h4><p>A query in Vespa defines, among other things, how Vespa should recall documents (called the matching phase) and how Vespa should score the documents (called the ranking phase). Vespa provides a <a href="https://docs.vespa.ai/documentation/query-api.html">rich query API</a>, where queries are specified with <a href="https://docs.vespa.ai/documentation/reference/query-language-reference.html">the Vespa YQL language</a>. As the different retrieval strategies (term-based and embedding-based) have different query syntax, we have built a custom searcher component that allows us to build a unified search interface and only pass the actual question and retrieval strategy as parameters. This simplifies comparisons between the methods.</p><p>The retrieval strategies differ both on what is recalled and how they are scored. In Vespa, scoring is expressed using ranking expressions that are configured in the document schema. Vespa supports <a href="https://docs.vespa.ai/documentation/phased-ranking.html">multi-phased ranking</a>, and we exploit that here so that the first phase represents the retriever, and the second phase the reader. We set up the first phase ranking profile like this:</p><pre>rank-profile sparse inherits openqa {<br>  first-phase {<br>    expression: bm25(text) + bm25(title)<br>  }<br>}<br>rank-profile dense inherits openqa {<br>  first-phase {<br>    expression: closeness(field, text_embedding)<br>  }<br>}<br>rank-profile hybrid inherits openqa {<br>  first-phase {<br>    expression: 1000*closeness(field, text_embedding) + bm25(text) + bm25(title)<br>  }<br>}</pre><p>Here, we set up three ranking profiles, one for sparse retrieval, one for dense retrieval, and one for hybrid retrieval. The sparse ranking profile uses the BM25 score of the title and text fields against the query as the scoring function. The dense profile uses the <em>closeness</em>, e.g., the euclidean distance between the query and document embedding field. The hybrid profile is an example that combines both for hybrid retrieval. This first phase represents the retriever.</p><p>For the reader model we set up the base profile <em>openqa</em> which introduces a second phase, common between the retrieval strategies:</p><pre>onnx-model reader {<br>  file: files/reader.onnx<br>  input  input_ids: input_ids<br>  input  attention_mask: attention_mask<br>  output output_0: start_logits<br>  output output_1: end_logits<br>  output output_2: relevance_logits  <br>}</pre><pre>rank-profile openqa {<br>  second-phase {<br>    rerank-count: 10<br>    expression: onnxModel(reader).relevance_logits<br>  }<br>  summary-features {<br>    onnxModel(reader).start_logits<br>    onnxModel(reader).end_logits<br>  }<br>}</pre><p>Here, the top 10 documents are re-ranked by the reader model, defined be the onnxModel rank feature. The actual model we use is a <a href="https://huggingface.co/facebook/dpr-reader-single-nq-base">pre-trained model</a> the DPR team has published on HuggingFace’s model repository. HuggingFace has released an excellent <a href="https://huggingface.co/transformers/serialization.html">transformer model export</a>, which makes it easy to export Transformer models (from either PyTorch or TensorFlow) to <a href="https://onnx.ai/">ONNX format</a>. After the model is exported to ONNX, we can put the model file in the application package and configure its use in the document schema as seen above. To make this scale, Vespa distributes this model to all content nodes in the cluster. Thus the model is evaluated on the content node during ranking, avoiding transferring data to an external model service.</p><p>The reader model has three outputs, where the <em>relevance_logits</em> output is used for scoring. The other two represent the probabilities of each token being a start or end token, respectively, for the ultimate answer to the question. These are picked up by a custom searcher, and the actual span these fields represent is extracted there.</p><p>The application contains one additional model, the <a href="https://huggingface.co/facebook/dpr-question_encoder-single-nq-base">question encoder model</a> used to generate the embedding vector for the query at run time. The pre-computed document embeddings from the Wikipedia dataset are published by Facebook Research. We use these embeddings directly.</p><h4>Vespa container middleware — putting it all together</h4><p>The application has the following custom plugins implemented as Java in Vespa containers:</p><ul><li>A BERT tokenizer component that is responsible for generating the sequence of BERT tokens from a text.</li><li>A custom document processor which uses the BERT tokenization during indexing.</li><li>A custom searcher that retrieves the embedding representation for the query invoking the BERT question encoder model.</li><li>A custom searcher that controls the retrieval logic (e.g., sparse, dense, or hybrid).</li><li>A custom searcher that reads the output of the reader model and extracts the best matching answer span and converts that token sequence to the actual text which is returned to the user.</li></ul><p>The result is a service which takes a textual question and returns the predicted answer, all within one Vespa application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*EGKHcDZrt0oOIF5jzTKj7w.png" /><figcaption>Data and computation on data (such as ML model evaluation) is distributed to all content nodes. Custom processing happens on stateless containers. (<em>Image by author</em>)</figcaption></figure><h3>Results</h3><p>The benchmark we use for this application is the Natural Questions data set. All experiments in this section are run by querying the Vespa instance and checking the predicted answer to the golden reference answer.</p><p><strong>Retriever Accuracy Summary</strong></p><p>We use Recall@position as the main evaluation metric for the retriever. The obvious goal of the retriever is to have the highest recall possible at the lowest possible position. Since the final top position passages are re-ranked using the BERT-based reader, the fewer passages we need to evaluate the better the run time complexity and performance.</p><p>The following table summarizes the retriever accuracy using the original 3,610 dev questions in the Natural Questions for Open Domain Question Answering tasks (<a href="https://github.com/google-research-datasets/natural-questions/blob/master/nq_open/NQ-open.dev.jsonl">NQ-open.dev.jsonl</a>).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/691/1*ZrGnbNdKA_vHr6_Bw3f4cw.png" /><figcaption>Retriever accuracy</figcaption></figure><p>The DPR paper reports recall@20 of 79.4, so our results are inline with their reported results for the dense retrieval method. We attribute the slight difference in our favor here for a different set of settings for the HNSW index.</p><p><strong>Reader Accuracy Summary</strong></p><p>We evaluate the reader accuracy using the Exact Match (EM) metric. The Exact Match metric measures the percentage of predictions that match any one of the ground truth answers exactly. To get an EM score of 1 for a query the answer prediction must match the golden answer exactly as given in the dataset. This is challenging. For instance, the question “When was the last moon landing?” has golden answers “14 December 1972 UTC” or “December 1972”, and the predicted answer “14 December 1972” will be scored 0.</p><p>The results are for the same data set above, with a re-rank of the top 10 results from the retriever:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*AQw9sBWYF7uOdpO0-ASdnQ.png" /><figcaption>Reader accuracy</figcaption></figure><p>The above results reproduce the results of the DPR paper which at the writing of this post is the current state of the art for retrieval-based systems.</p><h3>Further work</h3><p>In this blog post we’ve been focused on recreating the results of the DPR paper within a single instance of Vespa. In the next part of this series we will introduce a more sophisticated hybrid model and show how we can use other model types to hopefully improve accuracy. We will follow up with another post on lowering total system latency down to more reasonable levels while measuring any impact this has on accuracy.</p><p>Stay tuned!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72562121dcd8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/efficient-open-domain-question-answering-on-vespa-ai-72562121dcd8">Efficient open-domain question-answering on Vespa.ai</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>