{"title":"Bits & Backprops","subtitle":"Notes on machine learning, the systems around it, and what happens when you put them to work.","link":[{"@attributes":{"href":"https:\/\/yudhiesh.github.io\/feed.xml","rel":"self","type":"application\/atom+xml"}},{"@attributes":{"href":"https:\/\/yudhiesh.github.io\/","rel":"alternate","type":"text\/html"}}],"id":"https:\/\/yudhiesh.github.io\/feed.xml","updated":"2026-10-27T06:52:17+08:00","generator":"Jekyll","author":{"name":"Yudhiesh Ravindranath"},"entry":[{"title":"Cerberus: Building an LLM Guardian","link":{"@attributes":{"href":"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/","rel":"alternate","type":"text\/html"}},"id":"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1","published":"2025-06-17T00:33:48+08:00","updated":"2026-10-25T00:00:00+08:00","author":{"name":"Yudhiesh Ravindranath"},"category":[{"@attributes":{"term":"llm-safety"}},{"@attributes":{"term":"synthetic-data"}}],"summary":"A practical look at building an LLM safety dataset: generating examples, removing duplicates, and figuring out which labels to trust.","content":"<figure><img src=\"https:\/\/yudhiesh.github.io\/images\/art\/cerberus.webp\" alt=\"An indigo engraving of a gentle three-headed Cerberus guarding a flowering branch\" width=\"160\" height=\"160\"><\/figure><details class=\"post-toc\">\n  <summary>In this post<\/summary>\n  <ul>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#introduction\">Introduction<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#safeguards\">Safeguards<\/a>\n      <ul>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#what-are-llm-safeguards\">What are LLM Safeguards?<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#llm-safeguards-requirements\">LLM Safeguards Requirements<\/a>\n          <ul>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#functional\">Functional<\/a><\/li>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#non-functional\">Non-Functional<\/a><\/li>\n          <\/ul>\n        <\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#llm-inference-using-safeguards\">LLM Inference using Safeguards<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#building-safeguards\">Building Safeguards<\/a><\/li>\n      <\/ul>\n    <\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#synthetic-data-generation\">Synthetic Data Generation<\/a>\n      <ul>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#the-challenge-imbalanced-data\">The Challenge: Imbalanced Data<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#synthetic-data-generation-flow\">Synthetic Data Generation Flow<\/a>\n          <ul>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#1-prompt-template-design\">1. Prompt Template Design<\/a>\n              <ul>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#safe-context-templates\">Safe Context Templates<\/a><\/li>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#unsafe-context-templates\">Unsafe Context Templates<\/a><\/li>\n              <\/ul>\n            <\/li>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#2-controlled-generation\">2. Controlled Generation<\/a>\n              <ul>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#volume-and-distribution\">Volume and Distribution<\/a><\/li>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#generation-process\">Generation Process<\/a><\/li>\n              <\/ul>\n            <\/li>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#3-semantic-deduplication\">3. Semantic Deduplication<\/a>\n              <ul>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#deduplication-process\">Deduplication Process<\/a><\/li>\n              <\/ul>\n            <\/li>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#4-g-eval-quality-validation\">4. G-Eval Quality Validation<\/a>\n              <ul>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#validation-process\">Validation Process<\/a><\/li>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#evaluation-workflow\">Evaluation Workflow<\/a><\/li>\n              <\/ul>\n            <\/li>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#5-human-in-the-loop-annotation\">5. Human-in-the-Loop Annotation<\/a>\n              <ul>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#annotation-workflow\">Annotation Workflow<\/a><\/li>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#annotation-process\">Annotation Process<\/a><\/li>\n              <\/ul>\n            <\/li>\n            <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#6-dataset-finalization\">6. Dataset Finalization<\/a>\n              <ul>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#finalization-steps\">Finalization Steps<\/a><\/li>\n                <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#dataset-structure\">Dataset Structure<\/a><\/li>\n              <\/ul>\n            <\/li>\n          <\/ul>\n        <\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#exploratory-data-analysis-on-synthetic-data\">Exploratory Data Analysis on Synthetic Data<\/a><\/li>\n      <\/ul>\n    <\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#final-thoughts\">Final Thoughts<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#coming-up-next\">Coming Up Next<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/#references\">References<\/a><\/li>\n  <\/ul>\n\n<\/details>\n\n<h2 id=\"introduction\">Introduction<\/h2>\n\n<p>Getting an LLM to answer questions is the easy part. Deciding which questions it should answer takes a little more work.<\/p>\n\n<p>For this project, I wanted to build a small model that checks prompts before they reach the main LLM. I called it Cerberus, after the three-headed guardian of the underworld. Ours has a quieter job: let useful requests through and catch the ones that need a closer look.<\/p>\n\n<p>Before training anything, though, we need examples. This first post follows the dataset from generated prompts through deduplication, automated checks, and human review. Along the way, we\u2019ll look at where the tools help and where their judgments disagree.<\/p>\n\n<p>The goal is to check a request before spending time and compute on the main model. That means balancing two kinds of mistakes: letting an unsafe request through and blocking a useful one. The dataset needs to help us understand both.<\/p>\n\n<blockquote>\n  <p>This post focuses on input checks. Output validation matters too, but it is a separate part of the system.<\/p>\n<\/blockquote>\n\n<h2 id=\"safeguards\">Safeguards<\/h2>\n\n<h3 id=\"what-are-llm-safeguards\">What Are LLM Safeguards?<\/h3>\n\n<p>A safeguard is a check around a model call. It can inspect the request, the response, or both. The check might be a rule, a small classifier, or another LLM; the right choice depends on what you need to catch and the latency you can afford.<\/p>\n\n<figure>\n  <img src=\"https:\/\/yudhiesh.github.io\/images\/diagrams\/llm-safeguards.png\" alt=\"A request passes through an input check, the main LLM, and an output check. A failed check routes the request or response for review instead of passing it onward.\" width=\"1000\" height=\"800\" loading=\"lazy\" \/>\n  <figcaption>Checks before and after the model call serve different purposes.<\/figcaption>\n<\/figure>\n\n<p><strong>Input checks<\/strong> look for requests that fall outside the application\u2019s policy, including prompt injection attempts or sensitive data the model should not receive.<\/p>\n\n<p><strong>Output checks<\/strong> inspect the generated response for issues such as policy violations or an unexpected format. Neither layer guarantees correctness; both need evaluation against the application\u2019s actual failure cases.<\/p>\n\n<h3 id=\"llm-safeguards-requirements\">LLM Safeguards Requirements<\/h3>\n\n<h4 id=\"functional\">Functional<\/h4>\n\n<p>These are the core jobs your guardrails need to handle:<\/p>\n\n<ul>\n  <li>\n    <p><strong>Input Filtering<\/strong> - Block problematic content before it reaches your LLM. This includes jailbreak attempts, PII that creates compliance issues, and off-topic requests that waste resources.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Output Validation<\/strong> - Check LLM responses before users see them. Models can hallucinate, generate inappropriate content, or mention competitors when they shouldn\u2019t.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Content Moderation<\/strong> - Enforce your business rules and brand guidelines automatically. If your support bot starts giving legal advice, that\u2019s a problem.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Format Checking<\/strong> - For structured outputs like JSON, ensure the response is actually parseable. Malformed responses break downstream systems.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Threat Detection<\/strong> - Identify prompt injections, conversation hijacking, and policy violations in real-time.<\/p>\n  <\/li>\n<\/ul>\n\n<h4 id=\"non-functional\">Non-Functional<\/h4>\n\n<ul>\n  <li>\n    <p><strong>Latency<\/strong> - Guardrails add processing time. Users expect fast responses, so you need to run checks efficiently, often in parallel with your main LLM call.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Accuracy<\/strong> - Balance false positives (blocking good requests) with false negatives (missing actual threats). This requires proper evaluation and threshold tuning.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Cost<\/strong> - Each guardrail adds computational overhead. You need to optimize between expensive models that are accurate and cheaper models that are fast enough.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Scale<\/strong> - Your guardrails must handle production traffic without becoming bottlenecks. This means efficient architecture and resource management.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Maintainability<\/strong> - Threats evolve constantly. Your system needs to be easily updated as new attack patterns emerge.<\/p>\n  <\/li>\n<\/ul>\n\n<h3 id=\"llm-inference-using-safeguards\">LLM Inference using Safeguards<\/h3>\n\n<div align=\"center\">\n<figure>\n  <img src=\"https:\/\/www.omrimallis.com\/assets\/llama_cpp_high_level_flow.png.webp\" alt=\"LLM Inference Workflow\" width=\"800\" \/>\n  <figcaption><em>LLM Inference Workflow<\/em><\/figcaption>\n<\/figure>\n<\/div>\n\n<p>When you type a prompt into the ChatGPT web UI and hit \u201cSend,\u201d your text is sent to the inference server. The server breaks your input into tokens, turns each token into a numeric embedding, and runs those embeddings through a stack of transformer layers to build a contextual representation. At each step, it computes scores (logits) for every possible next token, picks one based on those scores, appends it to the output, and repeats until a stop token is produced. Finally, the completed response is sent back to the UI and displayed on your screen.<\/p>\n\n<div align=\"center\">\n<figure>\n  <img src=\"https:\/\/i.postimg.cc\/gYb0nTdJ\/Screenshot-2025-06-01-at-12-55-21.png\" alt=\"LLM Safeguards in Inference\" \/>\n  <figcaption><em>LLM Safeguards in Inference<\/em><\/figcaption>\n<\/figure>\n<\/div>\n\n<p>With LLM Safeguards you would be having a separate service to determine beforehand whether the input prompt is safe or unsafe. From there the simplest approach would be to return a placeholder <strong>\u201cSorry I am unable to answer that question!\u201d<\/strong>. More advanced systems could even send the response to a smaller and faster LLM in order to return a more personalized response. Much like how OpenAI handles it when you try asking questions that should definitely be blocked:<\/p>\n\n<p><img src=\"https:\/\/yudhiesh.github.io\/images\/chatgpt_safeguards.png\" alt=\"ChatGPT Safeguards\" \/><\/p>\n\n<h3 id=\"building-safeguards\">Building Safeguards<\/h3>\n\n<div align=\"center\">\n<figure>\n  <img src=\"https:\/\/i.postimg.cc\/brjBjCmN\/Screenshot-2025-06-01-at-13-20-02.png\" alt=\"Safeguards Tradeoff Chart\" \/>\n  <figcaption><em>Safeguards Tradeoff Chart<\/em><\/figcaption>\n<\/figure>\n<\/div>\n\n<p>In a general sense, the three techniques we have for building safeguards can be broken down into the following characteristics:<\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th>Technique<\/th>\n      <th>Speed\/Cost<\/th>\n      <th>Accuracy<\/th>\n      <th>Description<\/th>\n      <th>Use Case<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td><strong>Heuristics<\/strong><\/td>\n      <td>Fast\/Cheap<\/td>\n      <td>Low<\/td>\n      <td>Rule-based classification using keywords, patterns, or regex. Simple if-then logic for safety detection.<\/td>\n      <td>Quick prototyping, baseline systems, or when computational resources are extremely limited<\/td>\n    <\/tr>\n    <tr>\n      <td><strong>Small ML Models<\/strong><\/td>\n      <td>Fast\/Cheap<\/td>\n      <td>High<\/td>\n      <td>Lightweight, specialized models (e.g., DistilBERT, small classifiers) trained specifically for safety classification<\/td>\n      <td>Production systems, large-scale synthetic data generation, real-time applications<\/td>\n    <\/tr>\n    <tr>\n      <td><strong>LLM-as-a-Guardrail<\/strong><\/td>\n      <td>Slow\/Expensive<\/td>\n      <td>High<\/td>\n      <td>Large language models (GPT-4, Claude, etc.) used to evaluate and classify prompt safety with nuanced understanding<\/td>\n      <td>High-stakes decisions, complex edge cases, quality validation of synthetic datasets<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<p>A key goal in building these systems is to minimize the overrefusal rate\u2014ensuring that legitimate queries are not incorrectly blocked. As highlighted in <a href=\"https:\/\/www.anthropic.com\/news\/constitutional-classifiers\">Anthropic\u2019s Constitutional Classifiers<\/a>, achieving a balance between robust safety and minimal overrefusal is crucial for practical deployment. This balance allows us to maintain high safety standards while providing a smooth user experience.<\/p>\n\n<p>Before we can build and evaluate these safeguards, we need ground truth data\u2014a collection of prompts labeled as either safe or unsafe. However, obtaining high-quality safety datasets poses several challenges: they often contain sensitive content, require careful human annotation, and must cover diverse edge cases.<\/p>\n\n<p>To address this challenge, we\u2019ll leverage LLMs themselves to generate our training data. This process, known as <a href=\"https:\/\/aws.amazon.com\/what-is\/synthetic-data\/\">Synthetic Data Generation<\/a>, allows us to create large-scale, diverse datasets with accurate safety labels while maintaining control over the distribution and complexity of examples.<\/p>\n\n<h2 id=\"synthetic-data-generation\">Synthetic Data Generation<\/h2>\n\n<p>For this experiment, I used an LLM to draft prompts and initial labels, then checked those examples before using them for training. Generation gives us a starting point; it does not make the labels ground truth. OpenAI\u2019s <a href=\"https:\/\/cookbook.openai.com\/examples\/sdg1\">synthetic data walkthrough<\/a> is another useful starting point.<\/p>\n\n<h3 id=\"the-challenge-imbalanced-data\">The Challenge: Imbalanced Data<\/h3>\n\n<p>I chose a 90\/10 safe-to-unsafe split for this experiment. That is a dataset design choice, not a universal estimate of production traffic. With an imbalanced dataset, there are a few things to watch:<\/p>\n\n<ul>\n  <li><strong>Model Bias<\/strong>: Classifiers tend to over-predict the majority class (safe)<\/li>\n  <li><strong>Poor Recall<\/strong>: Models may miss many unsafe prompts, creating safety risks<\/li>\n  <li><strong>Limited Edge Cases<\/strong>: Rare but critical safety violations are underrepresented<\/li>\n<\/ul>\n\n<h3 id=\"synthetic-data-generation-flow\">Synthetic Data Generation Flow<\/h3>\n\n<p>The pipeline starts with separate safe and unsafe prompt templates. Examples move through generation, deduplication, label checks, and review before dataset assembly:<\/p>\n\n<figure>\n  <img src=\"{{ '\/images\/diagrams\/synthetic-data-pipeline.png' | relative_url }}\" alt=\"Prompt templates feed generation, semantic deduplication, and G-Eval checks. Agreed labels proceed to dataset assembly; disagreements go through human review first.\" width=\"1000\" height=\"1100\" loading=\"lazy\" \/>\n  <figcaption>Generation is the start of the pipeline. Deduplication and label review decide what is worth keeping.<\/figcaption>\n<\/figure>\n\n<h4 id=\"1-prompt-template-design\">1. Prompt Template Design<\/h4>\n\n<p>The foundation of the synthetic data generation process lies in carefully crafted prompt templates. Think of these as blueprints for generating diverse, realistic examples that cover the full spectrum of safety scenarios. Two distinct sets of templates were developed:<\/p>\n\n<h5 id=\"safe-context-templates\">Safe Context Templates<\/h5>\n<p>The safe context templates (<a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/v2_safe_contexts.txt\">v2_safe_contexts.txt<\/a>) focus on legitimate use cases across various domains:<\/p>\n\n<ul>\n  <li><strong>Web Development &amp; APIs<\/strong>: Templates for API documentation, web service queries, and frontend development<\/li>\n  <li><strong>Mobile Development<\/strong>: Mobile app development scenarios, platform-specific queries<\/li>\n  <li><strong>Cloud &amp; DevOps<\/strong>: Infrastructure management, deployment workflows, and cloud service interactions<\/li>\n  <li><strong>Databases<\/strong>: Database design, query optimization, and data modeling<\/li>\n  <li><strong>Distributed Systems<\/strong>: System architecture, scalability patterns, and distributed computing concepts<\/li>\n<\/ul>\n\n<h5 id=\"unsafe-context-templates\">Unsafe Context Templates<\/h5>\n<p>The unsafe context templates (<a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/v2_unsafe_contexts.txt\">v2_unsafe_contexts.txt<\/a>) cover potential security threats and misuse cases:<\/p>\n\n<ul>\n  <li><strong>Network Exploitation<\/strong>: Attempts to discover vulnerabilities or bypass security measures<\/li>\n  <li><strong>Web App Attacks<\/strong>: SQL injection, XSS, and other web-based attack vectors<\/li>\n  <li><strong>Malware Development<\/strong>: Requests for malicious code or exploit development<\/li>\n  <li><strong>Social Engineering<\/strong>: Attempts to manipulate or deceive users<\/li>\n  <li><strong>Cryptographic Attacks<\/strong>: Attempts to break or bypass encryption<\/li>\n<\/ul>\n\n<p>Each template is designed to generate contextually appropriate examples that maintain realism while covering edge cases. For instance, a safe template might generate:<\/p>\n\n<div class=\"language-plaintext highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>\"Can you help me implement rate limiting in my Express.js API to prevent abuse?\"\n<\/code><\/pre><\/div><\/div>\n\n<p>While an unsafe template might generate:<\/p>\n\n<div class=\"language-plaintext highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code>\"How can I bypass rate limiting to perform a brute force attack on an API endpoint?\"\n<\/code><\/pre><\/div><\/div>\n\n<p>This careful template design ensures the synthetic dataset captures the nuanced differences between legitimate and malicious requests, providing a robust foundation for training effective safety classifiers.<\/p>\n\n<h4 id=\"2-controlled-generation\">2. Controlled Generation<\/h4>\n\n<p>The controlled generation phase transforms carefully designed templates into a diverse dataset of examples. Using the <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/src\/data_generation\/generate.py\">generate.py<\/a> script, <a href=\"https:\/\/distilabel.argilla.io\/latest\/\">Distilabel<\/a> orchestrates the generation process with several key considerations:<\/p>\n\n<h5 id=\"volume-and-distribution\">Volume and Distribution<\/h5>\n<ul>\n  <li>Generated 1,000 examples in total across the prompt categories<\/li>\n  <li>Maintained a 90\/10 split between safe and unsafe examples<\/li>\n  <li>This split was the starting distribution for this experiment; a deployment would need its own traffic analysis<\/li>\n<\/ul>\n\n<h5 id=\"generation-process\">Generation Process<\/h5>\n<p>The generation process follows these steps:<\/p>\n<ol>\n  <li><strong>Template Selection<\/strong>: Randomly selects a template from either safe or unsafe context pools<\/li>\n  <li><strong>Parameter Filling<\/strong>: Populates template variables with appropriate values<\/li>\n  <li><strong>Context Injection<\/strong>: Adds relevant technical context to make examples realistic<\/li>\n  <li><strong>Quality Checks<\/strong>: Validates generated examples for coherence and relevance<\/li>\n<\/ol>\n\n<p>Here\u2019s a simplified example of how Distilabel is used for controlled generation:<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kn\">from<\/span> <span class=\"nn\">distilabel.pipeline<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Pipeline<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">distilabel.steps<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">LoadDataFromDicts<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">distilabel.steps.tasks<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">TextGeneration<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">distilabel.llm<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">OpenRouterLLM<\/span>\n\n<span class=\"c1\"># Initialize the pipeline\n<\/span><span class=\"k\">with<\/span> <span class=\"n\">Pipeline<\/span><span class=\"p\">(<\/span><span class=\"s\">\"safety-prompt-generation\"<\/span><span class=\"p\">)<\/span> <span class=\"k\">as<\/span> <span class=\"n\">pipeline<\/span><span class=\"p\">:<\/span>\n    <span class=\"c1\"># Load templates and configure distribution\n<\/span>    <span class=\"n\">load_dataset<\/span> <span class=\"o\">=<\/span> <span class=\"n\">LoadDataFromDicts<\/span><span class=\"p\">(<\/span>\n        <span class=\"n\">name<\/span><span class=\"o\">=<\/span><span class=\"s\">\"load_templates\"<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">data<\/span><span class=\"o\">=<\/span><span class=\"p\">[<\/span>\n            <span class=\"p\">{<\/span><span class=\"s\">\"instruction\"<\/span><span class=\"p\">:<\/span> <span class=\"n\">safe_template<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"label\"<\/span><span class=\"p\">:<\/span> <span class=\"s\">\"safe\"<\/span><span class=\"p\">}<\/span> <span class=\"k\">for<\/span> <span class=\"n\">_<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">900<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">]<\/span> <span class=\"o\">+<\/span> <span class=\"p\">[<\/span>\n            <span class=\"p\">{<\/span><span class=\"s\">\"instruction\"<\/span><span class=\"p\">:<\/span> <span class=\"n\">unsafe_template<\/span><span class=\"p\">,<\/span> <span class=\"s\">\"label\"<\/span><span class=\"p\">:<\/span> <span class=\"s\">\"unsafe\"<\/span><span class=\"p\">}<\/span> <span class=\"k\">for<\/span> <span class=\"n\">_<\/span> <span class=\"ow\">in<\/span> <span class=\"nb\">range<\/span><span class=\"p\">(<\/span><span class=\"mi\">100<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">]<\/span>\n    <span class=\"p\">)<\/span>\n    \n    <span class=\"c1\"># Configure the LLM for generation\n<\/span>    <span class=\"n\">llm<\/span> <span class=\"o\">=<\/span> <span class=\"n\">OpenRouterLLM<\/span><span class=\"p\">(<\/span>\n        <span class=\"n\">model<\/span><span class=\"o\">=<\/span><span class=\"s\">\"mistralai\/mistral-small\"<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">temperature<\/span><span class=\"o\">=<\/span><span class=\"mf\">0.7<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">max_tokens<\/span><span class=\"o\">=<\/span><span class=\"mi\">2048<\/span>\n    <span class=\"p\">)<\/span>\n    \n    <span class=\"c1\"># Set up the generation step\n<\/span>    <span class=\"n\">text_generation<\/span> <span class=\"o\">=<\/span> <span class=\"n\">TextGeneration<\/span><span class=\"p\">(<\/span>\n        <span class=\"n\">name<\/span><span class=\"o\">=<\/span><span class=\"s\">\"generate_prompts\"<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">llm<\/span><span class=\"o\">=<\/span><span class=\"n\">llm<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">input_batch_size<\/span><span class=\"o\">=<\/span><span class=\"mi\">32<\/span>\n    <span class=\"p\">)<\/span>\n    \n    <span class=\"c1\"># Connect the pipeline steps\n<\/span>    <span class=\"n\">load_dataset<\/span> <span class=\"o\">&gt;&gt;<\/span> <span class=\"n\">text_generation<\/span>\n\n<span class=\"c1\"># Run the pipeline\n<\/span><span class=\"n\">distiset<\/span> <span class=\"o\">=<\/span> <span class=\"n\">pipeline<\/span><span class=\"p\">.<\/span><span class=\"n\">run<\/span><span class=\"p\">()<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>This controlled approach ensures the dataset maintains high quality while covering the full spectrum of possible scenarios. The actual implementation in <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/src\/data_generation\/generate.py\">generate.py<\/a> includes additional features like structured output validation and custom quality metrics.<\/p>\n\n<h4 id=\"3-semantic-deduplication\">3. Semantic Deduplication<\/h4>\n\n<p>After generation, the challenge of removing redundant examples while preserving semantic diversity is addressed. The <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/src\/data_generation\/deduplicate.py\">deduplicate.py<\/a> script leverages the <a href=\"https:\/\/github.com\/MinishLab\/semhash\">SemHash<\/a> library for efficient semantic deduplication:<\/p>\n\n<p>SemHash provides a fast and scalable solution for semantic deduplication:<\/p>\n<ul>\n  <li>Uses model2vec for efficient text embedding<\/li>\n  <li>Leverages ANN backends for fast similarity search<\/li>\n  <li>Supports both single-dataset and cross-dataset deduplication<\/li>\n  <li>Provides explainable results with detailed metrics<\/li>\n<\/ul>\n\n<h5 id=\"deduplication-process\">Deduplication Process<\/h5>\n<p>The deduplication workflow is straightforward with SemHash:<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kn\">from<\/span> <span class=\"nn\">datasets<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">load_dataset<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">semhash<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">SemHash<\/span>\n\n<span class=\"c1\"># Load a dataset to deduplicate\n<\/span><span class=\"n\">texts<\/span> <span class=\"o\">=<\/span> <span class=\"n\">load_dataset<\/span><span class=\"p\">(<\/span><span class=\"s\">\"ag_news\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">split<\/span><span class=\"o\">=<\/span><span class=\"s\">\"train\"<\/span><span class=\"p\">)[<\/span><span class=\"s\">\"text\"<\/span><span class=\"p\">]<\/span>\n\n<span class=\"c1\"># Initialize a SemHash instance\n<\/span><span class=\"n\">semhash<\/span> <span class=\"o\">=<\/span> <span class=\"n\">SemHash<\/span><span class=\"p\">.<\/span><span class=\"n\">from_records<\/span><span class=\"p\">(<\/span><span class=\"n\">records<\/span><span class=\"o\">=<\/span><span class=\"n\">texts<\/span><span class=\"p\">)<\/span>\n\n<span class=\"c1\"># Deduplicate the texts\n<\/span><span class=\"n\">deduplicated_texts<\/span> <span class=\"o\">=<\/span> <span class=\"n\">semhash<\/span><span class=\"p\">.<\/span><span class=\"n\">self_deduplicate<\/span><span class=\"p\">().<\/span><span class=\"n\">selected<\/span>\n\n<span class=\"c1\"># Filter outliers\n<\/span><span class=\"n\">filtered_texts<\/span> <span class=\"o\">=<\/span> <span class=\"n\">semhash<\/span><span class=\"p\">.<\/span><span class=\"n\">self_filter_outliers<\/span><span class=\"p\">().<\/span><span class=\"n\">selected<\/span>\n\n<span class=\"c1\"># Find representative texts\n<\/span><span class=\"n\">representative_texts<\/span> <span class=\"o\">=<\/span> <span class=\"n\">semhash<\/span><span class=\"p\">.<\/span><span class=\"n\">self_find_representative<\/span><span class=\"p\">().<\/span><span class=\"n\">selected<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>The deduplication process involves:<\/p>\n<ol>\n  <li><strong>Embedding Generation<\/strong>: SemHash automatically converts texts into semantic embeddings<\/li>\n  <li><strong>Similarity Clustering<\/strong>: Groups similar examples using efficient ANN search<\/li>\n  <li><strong>Representative Selection<\/strong>: Chooses the most representative example from each cluster<\/li>\n  <li><strong>Threshold Filtering<\/strong>: Removes examples that exceed similarity thresholds<\/li>\n<\/ol>\n\n<h5 id=\"deduplication-metrics\">Deduplication Metrics<\/h5>\n<p>The implementation achieved the following <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/data\/v2_synthetic_1000_deduplication_metrics.json\">metrics<\/a> on the synthetic dataset:<\/p>\n\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"p\">{<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"duplicate_ratio\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.292<\/span><span class=\"p\">,<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"exact_duplicate_ratio\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.0<\/span><span class=\"p\">,<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"least_similar_text_similarity\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.900<\/span><span class=\"p\">,<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"original_size\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">1000<\/span><span class=\"p\">,<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"deduplicated_size\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">708<\/span><span class=\"p\">,<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"removed_count\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">292<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n\n<p>These metrics show that:<\/p>\n<ul>\n  <li>29.2% of examples were identified as semantic duplicates<\/li>\n  <li>No exact duplicates were found (0.0%)<\/li>\n  <li>The least similar examples still had a 90% similarity score<\/li>\n  <li>The dataset was reduced from 1,000 to 708 examples<\/li>\n  <li>292 examples were removed as duplicates<\/li>\n<\/ul>\n\n<h4 id=\"4-g-eval-quality-validation\">4. G-Eval Quality Validation<\/h4>\n\n<p>Quality validation is crucial for ensuring the reliability of the synthetic dataset. The <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/src\/data_generation\/evaluate.py\">evaluate.py<\/a> script uses the <a href=\"https:\/\/deepeval.com\/\">DeepEval<\/a> framework, specifically implementing the G-Eval algorithm for robust validation. For a comprehensive guide on G-Eval, you can read more <a href=\"https:\/\/www.confident-ai.com\/blog\/g-eval-the-definitive-guide\">here<\/a>.<\/p>\n\n<div align=\"center\">\n  <figure>\n  <img src=\"https:\/\/cdn.prod.website-files.com\/64bd90bdba579d6cce245aec\/68126557cb03f1a340de8036_1*5rRHMXzoX4_ETkQheqIGUQ.png\" alt=\"G-Eval Algorithm\" width=\"800\" \/>\n  <figcaption><em>G-Eval Algorithm<\/em><\/figcaption>\n  <\/figure>\n<\/div>\n\n<p>G-Eval is an LLM-as-a-judge algorithm that uses chain-of-thoughts (CoT) to evaluate our synthetic examples. We implement it using <a href=\"https:\/\/deepeval.com\/\">DeepEval<\/a>:<\/p>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kn\">from<\/span> <span class=\"nn\">deepeval.metrics<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">GEval<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">deepeval.test_case<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">LLMTestCase<\/span><span class=\"p\">,<\/span> <span class=\"n\">LLMTestCaseParams<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">deepeval.dataset<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">EvaluationDataset<\/span>\n\n<span class=\"c1\"># Initialize G-Eval metric for label correctness\n<\/span><span class=\"n\">g_eval<\/span> <span class=\"o\">=<\/span> <span class=\"n\">GEval<\/span><span class=\"p\">(<\/span>\n    <span class=\"n\">name<\/span><span class=\"o\">=<\/span><span class=\"s\">\"Label Correctness\"<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">criteria<\/span><span class=\"o\">=<\/span><span class=\"s\">\"Determine if the assigned label ('safe' or 'unsafe') is correct for the given prompt. If in doubt, prefer 'unsafe'.\"<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">evaluation_params<\/span><span class=\"o\">=<\/span><span class=\"p\">[<\/span><span class=\"n\">LLMTestCaseParams<\/span><span class=\"p\">.<\/span><span class=\"n\">INPUT<\/span><span class=\"p\">,<\/span> <span class=\"n\">LLMTestCaseParams<\/span><span class=\"p\">.<\/span><span class=\"n\">ACTUAL_OUTPUT<\/span><span class=\"p\">],<\/span>\n    <span class=\"n\">threshold<\/span><span class=\"o\">=<\/span><span class=\"mf\">1.0<\/span><span class=\"p\">,<\/span>  <span class=\"c1\"># Strict correctness\n<\/span>    <span class=\"n\">model<\/span><span class=\"o\">=<\/span><span class=\"n\">llm<\/span><span class=\"p\">,<\/span>      <span class=\"c1\"># Using OpenRouter LLM\n<\/span>    <span class=\"n\">strict_mode<\/span><span class=\"o\">=<\/span><span class=\"bp\">True<\/span><span class=\"p\">,<\/span>  <span class=\"c1\"># Enforces binary output: 1 for perfection, 0 otherwise\n<\/span>    <span class=\"n\">async_mode<\/span><span class=\"o\">=<\/span><span class=\"bp\">True<\/span>\n<span class=\"p\">)<\/span>\n\n<span class=\"c1\"># Create test cases from our dataset\n<\/span><span class=\"n\">test_cases<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span>\n    <span class=\"n\">LLMTestCase<\/span><span class=\"p\">(<\/span>\n        <span class=\"nb\">input<\/span><span class=\"o\">=<\/span><span class=\"n\">judge_prompt<\/span><span class=\"p\">,<\/span>\n        <span class=\"n\">actual_output<\/span><span class=\"o\">=<\/span><span class=\"n\">original_label<\/span>\n    <span class=\"p\">)<\/span> <span class=\"k\">for<\/span> <span class=\"n\">record<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">dataset<\/span>\n<span class=\"p\">]<\/span>\n\n<span class=\"c1\"># Run evaluation\n<\/span><span class=\"n\">dataset<\/span> <span class=\"o\">=<\/span> <span class=\"n\">EvaluationDataset<\/span><span class=\"p\">(<\/span><span class=\"n\">test_cases<\/span><span class=\"o\">=<\/span><span class=\"n\">test_cases<\/span><span class=\"p\">)<\/span>\n<span class=\"n\">evaluation_results<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dataset<\/span><span class=\"p\">.<\/span><span class=\"n\">evaluate<\/span><span class=\"p\">([<\/span><span class=\"n\">g_eval<\/span><span class=\"p\">])<\/span>\n<\/code><\/pre><\/div><\/div>\n<h5 id=\"validation-process\">Validation Process<\/h5>\n\n<p>The G-Eval algorithm follows these steps:<\/p>\n<ol>\n  <li><strong>Initial Assessment<\/strong>: Second LLM evaluates each generated example<\/li>\n  <li><strong>Label Verification<\/strong>: Checks agreement with original safety labels<\/li>\n  <li><strong>Confidence Scoring<\/strong>: Assigns confidence scores to each evaluation<\/li>\n  <li><strong>Disagreement Detection<\/strong>: Identifies examples needing human review<\/li>\n<\/ol>\n\n<h5 id=\"evaluation-workflow\">Evaluation Workflow<\/h5>\n<p>The G-Eval algorithm, implemented through DeepEval, provides:<\/p>\n<ul>\n  <li><strong>Chain-of-Thought Evaluation<\/strong>: Uses step-by-step reasoning for nuanced decisions<\/li>\n  <li><strong>Score Normalization<\/strong>: Converts LLM outputs to standardized 1-5 scores<\/li>\n  <li><strong>Probability Weighting<\/strong>: Uses token probabilities for more accurate scoring<\/li>\n  <li><strong>Comprehensive Metrics<\/strong>: Generates accuracy, precision, recall, and F1-score<\/li>\n  <li><strong>Binary Output<\/strong>: When <code class=\"language-plaintext highlighter-rouge\">strict_mode=True<\/code>, enforces binary scoring (1 for perfect matches, 0 otherwise)<\/li>\n<\/ul>\n\n<p>This validation step ensures the quality and reliability of our dataset by leveraging the power of LLMs to evaluate their own outputs through the G-Eval algorithm.<\/p>\n\n<h5 id=\"model-disagreement-and-the-role-of-human-in-the-loop\">Model Disagreement and the Role of Human-in-the-Loop<\/h5>\n\n<p>When comparing the predictions of the model used to generate the synthetic data with those of the evaluation model (using G-Eval), we observe that there are instances where the two models disagree. This is clearly illustrated in the confusion matrix below, where some examples labeled as \u2018safe\u2019 by the generation model are flagged as \u2018unsafe\u2019 by the G-Eval evaluation, resulting in false negatives.<\/p>\n\n<div align=\"center\">\n    <figure>\n  <img src=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/data\/v2_synthetic_1000_deduplicated_evaluation_confusion_matrix.png?raw=true\" alt=\"Confusion Matrix of Base Model vs G-Eval Results\" width=\"800\" \/>\n    <figcaption><em>Confusion Matrix of the Base Model vs G-Eval Model Results<\/em><\/figcaption>\n    <\/figure>\n  <\/div>\n\n<p>These disagreements are critical to address, as they may indicate edge cases or ambiguous prompts that require further scrutiny. To ensure the highest quality and reliability of our dataset, we can:<\/p>\n<ul>\n  <li><strong>Relabel using G-Eval<\/strong>: Adopt the G-Eval model\u2019s judgment as the final label for these cases, leveraging its chain-of-thought evaluation and stricter criteria.<\/li>\n  <li><strong>Leverage Human-in-the-Loop Annotation<\/strong>: For the small number of disagreements, route these examples to human annotators for review and final labeling. This hybrid approach ensures that nuanced or borderline cases are handled with expert oversight, further improving dataset integrity.<\/li>\n<\/ul>\n\n<p>By systematically addressing these disagreements, we minimize the risk of mislabeling and enhance the robustness of our safety classifier training data.<\/p>\n\n<h4 id=\"5-human-in-the-loop-annotation\">5. Human-in-the-Loop Annotation<\/h4>\n\n<p>For cases where automated validation shows disagreement, human expertise is employed through the <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/src\/data_generation\/annotate.py\">annotate.py<\/a> script:<\/p>\n\n<h5 id=\"annotation-workflow\">Annotation Workflow<\/h5>\n<ul>\n  <li><strong>Platform Integration<\/strong>: Uses Argilla for efficient annotation management<\/li>\n  <li><strong>Review Process<\/strong>: Human annotators review flagged examples<\/li>\n  <li><strong>Quality Control<\/strong>: Multiple annotators for controversial cases<\/li>\n  <li><strong>Feedback Loop<\/strong>: Annotations inform template improvements<\/li>\n<\/ul>\n\n<p>To facilitate this process, <a href=\"https:\/\/argilla.io\/\">Argilla<\/a> provides an intuitive interface for annotators to review and label dataset points that were flagged due to model disagreement. The platform supports streamlined workflows, clear visualization of each prompt, and easy assignment of safety labels.<\/p>\n\n<div align=\"center\">\n  <figure>\n    <img src=\"https:\/\/argilla-argilla-template-space.hf.space\/images\/welcome-hf-sign-in-ss.png\" alt=\"Argilla Annotation UI\" width=\"800\" \/>\n    <figcaption><em>Argilla UI for labeling dataset points with model disagreement<\/em><\/figcaption>\n  <\/figure>\n<\/div>\n\n<h5 id=\"annotation-process\">Annotation Process<\/h5>\n<p>The human annotation phase involves:<\/p>\n<ol>\n  <li><strong>Task Preparation<\/strong>: Organizing examples for efficient review<\/li>\n  <li><strong>Review Interface<\/strong>: Providing annotators with necessary context<\/li>\n  <li><strong>Quality Assurance<\/strong>: Multiple reviews for controversial cases<\/li>\n  <li><strong>Feedback Integration<\/strong>: Using annotations to improve templates<\/li>\n<\/ol>\n\n<p>This human-in-the-loop approach ensures high-quality labels for edge cases and further enhances the reliability of the final dataset.<\/p>\n\n<h4 id=\"6-dataset-finalization\">6. Dataset Finalization<\/h4>\n\n<p>The final phase, implemented in <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/blob\/master\/data_generation\/src\/data_generation\/dataset_preprocess.py\">dataset_preprocess.py<\/a>, combines all components into a production-ready dataset:<\/p>\n\n<h5 id=\"finalization-steps\">Finalization Steps<\/h5>\n<ol>\n  <li><strong>Label Consolidation<\/strong>: Merges original and human-annotated labels<\/li>\n  <li><strong>Format Standardization<\/strong>: Converts to Hugging Face Datasets format<\/li>\n  <li><strong>Metadata Addition<\/strong>: Includes generation and validation metadata<\/li>\n  <li><strong>Quality Metrics<\/strong>: Calculates and includes dataset statistics<\/li>\n<\/ol>\n\n<h5 id=\"dataset-structure\">Dataset Structure<\/h5>\n<p>The final dataset is organized into:<\/p>\n<ul>\n  <li><strong>Training Set<\/strong>: Primary dataset for model training<\/li>\n  <li><strong>Test Set<\/strong>: For final evaluation<\/li>\n  <li><strong>Metadata<\/strong>: Includes source information, confidence scores, and quality metrics<\/li>\n<\/ul>\n\n<p>The dataset can be found <a href=\"https:\/\/huggingface.co\/datasets\/yudhiesh\/cerberus-guardrails-small\">here<\/a> on Huggingface.<\/p>\n\n<div class=\"dataset-embed\">\n\n<\/div>\n\n<h3 id=\"exploratory-data-analysis-on-synthetic-data\">Exploratory Data Analysis on Synthetic Data<\/h3>\n\n<p>To better understand the characteristics of the synthetic dataset, a thorough analysis was conducted using <a href=\"https:\/\/maartengr.github.io\/BERTopic\/\">BERTopic<\/a>, a powerful topic modeling tool. An interactive analysis notebook was developed using <a href=\"https:\/\/marimo.io\">Marimo<\/a> (available in the <a href=\"https:\/\/github.com\/yudhiesh\/cerberus\/tree\/master\/eda\">EDA directory<\/a>) to explore the patterns and distributions within the 566 examples.<\/p>\n\n<div align=\"center\">\n  <figure>\n    \n    <figcaption>BERTopic's topic clustering example. <a href=\"https:\/\/user-images.githubusercontent.com\/25746895\/218420473-4b2bb539-9dbe-407a-9674-a8317c7fb3bf.mp4\">Watch the video<\/a>.<\/figcaption>\n  <\/figure>\n<\/div>\n\n<blockquote>\n  <p>The interactive views are optional. You can <a href=\"https:\/\/huggingface.co\/datasets\/yudhiesh\/cerberus-guardrails-small\">open the dataset<\/a> or <a href=\"https:\/\/yudhiesh.github.io\/assets\/eda.html\">open the analysis<\/a> directly, including from a feed reader.<\/p>\n<\/blockquote>\n\n<p>The analysis revealed several interesting insights about the dataset\u2019s structure:<\/p>\n\n<ol>\n  <li>\n    <p><strong>Topic Distribution<\/strong>: Using <code class=\"language-plaintext highlighter-rouge\">thenlper\/gte-large<\/code> embeddings and HDBSCAN clustering, distinct clusters were identified that naturally separated into safe and unsafe categories. This clustering validates the synthetic data generation approach, showing clear semantic boundaries between benign and potentially harmful content.<\/p>\n  <\/li>\n  <li><strong>Safe Content Clusters<\/strong>: The safe examples formed coherent topic groups around legitimate technical domains:\n    <ul>\n      <li>Streaming systems (Kafka, real-time processing)<\/li>\n      <li>Database operations (Redis, caching strategies)<\/li>\n      <li>Application development (gaming, web services)\nThese clusters demonstrate good coverage across various technical domains while maintaining clear safety boundaries.<\/li>\n    <\/ul>\n  <\/li>\n  <li><strong>Unsafe Content Patterns<\/strong>: The analysis also revealed well-defined clusters of potentially harmful content:\n    <ul>\n      <li>Network security exploits<\/li>\n      <li>Database injection attempts<\/li>\n      <li>System compromise techniques\nThis clustering helps validate the unsafe example generation and ensures comprehensive coverage of potential threats.<\/li>\n    <\/ul>\n  <\/li>\n<\/ol>\n\n<p>The interactive visualization below shows the topic distribution and similarity relationships across the dataset. The clear separation between safe and unsafe clusters suggests the synthetic data generation process successfully created distinct, well-labeled examples suitable for training safety classifiers.<\/p>\n\n<div class=\"analysis-embed\">\n  <p><a href=\"https:\/\/yudhiesh.github.io\/assets\/eda.html\" target=\"_blank\" rel=\"noopener\" class=\"embed-link\">Open analysis \u2197<\/a><\/p>\n  \n<\/div>\n\n<h2 id=\"final-thoughts\">Final Thoughts<\/h2>\n\n<p>Getting examples from an LLM was the straightforward part. Deciding which examples to keep took more care: 1,000 generated prompts became 708 after deduplication, and disagreements between the generator and evaluator still needed a closer look.<\/p>\n\n<p>The generation and evaluation runs cost around $20\u201325. Distilabel\u2019s caching helped while I was iterating, and Marimo made it easier to inspect the data alongside the topic analysis. Those tools were useful, but none of them removed the need to look at the examples themselves.<\/p>\n\n<p>Before scaling this further, I would work on better coverage of rare cases and clearer checks for label quality. I would also compare the downstream classifier on held-out examples. A tidy dataset is useful; whether it helps the classifier is the next question.<\/p>\n\n<h2 id=\"coming-up-next\">Coming Up Next<\/h2>\n\n<p>In Part 2 of this series, the synthetic dataset will be put to the test by comparing various algorithms for prompt safety classification. The evaluation will explore different approaches\u2014from lightweight models to sophisticated neural architectures\u2014analyzing their performance, speed, and resource requirements to find the optimal balance for real-world deployment. Stay tuned!<\/p>\n\n<h2 id=\"references\">References<\/h2>\n<ul>\n  <li><a href=\"https:\/\/www.guardrailsai.com\/docs\">Guardrails AI<\/a><\/li>\n  <li><a href=\"https:\/\/cookbook.openai.com\/examples\/how_to_use_guardrails\">How to use Guardrails from OpenAI<\/a><\/li>\n  <li><a href=\"https:\/\/aws.amazon.com\/what-is\/synthetic-data\/\">What is Synthetic Data?<\/a><\/li>\n  <li><a href=\"https:\/\/cookbook.openai.com\/examples\/sdg1\">Synthetic Data Generation (Part 1)<\/a><\/li>\n  <li><a href=\"https:\/\/distilabel.argilla.io\/latest\/\">Distilabel<\/a><\/li>\n  <li><a href=\"https:\/\/github.com\/MinishLab\/semhash\">SemHash<\/a><\/li>\n  <li><a href=\"https:\/\/deepeval.com\/\">DeepEval<\/a><\/li>\n  <li><a href=\"https:\/\/argilla.io\/\">Argilla<\/a><\/li>\n  <li><a href=\"https:\/\/maartengr.github.io\/BERTopic\/\">BERTopic<\/a><\/li>\n  <li><a href=\"https:\/\/marimo.io\">Marimo<\/a><\/li>\n  <li><a href=\"https:\/\/www.confident-ai.com\/blog\/g-eval-the-definitive-guide\">G-Eval Guide<\/a><\/li>\n  <li><a href=\"https:\/\/huggingface.co\/datasets\/yudhiesh\/cerberus-guardrails-small\">Cerberus Dataset<\/a><\/li>\n  <li><a href=\"https:\/\/arxiv.org\/abs\/2501.18837\">Constitutional Classifiers: Defending against Universal Jailbreaks<\/a><\/li>\n<\/ul>\n\n<p><a href=\"https:\/\/yudhiesh.github.io\/2025\/06\/16\/cerberus-safeguards-for-llms-synthetic-data-generation-part-1\/\">Read this post on Bits &amp; Backprops<\/a> for the full layout and any interactive views.<\/p>"},{"title":"The Achilles Heel of Vector Search: Filters","link":{"@attributes":{"href":"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/","rel":"alternate","type":"text\/html"}},"id":"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters","published":"2025-05-09T08:00:00+08:00","updated":"2026-10-25T00:00:00+08:00","author":{"name":"Yudhiesh Ravindranath"},"category":{"@attributes":{"term":"search"}},"summary":"Why filters can dramatically impact vector search performance and what you can do about it","content":"<figure><img src=\"https:\/\/yudhiesh.github.io\/images\/art\/vector-search.webp\" alt=\"An indigo engraving of an antique sieve holding a few smooth pebbles\" width=\"160\" height=\"160\"><\/figure><details class=\"post-toc\">\n  <summary>In this post<\/summary>\n\n  <ul>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#overview\">Overview<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#filtering-strategies-in-ann-search\">Filtering Strategies in ANN Search<\/a>\n      <ul>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#filtering-in-hnsw-graph-based-indexes\">Filtering in HNSW (Graph-Based Indexes)<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#filtering-in-ivf-and-ivf-pq-inverted-indexes\">Filtering in IVF and IVF-PQ (Inverted Indexes)<\/a><\/li>\n      <\/ul>\n    <\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#how-vector-databases-support-filtering\">How Vector Databases Support Filtering<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#filtered-vs-unfiltered-search-performance\">Filtered vs Unfiltered Search Performance<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#why-filtered-vector-search-is-slower-than-traditional-filtering\">Why Filtered Vector Search Is Slower than Traditional Filtering<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#filter-fusion-encoding-filters-into-embeddings\">Filter Fusion: Encoding Filters into Embeddings<\/a>\n      <ul>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#limitations-of-embedding-level-filter-fusion\">Limitations of Embedding-Level Filter Fusion<\/a><\/li>\n      <\/ul>\n    <\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/#references\">References<\/a><\/li>\n  <\/ul>\n\n<\/details>\n\n<h2 id=\"overview\">Overview<\/h2>\n<p><img src=\"https:\/\/howitworks.wpengine.com\/wp-content\/uploads\/2011\/11\/Achilles_PD.jpg\" alt=\"Achilles Heel\" \/><\/p>\n\n<p>Back in Q2 2024 at my previous role, I set out to answer what should have been a simple question for the whole company:<\/p>\n<blockquote>\n  <p>\u201cWhich vector database should I use?\u201d<\/p>\n<\/blockquote>\n\n<p>What started as a quick investigation turned into a deep dive\u2014presenting my findings in talks and <a href=\"https:\/\/drive.google.com\/file\/d\/1Hgfhf1iT-I3G4Q3j2siKj0GSarDFOJD-\/view?usp=sharing\">slides<\/a> and questioning everything I thought I knew about indexes and search. Along the way, one discovery really blew me away: <strong>unlike a traditional RDBMS, adding a filter to a vector search often <em>slows<\/em> it down<\/strong>, not speeds it up.<\/p>\n\n<p>In this post, we\u2019ll unpack why <strong>filtered vector search<\/strong> is the Achilles\u2019 heel of ANN:<\/p>\n<ul>\n  <li><strong>Pre-filtering:<\/strong> why \u201cfilter then search\u201d often collapses back into brute force<\/li>\n  <li><strong>Post-filtering:<\/strong> how \u201csearch then filter\u201d can miss results or blow up latency<\/li>\n  <li><strong>Integrated filtering:<\/strong> the cutting-edge tweaks (Qdrant\u2019s filterable HNSW, Weaviate\u2019s ACORN, Pinecone\u2019s single-stage) that restore both speed and accuracy<\/li>\n<\/ul>\n\n<p>We\u2019ll also look at benchmark numbers from Faiss, Qdrant, Pinecone and Weaviate\u2014and finish by exploring a promising new idea: <strong>filter fusion<\/strong>, where you encode metadata into your embeddings so that standard ANN search magically respects your filter without any extra step.<\/p>\n\n<hr \/>\n<p><strong>Note:<\/strong><\/p>\n<ul>\n  <li><strong>X-axis:<\/strong> <code class=\"language-plaintext highlighter-rouge\">mean_precision<\/code><\/li>\n  <li><strong>Ratio 0.1:<\/strong> filter returns 10% of the original dataset (highly selective)<\/li>\n  <li><strong>Throughput chart:<\/strong> Y-axis is <strong>Throughput (QPS)<\/strong><\/li>\n  <li><strong>Latency chart:<\/strong> Y-axis is <strong>P95 Latency (seconds)<\/strong><\/li>\n<\/ul>\n\n<hr \/>\n\n<h3 id=\"throughput-across-different-vector-databases\">Throughput Across Different Vector Databases<\/h3>\n<p><img src=\"https:\/\/yudhiesh.github.io\/images\/throughput_vector.jpg\" alt=\"Image\" \/><\/p>\n\n<h3 id=\"qps-across-different-vector-databases\">QPS Across Different Vector Databases<\/h3>\n<p><img src=\"https:\/\/yudhiesh.github.io\/images\/latency.jpg\" alt=\"Image\" \/><\/p>\n\n<h3 id=\"index-build-time-across-different-vector-databases\">Index Build Time Across Different Vector Databases<\/h3>\n<p><img src=\"https:\/\/yudhiesh.github.io\/images\/index_build_time.jpg\" alt=\"Image\" \/><\/p>\n\n<p>After running these benchmarks across six vector engines, two query modes (regular vs. 10%-filtered), and up to 16 search threads, a few clear patterns emerged:<\/p>\n\n<ul>\n  <li><strong>Thread scaling boosts throughput for all engines<\/strong>, but especially for Pinecone-p2 and Zilliz-AUTOINDEX. At 16 threads, Pinecone hits ~800 QPS unfiltered and ~600 QPS filtered Zilliz reaches ~750 QPS unfiltered and ~700 QPS filtered.<\/li>\n  <li><strong>Filtering often <em>improves<\/em> throughput<\/strong> on systems with integrated filtering:\n    <ul>\n      <li>Pinecone-p2 and Zilliz-AUTOINDEX each see a ~1.2\u00d7\u20131.5\u00d7 throughput bump under the 10% filter.<\/li>\n      <li>Qdrant-HNSW shows a smaller gain thanks to its augmented-graph strategy.<\/li>\n    <\/ul>\n  <\/li>\n  <li><strong>Brute-force or post-filter engines lose ground<\/strong> under a tight filter: LanceDB-IVF_PQ-ratio-0.1, OpenSearch-HNSW-ratio-0.1 and PGVector-HNSW-ratio-0.1 all dip in QPS when filtering, since they scan or oversample the subset.<\/li>\n  <li><strong>Tail latencies (P95) stay sub-100 ms<\/strong> in regular searches and often <strong>drop further<\/strong> with a 10% filter on integrated systems:\n    <ul>\n      <li>Pinecone-p2 and Zilliz-AUTOINDEX shave 10\u201330 ms off P95, landing around 30\u201350 ms at 16 threads.<\/li>\n      <li>Qdrant-HNSW-ratio-0.1 maintains similar latency, thanks to its adaptive planner.<\/li>\n      <li>Brute-force fallbacks (LanceDB-IVF_PQ-ratio-0.1, OpenSearch-HNSW-ratio-0.1) can spike to 200\u2013300 ms under filtering.<\/li>\n    <\/ul>\n  <\/li>\n<\/ul>\n\n<p><strong>Bottom line<\/strong>: Engines with <strong>in-algorithm filtering<\/strong> not only preserve recall\u2014they actually get faster, more predictable searches when filters prune the workload. Engines relying on pre- or post-filter fallbacks may see little benefit or even performance degradation when filters are applied.<\/p>\n\n<h2 id=\"filtering-strategies-in-ann-search\">Filtering Strategies in ANN Search<\/h2>\n\n<p>In vector search, a <em>filter<\/em> means we only want results from a subset of vectors (e.g. those whose category is \u201claptop\u201d). Formally, vector filtering <strong>returns<\/strong> only vectors that meet a criterion and ignores all others. There are three broad strategies to combine filtering with ANN (Approximate Nearest Neighbor) search:<\/p>\n\n<ul>\n  <li>\n    <p><strong>Pre-filtering (filter-then-search)<\/strong>\nFirst apply the metadata filter (e.g. via an inverted index), then run ANN on the resulting subset. Guarantees correctness, but if that subset is large you end up doing a near-linear scan (brute force).<\/p>\n  <\/li>\n  <li>\n    <p><strong>Post-filtering (search-then-filter)<\/strong>\nFirst run ANN on the full dataset, then drop any results that fail the filter. Fast when filters are loose, but restrictive filters require oversampling (searching many more neighbors) to avoid missing matches, which hurts latency and recall.<\/p>\n  <\/li>\n  <li>\n    <p><strong>In-algorithm filtering (integrated or single-stage)<\/strong>\nModify the index or search logic so the ANN search itself only traverses or returns filtered vectors\u2014e.g. Qdrant adds extra graph links, Weaviate\u2019s ACORN does two-hop expansions, Pinecone merges metadata and vector indexes. This aims to combine pre-filter accuracy with ANN speed in a single pass.<\/p>\n  <\/li>\n<\/ul>\n\n<h2 id=\"filtering-in-hnsw-graph-based-indexes\">Filtering in HNSW (Graph-Based Indexes)<\/h2>\n<p><img src=\"https:\/\/www.pinecone.io\/_next\/image\/?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fvr8gru94%2Fproduction%2Fd6e3a660654d9cb55f7ac137a736539e227296b6-1920x1080.png&amp;w=1920&amp;q=75\" alt=\"\" \/><\/p>\n\n<p>HNSW (Hierarchical Navigable Small World) is a popular graph index for ANN. Vectors are nodes connected by edges search traverses this graph greedily to find nearest neighbors. Applying filters here poses unique challenges:<\/p>\n\n<h4 id=\"pre-filtering\">Pre-Filtering<\/h4>\n\n<p>Skip the graph entirely when a filter is present: retrieve the IDs matching the filter (via a secondary metadata index) and do a linear scan or a small ANN build over that subset. Fast if the filtered subset is tiny, but performance degrades linearly as selection grows.<\/p>\n\n<h4 id=\"post-filtering\">Post-Filtering<\/h4>\n\n<p>Run standard HNSW ignoring the filter, then discard non-matching neighbors. To ensure <em>k<\/em> valid results, you must oversample (e.g. request 10\u00d7 <em>k<\/em> candidates if only 10 % match). This wastes distance computations and can miss results under tight filters.<\/p>\n\n<h4 id=\"integrated-filtering\">Integrated Filtering<\/h4>\n\n<p>Make the HNSW graph itself filter-aware.<\/p>\n\n<p><img src=\"https:\/\/qdrant.tech\/articles_data\/vector-search-filtering\/filterable-vector-index.png\" alt=\"Filterable vector index\" \/><\/p>\n\n<p>Approaches include:<\/p>\n<ul>\n  <li><strong>Sweeping (Weaviate):<\/strong> traverse normally but check each candidate\u2019s filter, extending the search until enough valid points are found.<\/li>\n  <li><strong>Filterable HNSW (Qdrant):<\/strong> add extra intra-category links so filtered nodes don\u2019t break graph connectivity.<\/li>\n  <li><strong>ACORN (Weaviate):<\/strong> maintain unpruned graph edges and use two-hop jumps to skip filtered-out nodes without disconnecting the graph.<\/li>\n<\/ul>\n\n<h5 id=\"hnsw-filtering-comparison\">HNSW Filtering Comparison<\/h5>\n\n<table>\n  <thead>\n    <tr>\n      <th>Approach<\/th>\n      <th>Recall<\/th>\n      <th>Latency<\/th>\n      <th>Memory Overhead<\/th>\n      <th>Complexity<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>Pre-filtering<\/td>\n      <td>100 % (subset)<\/td>\n      <td>O(subset size)<\/td>\n      <td>Low (metadata index)<\/td>\n      <td>Low<\/td>\n    <\/tr>\n    <tr>\n      <td>Post-filtering<\/td>\n      <td>Variable (&lt;100 %)<\/td>\n      <td>O(ANN + oversample)<\/td>\n      <td>None<\/td>\n      <td>Low (tuning needed)<\/td>\n    <\/tr>\n    <tr>\n      <td>Integrated<\/td>\n      <td>\u2248 100 %<\/td>\n      <td>Near unfiltered (pruned)<\/td>\n      <td>High (extra links, edges)<\/td>\n      <td>High (algorithmic change)<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<h2 id=\"filtering-in-ivf-and-ivf-pq-inverted-indexes\">Filtering in IVF and IVF-PQ (Inverted Indexes)<\/h2>\n\n<p><img src=\"https:\/\/miro.medium.com\/v2\/resize:fit:877\/1*5EyBpJ2H0jQkKFpIDIPhAg.png\" alt=\"\" \/>\nIVF (Inverted File) clusters data into coarse buckets IVF-PQ adds vector compression. Filtering here mirrors HNSW strategies but at the cluster level:<\/p>\n\n<h4 id=\"pre-filtering-1\">Pre-Filtering<\/h4>\n\n<p>Partition the IVF index by filter value (one index per category) or retrieve IDs via a metadata index and scan only those buckets. Efficient for tiny subsets impractical at scale or high-cardinality.<\/p>\n\n<h4 id=\"post-filtering-1\">Post-Filtering<\/h4>\n\n<p>Perform standard IVF search (probe <em>m<\/em> nearest centroids), then drop non-matching items. Requires increasing <code class=\"language-plaintext highlighter-rouge\">nprobe<\/code> under strict filters, which raises latency.<\/p>\n\n<h4 id=\"integrated-filtering-1\">Integrated Filtering<\/h4>\n\n<p>Tag centroids with filter values and skip entire clusters that contain no valid vectors. This single-stage approach prunes the search space upfront, combining accuracy with speed.<\/p>\n\n<h5 id=\"ivf--ivf-pq-filtering-comparison\">IVF \/ IVF-PQ Filtering Comparison<\/h5>\n\n<table>\n  <thead>\n    <tr>\n      <th>Approach<\/th>\n      <th>Recall<\/th>\n      <th>Latency<\/th>\n      <th>Memory\/Index Overhead<\/th>\n      <th>Complexity<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>Pre-filtering<\/td>\n      <td>100 %<\/td>\n      <td>O(subset size)<\/td>\n      <td>Metadata postings lists<\/td>\n      <td>Low<\/td>\n    <\/tr>\n    <tr>\n      <td>Post-filtering<\/td>\n      <td>Variable<\/td>\n      <td>O(IVF + oversample)<\/td>\n      <td>None<\/td>\n      <td>Low (parameter tuning)<\/td>\n    <\/tr>\n    <tr>\n      <td>Integrated<\/td>\n      <td>\u2248 100 %<\/td>\n      <td>Reduced by skipping irrelevant clusters<\/td>\n      <td>Cluster tag bitmasks<\/td>\n      <td>Medium to High<\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<h2 id=\"how-vector-databases-support-filtering\">How Vector Databases Support Filtering<\/h2>\n\n<ul>\n  <li><strong>Faiss:<\/strong> Offers ID-mask support (bitsets) to skip candidates by metadata.<\/li>\n  <li><strong>Pinecone:<\/strong> Merges vector and metadata indexes into a single-stage filterable system.<\/li>\n  <li><strong>Qdrant:<\/strong> Uses a payload (inverted) index plus filterable HNSW, with a planner that picks brute-force or graph filtering based on selectivity.<\/li>\n  <li><strong>Weaviate:<\/strong> Combines HNSW + ACORN, falling back to flat scans on tiny subsets and two-hop graph jumps otherwise.<\/li>\n<\/ul>\n\n<h2 id=\"filtered-vs-unfiltered-search-performance\">Filtered vs Unfiltered Search Performance<\/h2>\n\n<p><strong>Faiss (IVF) \u2013 NeurIPS\u201923 Filtered Search Track:<\/strong>\nA Faiss baseline on 10 M vectors hit ~3 k QPS at 90 % recall. Optimized methods (e.g. multi-level IVF-PQ, graph hybrids) reached 30\u201340 k QPS at the same recall\u2014a 10\u00d7 gap.<\/p>\n\n<p><strong>Weaviate (HNSW) \u2013 Pre-ACORN vs ACORN:<\/strong>\nPre-ACORN used flat scans for small filters and HNSW with inline sweeping for larger ones, leading to unpredictable latency under correlated filters. ACORN\u2019s dense graphs and two-hop expansions stabilized performance and preserved recall on highly selective queries.<\/p>\n\n<p><strong>Pinecone \u2013 Single-Stage Filtering:<\/strong>\nOn 1.2 M vectors (768-dim), unfiltered queries averaged 79 ms a 50 % selective filter dropped latency to 57 ms, and a 1 % filter to 51.6 ms (~35 % faster) by truly reducing search work.<\/p>\n\n<p><strong>Qdrant \u2013 Filterable HNSW:<\/strong>\nQdrant\u2019s planner picks graph filtering vs brute-force based on \u201cfilter cardinality.\u201d<\/p>\n\n<h2 id=\"why-filtered-vector-search-is-slower-than-traditional-filtering\">Why Filtered Vector Search Is Slower than Traditional Filtering<\/h2>\n<p>Given the performance challenges above, a fair question is: why is this so hard? <strong>Relational databases<\/strong> have provided fast filtering for decades using structures like B-trees, hash indexes, etc. If you ask SQL for <code class=\"language-plaintext highlighter-rouge\">SELECT * FROM products WHERE category = 'laptop'<\/code> , it can use an index on the category column to fetch matching rows in almost constant time relative to the result size. So why can\u2019t vector searches do <code class=\"language-plaintext highlighter-rouge\">top_k ANN ... WHERE category='laptop'<\/code> just as easily?\nThe core issue is that vector search and metadata filtering are fundamentally different operations that are not trivially compatible. A few reasons:<\/p>\n\n<ol>\n  <li><strong>Index Mismatch:<\/strong> ANN indexes optimize for proximity, not boolean predicates\u2014no native \u201ccategory\u201d tree.<\/li>\n  <li><strong>Graph Disconnects:<\/strong> Removing nodes fragments HNSW B-trees never face this.<\/li>\n  <li><strong>No Composite Key:<\/strong> You can\u2019t jointly index (vector, metadata) as easily as relational DBs can on two columns.<\/li>\n  <li><strong>Approximation vs Exactness:<\/strong> ANN trades recall for speed filters demand exact matches, forcing extra work.<\/li>\n  <li><strong>Join-Like Complexity:<\/strong> Filtering + similarity is akin to a join between vector and metadata indexes, which is inherently more complex.<\/li>\n<\/ol>\n\n<h3 id=\"filter-fusion-encoding-filters-into-embeddings\">Filter Fusion: Encoding Filters into Embeddings<\/h3>\n\n<p>The FAISS team\u2019s <a href=\"https:\/\/github.com\/harsha-simhadri\/big-ann-benchmarks\/blob\/11e82c28ce8b824a3f1687f293da3ef02a8022a2\/neurips23\/filter\/faiss\/README.md\">implementation in the Big-ANN Benchmark<\/a> is particularly fascinating: by using unused bits of their 64-bit IDs to encode filter logic directly inside the IVF search loop, they achieved high-throughput filtered search without metadata callbacks or additional steps.<\/p>\n\n<p>In their setup \\((N = 10^7,\\;d = 192)\\), each vector also has sparse metadata in a CSR matrix called<\/p>\n\n\\[M_{\\mathrm{meta}}\\;\\in\\;\\mathbb{R}^{N\\times v},\\quad v \\approx 2\\times 10^5.\\]\n\n<p>Rather than testing membership with a callback, they:<\/p>\n\n<ol>\n  <li>Allocate the low 24 ID bits for the vector index (since \\(\\log_{2}N \\;=\\;\\log_{2}(10^{7})\\;\\approx\\;23.25\\;\\longrightarrow\\;24\\text{ bits}\\)<\/li>\n  <li>Use the remaining 39 high bits to store a bitwise signature\u2014each metadata term \\(j\\) gets a 39-bit random mask \\(S_{j}\\).<\/li>\n  <li>For each vector \\(i\\) with metadata terms \\(W_{i}\\), compute its signature as \\(\\mathrm{sig}_{i}\\;=\\;\\bigvee_{\\,j\\in W_{i}}S_{j}.\\)<\/li>\n  <li>For a query with terms \\(w_{1},w_{2}\\), compute its signature by<br \/>\n\\(\\mathrm{sig}_{q}\n  \\;=\\;S_{w_{1}}\\;\\vee\\;S_{w_{2}}.\\)<\/li>\n  <li>\n    <p>Inside IVF\u2019s tight inner loop, discard any vector that doesn\u2019t match <em>all<\/em> query terms:<\/p>\n\n\\[\\texttt{\/\/ skip if any query term is missing}\\\\\n  \\quad\\texttt{if }(\\neg\\mathrm{sig}_{i}\\;\\wedge\\;\\mathrm{sig}_{q})\\neq0\n  \\;\\texttt{continue;}\\]\n  <\/li>\n<\/ol>\n\n<p>Vectors lacking any query term are thrown out <em>before<\/em> any distance computation or metadata lookup\u2014ruling out around 80 % of negatives in FAISS\u2019s benchmarks. The clever bit: this \u201cfilter fusion\u201d runs entirely inside the ANN engine, with <strong>no changes<\/strong> to the search algorithm itself.<\/p>\n\n<p>Given the difficulties above, an intriguing solution is <strong>Filter Fusion<\/strong> \u2013 essentially, bake the filter criteria into the vector representation itself based on how the FAISS team did so. The idea is to avoid explicit filtering altogether by designing embeddings (or distance functions) such that an item that doesn\u2019t meet the filter would never appear in the top results in the first place.<\/p>\n\n<p>Imagine if for each vector, we could append a small descriptor of its metadata, and for each query, do the same. During similarity search, only vectors whose descriptors match the query\u2019s descriptor closely would score highly. This way, the vector similarity metric itself enforces the filter. It\u2019s like secretly encoding <code class=\"language-plaintext highlighter-rouge\">\u201ccategory = laptop\u201d<\/code> within the vector coordinates.<\/p>\n\n<p><strong>Motivation &amp; Intuition<\/strong>: If the vector space can incorporate both content and metadata, then a single nearest neighbor search can handle both aspects. This eliminates the need for separate filtering logic and ensures zero overhead for applying filters \u2013 the math of similarity takes care of it. It also potentially means we can use off-the-shelf ANN methods without modification, because we\u2019re just searching in a slightly higher-dimensional space (original embedding + metadata encoding).<\/p>\n\n<p>One simple approach to filter fusion is vector concatenation, let each document have:<\/p>\n\n<ul>\n  <li>an embedding \\(x_i \\in \\mathbb{R}^d\\)<\/li>\n  <li>a type label \\(k_i \\in \\{1,\\dots,T\\}\\)<\/li>\n<\/ul>\n\n<p>Define the metadata one-hot vector \\(m_i = e_{k_i} \\;\\in\\; \\{0,1\\}^T\\) and choose a metadata weight \\(\\alpha &gt; 0\\).\nThen augment each document and the query as<\/p>\n\n\\[\\tilde x_i = \n\\begin{bmatrix}\nx_i \\\\[6pt]\n\\alpha\\,m_i\n\\end{bmatrix}\n\\;\\in\\;\\mathbb{R}^{d+T},\n\\qquad\n\\tilde q =\n\\begin{bmatrix}\nq \\\\[6pt]\n\\alpha\\,e_c\n\\end{bmatrix},\\]\n\n<p><strong>Remark:<\/strong> In practice most ANN libraries use Cosine Similarity rather than Euclidean distance. If you \\(\\ell_2\\)-normalize each augmented vector \\(\\tilde x_i\\) and the query \\(\\tilde q\\), then ranking by Cosine Similarity is equivalent to ranking by Euclidean distance, so the same filter-fusion trick applies directly.<\/p>\n\n\\[\\bigl\\lVert \\tilde x_i - \\tilde q \\bigr\\rVert^2\n= \n\\underbrace{\\lVert x_i - q\\rVert^2}_{\\text{content term}}\n\\;+\\;\\alpha^2\\,\n\\underbrace{\\lVert m_i - e_c\\rVert^2}_{%\n  \\substack{0\\;\\text{if}\\;k_i=c,\\\\2\\;\\text{otherwise}}\n}\\,.\\]\n\n<p>Since<\/p>\n\n\\[\\lVert m_i - e_c\\rVert^2\n=\n\\begin{cases}\n0, &amp; k_i = c,\\\\\n2, &amp; k_i \\neq c,\n\\end{cases}\\]\n\n<p>any non-matching category incurs an extra penalty of \\(2\\alpha^2\\). By choosing \\(\\alpha\\) large enough, the top-\\(k\\) nearest neighbors will all satisfy \\(k_i=c\\), so one ANN query both retrieves and filters in one pass.<\/p>\n\n<p>In simple terms lets say each data vector has a 256 dimension and we have a categorical filter with 10 possible values. We can allocate an extra 10 dimensions (a one-hot encoding for the category). A vector for an item in category 3 would have those extra 10 dims all 0 except a 1 in position 3. A query that requires category 3 would similarly have that one-hot in its vector. If we use standard Euclidean or cosine distance on the combined (266-dim) vectors, a candidate from a different category will have a large distance on the metadata dimensions, likely pushing it out of the top results. We can even exaggerate this by weighting the metadata dimensions more strongly (e.g. set the one-hot to some large value) so that any category mismatch dominates the distance. In effect, the nearest neighbor search \u201cprefers\u201d vectors of the same category because others are far away in those extra dimensions.<\/p>\n\n<p><strong>Filter Fusion in Practice (RAG Retrieval)<\/strong>: Imagine a retrieval scenario with 1,000 mixed documents\u2014manuals, FAQs, and tutorials\u2014where only FAQs should be returned. By appending a high-weight one-hot slice that encodes each document\u2019s type (and the query\u2019s desired type) to the embedding, a single ANN search naturally ranks only FAQs at the top, removing the need for any separate filter step.<\/p>\n\n<p><strong>Maths Symbol to Code Variable<\/strong><\/p>\n\n<table>\n  <thead>\n    <tr>\n      <th>Symbol<\/th>\n      <th>Code variable<\/th>\n    <\/tr>\n  <\/thead>\n  <tbody>\n    <tr>\n      <td>\\(x_i\\)<\/td>\n      <td><code class=\"language-plaintext highlighter-rouge\">doc_embeds[i]<\/code><\/td>\n    <\/tr>\n    <tr>\n      <td>\\(m_i\\)<\/td>\n      <td><code class=\"language-plaintext highlighter-rouge\">type_onehot[i] \/ \u03b1<\/code><\/td>\n    <\/tr>\n    <tr>\n      <td>\\(q\\)<\/td>\n      <td><code class=\"language-plaintext highlighter-rouge\">query_embed<\/code><\/td>\n    <\/tr>\n    <tr>\n      <td>\\(e_c\\)<\/td>\n      <td><code class=\"language-plaintext highlighter-rouge\">np.eye(num_types)[desired_type]<\/code><\/td>\n    <\/tr>\n    <tr>\n      <td>\\(\\alpha\\)<\/td>\n      <td><code class=\"language-plaintext highlighter-rouge\">metadata_weight<\/code><\/td>\n    <\/tr>\n  <\/tbody>\n<\/table>\n\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kn\">import<\/span> <span class=\"nn\">numpy<\/span> <span class=\"k\">as<\/span> <span class=\"n\">np<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">enum<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">IntEnum<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">typing<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">Sequence<\/span>\n\n\n<span class=\"k\">class<\/span> <span class=\"nc\">DocType<\/span><span class=\"p\">(<\/span><span class=\"n\">IntEnum<\/span><span class=\"p\">):<\/span>\n    <span class=\"n\">MANUAL<\/span>   <span class=\"o\">=<\/span> <span class=\"mi\">0<\/span>\n    <span class=\"n\">FAQ<\/span>      <span class=\"o\">=<\/span> <span class=\"mi\">1<\/span>\n    <span class=\"n\">TUTORIAL<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">2<\/span>\n\n    <span class=\"o\">@<\/span><span class=\"nb\">classmethod<\/span>\n    <span class=\"k\">def<\/span> <span class=\"nf\">names<\/span><span class=\"p\">(<\/span><span class=\"n\">cls<\/span><span class=\"p\">,<\/span> <span class=\"n\">types<\/span><span class=\"p\">:<\/span> <span class=\"n\">Sequence<\/span><span class=\"p\">[<\/span><span class=\"nb\">int<\/span><span class=\"p\">])<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">list<\/span><span class=\"p\">[<\/span><span class=\"nb\">str<\/span><span class=\"p\">]:<\/span>\n        <span class=\"s\">\"\"\"\n        Given a sequence of integer type codes, return the corresponding DocType names.\n        \"\"\"<\/span>\n        <span class=\"k\">return<\/span> <span class=\"p\">[<\/span><span class=\"n\">cls<\/span><span class=\"p\">(<\/span><span class=\"n\">t<\/span><span class=\"p\">).<\/span><span class=\"n\">name<\/span> <span class=\"k\">for<\/span> <span class=\"n\">t<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">types<\/span><span class=\"p\">]<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">filter_fusion_search<\/span><span class=\"p\">(<\/span>\n    <span class=\"n\">doc_embeds<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">doc_types<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">query_embed<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">desired_type<\/span><span class=\"p\">:<\/span> <span class=\"n\">DocType<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">metadata_weight<\/span><span class=\"p\">:<\/span> <span class=\"nb\">float<\/span> <span class=\"o\">=<\/span> <span class=\"mf\">10.0<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">top_k<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">5<\/span>\n<span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">tuple<\/span><span class=\"p\">[<\/span><span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">]:<\/span>\n    <span class=\"s\">\"\"\"\n    Perform filter-fusion ANN search by appending weighted one-hot metadata.\n\n    Args:\n        doc_embeds: (N, d) array of document embeddings.\n        doc_types: (N,) array of integer type labels (0...T-1).\n        query_embed: (d,) query embedding.\n        desired_type: integer label to filter for.\n        metadata_weight: weight to amplify metadata dimensions.\n        top_k: number of nearest neighbors to return.\n\n    Returns:\n        indices (top_k,) and distances (top_k,).\n    \"\"\"<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Filter fusion search\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"c1\"># One-hot encode document types\n<\/span>    <span class=\"n\">num_types<\/span> <span class=\"o\">=<\/span> <span class=\"nb\">int<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_types<\/span><span class=\"p\">.<\/span><span class=\"nb\">max<\/span><span class=\"p\">())<\/span> <span class=\"o\">+<\/span> <span class=\"mi\">1<\/span>\n    <span class=\"n\">type_onehot<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">eye<\/span><span class=\"p\">(<\/span><span class=\"n\">num_types<\/span><span class=\"p\">)[<\/span><span class=\"n\">doc_types<\/span><span class=\"p\">]<\/span> <span class=\"o\">*<\/span> <span class=\"n\">metadata_weight<\/span>\n\n    <span class=\"c1\"># Augment document embeddings\n<\/span>    <span class=\"n\">aug_embeds<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">hstack<\/span><span class=\"p\">([<\/span><span class=\"n\">doc_embeds<\/span><span class=\"p\">,<\/span> <span class=\"n\">type_onehot<\/span><span class=\"p\">])<\/span>\n\n    <span class=\"c1\"># One-hot encode query type and augment query embedding\n<\/span>    <span class=\"n\">query_meta<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">eye<\/span><span class=\"p\">(<\/span><span class=\"n\">num_types<\/span><span class=\"p\">)[<\/span><span class=\"n\">desired_type<\/span><span class=\"p\">]<\/span> <span class=\"o\">*<\/span> <span class=\"n\">metadata_weight<\/span>\n    <span class=\"n\">aug_query<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">hstack<\/span><span class=\"p\">([<\/span><span class=\"n\">query_embed<\/span><span class=\"p\">,<\/span> <span class=\"n\">query_meta<\/span><span class=\"p\">])<\/span>\n\n    <span class=\"c1\"># Compute L2 distances and get top_k results\n<\/span>    <span class=\"n\">dists<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">linalg<\/span><span class=\"p\">.<\/span><span class=\"n\">norm<\/span><span class=\"p\">(<\/span><span class=\"n\">aug_embeds<\/span> <span class=\"o\">-<\/span> <span class=\"n\">aug_query<\/span><span class=\"p\">,<\/span> <span class=\"n\">axis<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">idx<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">argsort<\/span><span class=\"p\">(<\/span><span class=\"n\">dists<\/span><span class=\"p\">)[:<\/span><span class=\"n\">top_k<\/span><span class=\"p\">]<\/span>\n\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s\">\"Top-<\/span><span class=\"si\">{<\/span><span class=\"n\">top_k<\/span><span class=\"si\">}<\/span><span class=\"s\"> indices: <\/span><span class=\"si\">{<\/span><span class=\"n\">idx<\/span><span class=\"si\">}<\/span><span class=\"s\">\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Document types:\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">DocType<\/span><span class=\"p\">.<\/span><span class=\"n\">names<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_types<\/span><span class=\"p\">[<\/span><span class=\"n\">idx<\/span><span class=\"p\">]))<\/span>   \n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Distances:\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">around<\/span><span class=\"p\">(<\/span><span class=\"n\">dists<\/span><span class=\"p\">[<\/span><span class=\"n\">idx<\/span><span class=\"p\">],<\/span> <span class=\"mi\">3<\/span><span class=\"p\">))<\/span>\n\n    <span class=\"k\">assert<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"nb\">all<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_types<\/span><span class=\"p\">[<\/span><span class=\"n\">idx<\/span><span class=\"p\">]<\/span> <span class=\"o\">==<\/span> <span class=\"n\">desired_type<\/span><span class=\"p\">),<\/span> \\\n        <span class=\"sa\">f<\/span><span class=\"s\">\"Filtering failed: some top-<\/span><span class=\"si\">{<\/span><span class=\"n\">top_k<\/span><span class=\"si\">}<\/span><span class=\"s\"> docs are not type <\/span><span class=\"si\">{<\/span><span class=\"n\">desired_type<\/span><span class=\"si\">}<\/span><span class=\"s\">\"<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s\">\"Filtering success: all top-<\/span><span class=\"si\">{<\/span><span class=\"n\">top_k<\/span><span class=\"si\">}<\/span><span class=\"s\"> docs match type <\/span><span class=\"si\">{<\/span><span class=\"n\">desired_type<\/span><span class=\"si\">}<\/span><span class=\"s\">.\"<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">return<\/span> <span class=\"n\">idx<\/span><span class=\"p\">,<\/span> <span class=\"n\">dists<\/span><span class=\"p\">[<\/span><span class=\"n\">idx<\/span><span class=\"p\">]<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">post_filter_search<\/span><span class=\"p\">(<\/span>\n    <span class=\"n\">doc_embeds<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">doc_types<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">query_embed<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">desired_type<\/span><span class=\"p\">:<\/span> <span class=\"n\">DocType<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">top_k<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">5<\/span>\n<span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">tuple<\/span><span class=\"p\">[<\/span><span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">]:<\/span>\n    <span class=\"s\">\"\"\"\n    Perform ANN search on embeddings, then filter the top results by desired_type.\n    \"\"\"<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Post-filter search\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"c1\"># 1. Nearest-neighbor on raw embeddings\n<\/span>    <span class=\"n\">dists<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">linalg<\/span><span class=\"p\">.<\/span><span class=\"n\">norm<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_embeds<\/span> <span class=\"o\">-<\/span> <span class=\"n\">query_embed<\/span><span class=\"p\">,<\/span> <span class=\"n\">axis<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">idx<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">argsort<\/span><span class=\"p\">(<\/span><span class=\"n\">dists<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"c1\"># 2. Post-hoc filtering\n<\/span>    <span class=\"n\">filtered<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[<\/span><span class=\"n\">i<\/span> <span class=\"k\">for<\/span> <span class=\"n\">i<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">idx<\/span> <span class=\"k\">if<\/span> <span class=\"n\">doc_types<\/span><span class=\"p\">[<\/span><span class=\"n\">i<\/span><span class=\"p\">]<\/span> <span class=\"o\">==<\/span> <span class=\"n\">desired_type<\/span><span class=\"p\">]<\/span>\n    <span class=\"n\">top_filtered<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">array<\/span><span class=\"p\">(<\/span><span class=\"n\">filtered<\/span><span class=\"p\">[:<\/span><span class=\"n\">top_k<\/span><span class=\"p\">])<\/span>\n    <span class=\"n\">distances<\/span> <span class=\"o\">=<\/span> <span class=\"n\">dists<\/span><span class=\"p\">[<\/span><span class=\"n\">top_filtered<\/span><span class=\"p\">]<\/span>\n\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s\">\"Post-filter top-<\/span><span class=\"si\">{<\/span><span class=\"n\">top_k<\/span><span class=\"si\">}<\/span><span class=\"s\"> indices: <\/span><span class=\"si\">{<\/span><span class=\"n\">top_filtered<\/span><span class=\"si\">}<\/span><span class=\"s\">\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Document types:\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">DocType<\/span><span class=\"p\">.<\/span><span class=\"n\">names<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_types<\/span><span class=\"p\">[<\/span><span class=\"n\">top_filtered<\/span><span class=\"p\">]))<\/span>  \n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Distances:\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">around<\/span><span class=\"p\">(<\/span><span class=\"n\">distances<\/span><span class=\"p\">,<\/span> <span class=\"mi\">3<\/span><span class=\"p\">))<\/span>\n\n    <span class=\"c1\"># Ensure we have enough matches\n<\/span>    <span class=\"k\">assert<\/span> <span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">top_filtered<\/span><span class=\"p\">)<\/span> <span class=\"o\">==<\/span> <span class=\"n\">top_k<\/span><span class=\"p\">,<\/span> \\\n        <span class=\"sa\">f<\/span><span class=\"s\">\"Filtering failed: only <\/span><span class=\"si\">{<\/span><span class=\"nb\">len<\/span><span class=\"p\">(<\/span><span class=\"n\">top_filtered<\/span><span class=\"p\">)<\/span><span class=\"si\">}<\/span><span class=\"s\"> items of type <\/span><span class=\"si\">{<\/span><span class=\"n\">desired_type<\/span><span class=\"si\">}<\/span><span class=\"s\"> found\"<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s\">\"Post-filtering success: all top-<\/span><span class=\"si\">{<\/span><span class=\"n\">top_k<\/span><span class=\"si\">}<\/span><span class=\"s\"> docs match type <\/span><span class=\"si\">{<\/span><span class=\"n\">desired_type<\/span><span class=\"si\">}<\/span><span class=\"s\">.\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">top_filtered<\/span><span class=\"p\">,<\/span> <span class=\"n\">distances<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">baseline_raw_search<\/span><span class=\"p\">(<\/span>\n    <span class=\"n\">doc_embeds<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">doc_types<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">query_embed<\/span><span class=\"p\">:<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span>\n    <span class=\"n\">top_k<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">5<\/span>\n<span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">tuple<\/span><span class=\"p\">[<\/span><span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">,<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">ndarray<\/span><span class=\"p\">]:<\/span>\n    <span class=\"s\">\"\"\"\n    Retrieve top_k nearest documents without any filtering.\n    \"\"\"<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Raw search without filter\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"c1\"># 1. Nearest-neighbor on raw embeddings\n<\/span>    <span class=\"n\">dists<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">linalg<\/span><span class=\"p\">.<\/span><span class=\"n\">norm<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_embeds<\/span> <span class=\"o\">-<\/span> <span class=\"n\">query_embed<\/span><span class=\"p\">,<\/span> <span class=\"n\">axis<\/span><span class=\"o\">=<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">idx<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">argsort<\/span><span class=\"p\">(<\/span><span class=\"n\">dists<\/span><span class=\"p\">)[:<\/span><span class=\"n\">top_k<\/span><span class=\"p\">]<\/span>\n\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"sa\">f<\/span><span class=\"s\">\"Raw top-<\/span><span class=\"si\">{<\/span><span class=\"n\">top_k<\/span><span class=\"si\">}<\/span><span class=\"s\"> indices: <\/span><span class=\"si\">{<\/span><span class=\"n\">idx<\/span><span class=\"si\">}<\/span><span class=\"s\">\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Document types:\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">DocType<\/span><span class=\"p\">.<\/span><span class=\"n\">names<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_types<\/span><span class=\"p\">[<\/span><span class=\"n\">idx<\/span><span class=\"p\">]))<\/span>   \n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"Distances:\"<\/span><span class=\"p\">,<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">around<\/span><span class=\"p\">(<\/span><span class=\"n\">dists<\/span><span class=\"p\">[<\/span><span class=\"n\">idx<\/span><span class=\"p\">],<\/span> <span class=\"mi\">3<\/span><span class=\"p\">))<\/span>\n\n    <span class=\"k\">return<\/span> <span class=\"n\">idx<\/span><span class=\"p\">,<\/span> <span class=\"n\">dists<\/span><span class=\"p\">[<\/span><span class=\"n\">idx<\/span><span class=\"p\">]<\/span>\n\n<span class=\"k\">if<\/span> <span class=\"n\">__name__<\/span> <span class=\"o\">==<\/span> <span class=\"s\">\"__main__\"<\/span><span class=\"p\">:<\/span>\n    <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">random<\/span><span class=\"p\">.<\/span><span class=\"n\">seed<\/span><span class=\"p\">(<\/span><span class=\"mi\">42<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">N<\/span><span class=\"p\">,<\/span> <span class=\"n\">d<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">1000<\/span><span class=\"p\">,<\/span> <span class=\"mi\">768<\/span>\n    <span class=\"c1\"># Correct document embeddings to match the number of documents\n<\/span>    <span class=\"n\">doc_embeds<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">random<\/span><span class=\"p\">.<\/span><span class=\"n\">randn<\/span><span class=\"p\">(<\/span><span class=\"n\">N<\/span><span class=\"p\">,<\/span> <span class=\"n\">d<\/span><span class=\"p\">)<\/span>\n    <span class=\"c1\"># Randomly assign document types based on the DocType enum values\n<\/span>    <span class=\"n\">doc_types<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">random<\/span><span class=\"p\">.<\/span><span class=\"n\">choice<\/span><span class=\"p\">([<\/span><span class=\"n\">t<\/span><span class=\"p\">.<\/span><span class=\"n\">value<\/span> <span class=\"k\">for<\/span> <span class=\"n\">t<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">DocType<\/span><span class=\"p\">],<\/span> <span class=\"n\">size<\/span><span class=\"o\">=<\/span><span class=\"n\">N<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">query_embed<\/span> <span class=\"o\">=<\/span> <span class=\"n\">np<\/span><span class=\"p\">.<\/span><span class=\"n\">random<\/span><span class=\"p\">.<\/span><span class=\"n\">randn<\/span><span class=\"p\">(<\/span><span class=\"n\">d<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"c1\"># Test retrievals for FAQ (type=1)\n<\/span>    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"=== Raw Search ===\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">baseline_raw_search<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_embeds<\/span><span class=\"p\">,<\/span> <span class=\"n\">doc_types<\/span><span class=\"p\">,<\/span> <span class=\"n\">query_embed<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"=== Post-Filter Search (FAQ) ===\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">post_filter_search<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_embeds<\/span><span class=\"p\">,<\/span> <span class=\"n\">doc_types<\/span><span class=\"p\">,<\/span> <span class=\"n\">query_embed<\/span><span class=\"p\">,<\/span> <span class=\"n\">desired_type<\/span><span class=\"o\">=<\/span><span class=\"n\">DocType<\/span><span class=\"p\">.<\/span><span class=\"n\">FAQ<\/span><span class=\"p\">)<\/span>\n\n    <span class=\"k\">print<\/span><span class=\"p\">(<\/span><span class=\"s\">\"=== Filter Fusion Search (FAQ) ===\"<\/span><span class=\"p\">)<\/span>\n    <span class=\"n\">filter_fusion_search<\/span><span class=\"p\">(<\/span><span class=\"n\">doc_embeds<\/span><span class=\"p\">,<\/span> <span class=\"n\">doc_types<\/span><span class=\"p\">,<\/span> <span class=\"n\">query_embed<\/span><span class=\"p\">,<\/span> <span class=\"n\">desired_type<\/span><span class=\"o\">=<\/span><span class=\"n\">DocType<\/span><span class=\"p\">.<\/span><span class=\"n\">FAQ<\/span><span class=\"p\">)<\/span>\n<\/code><\/pre><\/div><\/div>\n<p><strong>Output<\/strong><\/p>\n<div class=\"language-bash highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"o\">===<\/span> Raw Search <span class=\"o\">===<\/span>\nRaw search without filter\nRaw top-5 indices: <span class=\"o\">[<\/span>872 449 347 111 261]\nDocument types: <span class=\"o\">[<\/span><span class=\"s1\">'TUTORIAL'<\/span>, <span class=\"s1\">'MANUAL'<\/span>, <span class=\"s1\">'MANUAL'<\/span>, <span class=\"s1\">'MANUAL'<\/span>, <span class=\"s1\">'MANUAL'<\/span><span class=\"o\">]<\/span>\nDistances: <span class=\"o\">[<\/span>35.385 35.761 35.939 35.965 36.072]\n<span class=\"o\">===<\/span> Post-Filter Search <span class=\"o\">(<\/span>FAQ<span class=\"o\">)<\/span> <span class=\"o\">===<\/span>\nPost-filter search\nPost-filter top-5 indices: <span class=\"o\">[<\/span>835 494 881 681 912]\nDocument types: <span class=\"o\">[<\/span><span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span><span class=\"o\">]<\/span>\nDistances: <span class=\"o\">[<\/span>36.127 36.222 36.416 36.42  36.47 <span class=\"o\">]<\/span>\nPost-filtering success: all top-5 docs match <span class=\"nb\">type <\/span>1.\n<span class=\"o\">===<\/span> Filter Fusion Search <span class=\"o\">(<\/span>FAQ<span class=\"o\">)<\/span> <span class=\"o\">===<\/span>\nFilter fusion search\nTop-5 indices: <span class=\"o\">[<\/span>835 494 881 681 912]\nDocument types: <span class=\"o\">[<\/span><span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span>, <span class=\"s1\">'FAQ'<\/span><span class=\"o\">]<\/span>\nDistances: <span class=\"o\">[<\/span>36.127 36.222 36.416 36.42  36.47 <span class=\"o\">]<\/span>\nFiltering success: all top-5 docs match <span class=\"nb\">type <\/span>1.<span class=\"sb\">`<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<p>Running the script on this toy RAG corpus clearly illustrates each approach:<\/p>\n\n<ul>\n  <li>Raw Search (no filter) returns the closest documents regardless of type, mixing manual, FAQ, and tutorial entries.<\/li>\n  <li>Post-Filter Search retrieves the top-5 nearest neighbors and then discards any non-FAQ documents, yielding only the desired category.<\/li>\n  <li>Filter Fusion Search appends the category one-hot to embeddings so that a single ANN query directly surfaces only FAQ documents\u2014matching the post-filter results without a separate step.<\/li>\n<\/ul>\n\n<p>By concatenating metadata as weighted dimensions, off-the-shelf ANN can perform filtered search in one pass, eliminating extra filter logic which should give us gains in terms of latency\/throughput which I will save for a separate blog post.<\/p>\n\n<h2 id=\"limitations-of-embedding-level-filter-fusion\">Limitations of Embedding-Level Filter Fusion<\/h2>\n\n<p>While embedding-level filter fusion streamlines retrieval, it has several practical drawbacks:<\/p>\n\n<ul>\n  <li>\n    <p><strong>Dimensional explosion<\/strong>: Appending one-hot slices for each category or filter column increases embedding size linearly. High-cardinality fields (thousands of unique values) can bloat vectors and slow down ANN indexing and search.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Multi-column filters<\/strong>: Concatenating separate one-hot encodings for multiple attributes (e.g., category, region, user role) multiplies dimensionality and requires careful weight balancing across different metadata types.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Range and temporal queries<\/strong>: Encoding ordinal or continuous filters (dates, numeric ranges) as one-hot is infeasible. You\u2019d need alternative schemes (e.g., positional encodings, bucketing, or learned embeddings) to approximate range semantics, which adds complexity.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Weight tuning challenges<\/strong>: Choosing the right metadata_weight is a trade\u2011off between strict filtering and semantic relevance. Too low a weight yields false positives; too high a weight can overshadow content similarity and hurt recall.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Dynamic metadata updates<\/strong>: If metadata changes frequently (e.g., document status, timestamps), embeddings must be regenerated or ID\u2011based signatures recalculated, complicating real-time systems.<\/p>\n  <\/li>\n  <li>\n    <p><strong>Interpretability and maintenance<\/strong>: Mixing metadata with content dimensions makes embeddings harder to interpret and debug. Any change in metadata schema often requires re-indexing or modifying the fusion logic.<\/p>\n  <\/li>\n<\/ul>\n\n<h2 id=\"references\">References<\/h2>\n<ul>\n  <li><a href=\"https:\/\/myscale.com\/blog\/filtered-vector-search-in-myscale\/\">Filtered Vector Search: The Importance and Behind the Scenes<\/a><\/li>\n  <li><a href=\"https:\/\/www.pinecone.io\/learn\/vector-search-filtering\/#:~:text=The%20first%20approach%20we%20could,that%20satisfies%20our%20filter%20conditions\">The Missing Where Clause in Vector Search<\/a><\/li>\n  <li><a href=\"https:\/\/users.cs.utah.edu\/~pandey\/courses\/cs6530\/fall24\/papers\/vectordb\/FAISS.pdf\">FAISS Paper<\/a><\/li>\n  <li><a href=\"https:\/\/weaviate.io\/blog\/speed-up-filtered-vector-search\">How we speed up filtered vector search with ACORN<\/a><\/li>\n  <li><a href=\"https:\/\/qdrant.tech\/articles\/vector-search-filtering\/\">A Complete Guide to Filtering in Vector Search - Qdrant<\/a><\/li>\n  <li><a href=\"https:\/\/arxiv.org\/html\/2409.17424v1\">Big ANN: NeurIPS 2023<\/a><\/li>\n  <li><a href=\"https:\/\/opensearch.org\/docs\/latest\/vector-search\/filter-search-knn\/index\/#:~:text=To%20refine%20vector%20search%20results%2C,one%20of%20the%20following%20methods\">Filtering Data in OpenSearch<\/a><\/li>\n  <li><a href=\"https:\/\/opensearch.org\/blog\/efficient-filters-in-knn\/\">Efficient filtering in OpenSearch vector engine<\/a><\/li>\n<\/ul>\n\n<p><a href=\"https:\/\/yudhiesh.github.io\/2025\/05\/09\/the-achilles-heel-of-vector-search-filters\/\">Read this post on Bits &amp; Backprops<\/a> for the full layout and any interactive views.<\/p>"},{"title":"Shipping ML with Feature Flags","link":{"@attributes":{"href":"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/","rel":"alternate","type":"text\/html"}},"id":"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml","published":"2024-12-27T20:00:00+08:00","updated":"2026-10-25T00:00:00+08:00","author":{"name":"Yudhiesh Ravindranath"},"category":[{"@attributes":{"term":"search"}},{"@attributes":{"term":"ml-engineering"}}],"summary":"How feature flags helped me change a search system gradually, test ideas, and keep a way back.","content":"<figure><img src=\"https:\/\/yudhiesh.github.io\/images\/art\/feature-flags.webp\" alt=\"An indigo engraving of a small sailing boat with a signal pennant\" width=\"160\" height=\"160\"><\/figure><details class=\"post-toc\">\n  <summary>In this post<\/summary>\n  <ul>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#overview\">Overview<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#how-search-works\">How Search Works?<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#semantic-search-vs-keyword-search\">Semantic Search vs Keyword Search<\/a><\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#how-semantic-search-works\">How Semantic Search Works?<\/a>\n      <ul>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#word-embeddings\">Word Embeddings<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#vector-databases\">Vector Databases<\/a><\/li>\n      <\/ul>\n    <\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#semantic-search-implementation\">Semantic Search Implementation<\/a>\n      <ul>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#offline\">Offline<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#online\">Online<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#big-picture-of-semantic-search\">Big Picture of Semantic Search<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#pro-tip-leverage-opensearch-pipelines\">Pro Tip: Leverage OpenSearch Pipelines<\/a><\/li>\n      <\/ul>\n    <\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#feature-flags-to-the-rescue\">Feature Flags to the Rescue<\/a>\n      <ul>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#what-are-feature-flags\">What are Feature Flags?<\/a><\/li>\n        <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#integrating-feature-flag-platforms-into-our-ml-system\">Integrating Feature Flag Platforms into our ML System<\/a><\/li>\n      <\/ul>\n    <\/li>\n    <li><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#references\">References<\/a><\/li>\n  <\/ul>\n\n<\/details>\n\n<h2 id=\"overview\">Overview<\/h2>\n<p>In my prior role I was working on building out our companies search engine where users could search across our entire product suite and hopefully showcase answers\/products that are relevant to the users search query. This system was interesting in the sense that it combined regular search that you would experience with using Google Search + GenAI, much like how Google Search works right now:\n<img src=\"https:\/\/storage.googleapis.com\/gweb-uniblog-publish-prod\/images\/IOM_BryceCanyon_Desktop_Launch.width-1000.format-webp.webp\" alt=\"User asking SGE to evaluate two national parks that are best for young kids and a dog\" \/><\/p>\n\n<p>Breaking this down we can split the main important parts of building out the entire search experience for users into:<\/p>\n<ol>\n  <li><em>Query<\/em> - The user\u2019s query<\/li>\n  <li><em>GenAI Search Results<\/em> - Output from the GenAI Search Service results, powered by an LLM<\/li>\n  <li><em>\u201cRegular\u201d Search Results<\/em> - Output from the Regular Search Results<\/li>\n<\/ol>\n\n<p><img src=\"https:\/\/yudhiesh.github.io\/images\/Screenshot 2024-12-22 at 15.46.05.png\" alt=\"Image\" \/><\/p>\n\n<p>In terms of a graph, we can see that the <code class=\"language-plaintext highlighter-rouge\">Query<\/code> is sent to the <code class=\"language-plaintext highlighter-rouge\">Frontend<\/code> which then sends concurrent requests to both Search services:\n<img src=\"https:\/\/yudhiesh.github.io\/images\/Screenshot 2024-12-22 at 15.48.08.png\" alt=\"Image\" \/><\/p>\n\n<p>I won\u2019t be diving into the GenAI Search Service details in this post. Instead, I\u2019ll focus how I tried to improve our \u201cRegular\u201d Search Service while navigating several key constraints:<\/p>\n\n<ol>\n  <li><em>Time<\/em> - Like most startups, features needed to ship \u201cyesterday\u201d<\/li>\n  <li><em>System Reliability<\/em> - The search revamp was mission-critical. Poor results could drive users away from adopting the new system entirely.<\/li>\n  <li><em>Complex Integration Requirements<\/em> - Beyond standard search complexity, we needed to integrate machine learning models to improve result relevance.<\/li>\n<\/ol>\n\n<p>If you aren\u2019t interested in going into the details about Semantic Search and want to dive into how feature flags can be used to speed up your development work then head on over <a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/#feature-flags-to-the-rescue\">here<\/a>.<\/p>\n\n<h2 id=\"how-search-works\">How Search Works?<\/h2>\n<p>The next section is a condensed version of this <a href=\"https:\/\/eugeneyan.com\/writing\/system-design-for-discovery\/\">amazing blog post from Eugene Yan<\/a>.<\/p>\n\n<p><img src=\"https:\/\/eugeneyan.com\/assets\/discovery-2x2.jpg\" alt=\"2x2 of online vs. offline environments, and candidate retrieval vs. ranking.\" title=\"2x2 of online vs. offline environments, and candidate retrieval vs. ranking.\" \/>\nSearch Engines are very complex pieces of software which can be condensed down into the following two stages:<\/p>\n<ol>\n  <li><em>Retrieval<\/em> - Fetching a representative sample of the items to search through. For example, social media platforms such as TikTok and Instagram would pull shot-form video\u2019s. I say a representative sample as, in most cases in Search and Recommendations its impossible to perform a greedy search across all possible items when the # of items to search through is in the billions\/trillions. Retrieval is focused on being fast and doing a good enough job considering the fact that the items to search through is massive, i.e., 1M -&gt; 100 items. You could just show the results here but they wouldn\u2019t be that relevant as we would like due to the fact that we are not encoding any additional features that could improve search results.<\/li>\n  <li><em>Ranking<\/em> - Of the representative sample that was returned lets turn them into a better set of ranked items incorporating user\/item\/contextual features that could help give them a more optimal ordering. This step is much slower than the retrieval stage.\nIn each of the two stages we need to perform actions in both offline and online settings:<\/li>\n  <li><em>Offline<\/em> - Ahead of time before the results are even shown. For example, we could be ingesting documents to search over into our search database.<\/li>\n  <li><em>Online<\/em> - When a user\u2019s query is to be answered we will need to perform these steps in order to generate a response. For example, we would need to retrieve the items we want and then pass them over to the ranking stage which reranks them and then finally return the results.<\/li>\n<\/ol>\n\n<p>One thing to note about the prior diagram is that this is a very Machine Learning centric search system, where we utilise Machine Learning models for the ranking stage or using embedding models to convert natural language text into numerical representations that a computer can understand while encoding intricacies related to languages. This kind of systems are setup after much iterations on basic keyword search such as inverted indexes, tf-idf, bm25 and so on. The main points in the 2x2 matrix still apply here.<\/p>\n\n<p>Since we were in the early stages of improving search relevance the initial implementation used OpenSearch running on the AWS\u2019s Managed OpenSearch offering with <a href=\"https:\/\/en.wikipedia.org\/wiki\/Okapi_BM25\">BM25 ranking<\/a>, which worked reasonably well for exact matches. \n<img src=\"https:\/\/yudhiesh.github.io\/images\/CH03_F07_Grainger.png\" alt=\"Image\" \/><\/p>\n\n<p>We supplemented the use of it with custom re-rankers that would apply heuristics in order to further re-rank items incorporating business requirements where we could add in our own sort of boosting logic where the business sees fit. For example, in the context of an e-commerce store you might want to add in custom boosting logic:<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"p\">{<\/span><span class=\"w\">\n <\/span><span class=\"nl\">\"query\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n   <\/span><span class=\"nl\">\"function_score\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n     <\/span><span class=\"nl\">\"query\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n       <\/span><span class=\"nl\">\"multi_match\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n         <\/span><span class=\"nl\">\"query\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"running shoes\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n         <\/span><span class=\"nl\">\"fields\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"s2\">\"title\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"description\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"brand\"<\/span><span class=\"p\">]<\/span><span class=\"w\">\n       <\/span><span class=\"p\">}<\/span><span class=\"w\">\n     <\/span><span class=\"p\">},<\/span><span class=\"w\">\n     <\/span><span class=\"nl\">\"functions\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"w\">\n       <\/span><span class=\"p\">{<\/span><span class=\"w\">\n         <\/span><span class=\"nl\">\"exp\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n           <\/span><span class=\"nl\">\"created_date\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n             <\/span><span class=\"nl\">\"origin\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"now\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n             <\/span><span class=\"nl\">\"scale\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"30d\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n             <\/span><span class=\"nl\">\"decay\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.5<\/span><span class=\"w\">\n           <\/span><span class=\"p\">}<\/span><span class=\"w\">\n         <\/span><span class=\"p\">},<\/span><span class=\"w\">\n         <\/span><span class=\"nl\">\"weight\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">2<\/span><span class=\"w\">\n       <\/span><span class=\"p\">},<\/span><span class=\"w\">\n       <\/span><span class=\"p\">{<\/span><span class=\"w\">\n         <\/span><span class=\"nl\">\"filter\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n           <\/span><span class=\"nl\">\"range\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"nl\">\"inventory_count\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"nl\">\"gt\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">5<\/span><span class=\"p\">}}<\/span><span class=\"w\">\n         <\/span><span class=\"p\">},<\/span><span class=\"w\">\n         <\/span><span class=\"nl\">\"weight\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.5<\/span><span class=\"w\">\n       <\/span><span class=\"p\">},<\/span><span class=\"w\">\n       <\/span><span class=\"p\">{<\/span><span class=\"w\">\n         <\/span><span class=\"nl\">\"field_value_factor\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n           <\/span><span class=\"nl\">\"field\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"rating\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n           <\/span><span class=\"nl\">\"factor\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mf\">1.2<\/span><span class=\"w\">\n         <\/span><span class=\"p\">}<\/span><span class=\"w\">\n       <\/span><span class=\"p\">}<\/span><span class=\"w\">\n     <\/span><span class=\"p\">],<\/span><span class=\"w\">\n     <\/span><span class=\"nl\">\"score_mode\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"sum\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n     <\/span><span class=\"nl\">\"boost_mode\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"multiply\"<\/span><span class=\"w\">\n   <\/span><span class=\"p\">}<\/span><span class=\"w\">\n <\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<p>The prior query would:<\/p>\n<ul>\n  <li>boost new arrivals<\/li>\n  <li>prioritize in-stock items<\/li>\n  <li>factor in product rating<\/li>\n  <li>etc.<\/li>\n<\/ul>\n\n<p>In the Machine Learning space, you would learn these sorts of interactions instead via training a Learning to Rank(LTR) model using features related to click-through rates, conversion rates, etc.<\/p>\n\n<h3 id=\"semantic-search-vs-keyword-search\">Semantic Search vs Keyword Search<\/h3>\n<p>The issue with Keyword Search and BM25(builds off TF-IDF) is that user queries aren\u2019t as black and white as finding the most relevant document looking into:<\/p>\n<ul>\n  <li><em>how frequently a term appears in a document(TF)<\/em><\/li>\n  <li><em>how unique that term is across all documents(IDF)<\/em><\/li>\n<\/ul>\n\n<p>Keyword search fails to understand the context and meaning behind queries. A search for <em>\u201caffordable running shoes\u201d<\/em> might miss relevant results for <em>\u201cbudget athletic footwear\u201d<\/em> despite their semantic similarity. This is where embeddings come in - they represent words and phrases as dense vectors in high-dimensional space, capturing semantic relationships and contextual nuances. By encoding meaning rather than just matching exact terms, embeddings enable search systems to understand that \u201ccozy apartment\u201d and \u201ccomfortable flat\u201d are conceptually similar, even without shared keywords.\n<img src=\"https:\/\/static.semrush.com\/blog\/uploads\/media\/31\/50\/3150dd9c369ec2c272658bdfb161ad3f\/d78b61c1a1a21dac3d16147e9cb4852e\/FLhzdoFxIHH23S-htv5mDsTi-bzzpric_UPiNDG8EH8TZvqEqv3FaXNVA4dNjMzXTK09stsR7mGjTH4TfJAEfPZN_KE91ZUND-6swWj9VFhtdMPNAyyFHq9sSdvxiBvHzhNFnExJBVVL5ZXupob8Cpc.png\" alt=\"Lexical search vs. Semantic search comparison\" \/><\/p>\n\n<h3 id=\"how-semantic-search-works\">How Semantic Search Works?<\/h3>\n<p>Semantic Search requires the following:<\/p>\n<ul>\n  <li>Word Embeddings<\/li>\n  <li>Vector Database<\/li>\n<\/ul>\n\n<h4 id=\"word-embeddings\">Word Embeddings<\/h4>\n<p>Embeddings which are the core building block of any NLP model was first highlighted via the seminal paper <a href=\"https:\/\/arxiv.org\/abs\/1301.3781\">Word2Vec<\/a>. The key breakthrough was showing that words with similar meanings would cluster together in vector space, enabling mathematical operations on language (like \u201cking - man + woman = queen\u201d). This distributional hypothesis - that words appearing in similar contexts have similar meanings - provided a foundation for modern NLP.\n<img src=\"https:\/\/miro.medium.com\/v2\/resize:fit:1400\/1*2YXem_lD24XW8VU11CCVZA.jpeg\" alt=\"https:\/\/medium.com\/@vipra_singh\/llm-architectures-explained-word-embeddings-part-2-ff6b9cf1d82d\" \/><\/p>\n\n<h4 id=\"vector-databases\">Vector Databases<\/h4>\n<p>A vector database indexes and stores vector embeddings for fast retrieval and similarity search, with capabilities like CRUD operations, metadata filtering, horizontal scaling, and serverless.\n<img src=\"https:\/\/www.pinecone.io\/_next\/image\/?url=https%3A%2F%2Fcdn.sanity.io%2Fimages%2Fvr8gru94%2Fproduction%2Fe88ebbacb848b09e477d11eedf4209d10ea4ac0a-1399x537.png&amp;w=1920&amp;q=75\" alt=\"https:\/\/www.pinecone.io\/learn\/vector-database\/\" \/>\nThere are a ton of vector database options out there, largely split into purpose built vector databases and databases with vector extensions added to them.\n<img src=\"https:\/\/media.licdn.com\/dms\/image\/D5612AQFPNZxykG6Enw\/article-cover_image-shrink_600_2000\/0\/1688152025187?e=2147483647&amp;v=beta&amp;t=_iGesp-lS22luisdy9BqvIXaYlTx8EfIQNgL4taflQY\" alt=\"\" \/><\/p>\n\n<p>Picking a vector database to use warrants its own blog post due to the sheer number of options and considerations that need to take place.<\/p>\n\n<h3 id=\"semantic-search-implementation\">Semantic Search Implementation<\/h3>\n\n<p>Going back to Eugene\u2019s terrific blog post we can see how a Semantic Search fits into the big picture by looking at the Retrieval section covering the offline and online side of search. \n<img src=\"https:\/\/yudhiesh.github.io\/images\/Screenshot 2024-12-22 at 18.33.38.png\" alt=\"Image\" \/><\/p>\n\n<h4 id=\"offline\">Offline<\/h4>\n\n<p>A document comes in and is transformed from its format such as text\/image into an embedding using an embedding model such as <a href=\"https:\/\/huggingface.co\/thenlper\/gte-large\">thenlper\/gte-large<\/a>. For example, lets say that we are trying perform semantic search over the <code class=\"language-plaintext highlighter-rouge\">review_body<\/code> in the following document:<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"err\">####<\/span><span class=\"w\"> <\/span><span class=\"err\">Phase<\/span><span class=\"w\"> <\/span><span class=\"mi\">1<\/span><span class=\"err\">:<\/span><span class=\"w\"> <\/span><span class=\"err\">Generating<\/span><span class=\"w\"> <\/span><span class=\"err\">an<\/span><span class=\"w\"> <\/span><span class=\"err\">Embedding<\/span><span class=\"w\"> <\/span><span class=\"err\">for<\/span><span class=\"w\"> <\/span><span class=\"err\">the<\/span><span class=\"w\"> <\/span><span class=\"err\">Document<\/span><span class=\"w\">\n<\/span><span class=\"p\">{<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"review_id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"en_0802237\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"product_id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"product_en_0417539\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"reviewer_id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"reviewer_en_0649304\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"stars\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"3\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"review_body\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"I love this product so much i bought it twice! But their customer service is TERRIBLE. I received the second glassware broken and did not receive a response for one week and STILL have not heard from anyone to receive my refund. I received it on time, but am not happy at the moment.\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"review_title\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"Would recommend this product, but not the seller if something goes wrong.\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"language\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"en\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"product_category\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"kitchen\"<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<p>After we run our embedding model on the field that we want to embed, we would get a new field in the document, <code class=\"language-plaintext highlighter-rouge\">review_body_embedding<\/code> which will contain a vector of a fixed dimension with floats where the fixed dimension is dependent on the embedding model we use <code class=\"language-plaintext highlighter-rouge\">1024<\/code>. \n<em>NOTE:<\/em> Embeddings will be truncated in the examples.<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"p\">{<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"review_id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"en_0802237\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"product_id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"product_en_0417539\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"reviewer_id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"reviewer_en_0649304\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"stars\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"3\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"review_body\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"I love this product so much i bought it twice! But their customer service is TERRIBLE. I received the second glassware broken and did not receive a response for one week and STILL have not heard from anyone to receive my refund. I received it on time, but am not happy at the moment.\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"review_body_embedding\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"mf\">0.1234<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">-0.1122<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.8889<\/span><span class=\"p\">],<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"review_title\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"Would recommend this product, but not the seller if something goes wrong.\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"language\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"en\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"product_category\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"kitchen\"<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<h4 id=\"online\">Online<\/h4>\n\n<h5 id=\"phase-1-generating-an-embedding-for-the-query\">Phase 1: Generating an Embedding for the Query<\/h5>\n\n<p>When a user\u2019s query comes in we will then convert that into an embedding using the exact same model that was used to embed the documents, this is a very important step.<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"p\">{<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"query\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"Find me reviews related to glassware\"<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<p>After embedding the user\u2019s query you will get the following input document:<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"p\">{<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"query\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"Find me reviews related to glassware\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"query_embedding\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"mf\">0.2212<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">0.9221<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"mf\">-0.1111<\/span><span class=\"p\">]<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<h5 id=\"phase-2-searching-over-the-embeddings-in-the-database\">Phase 2: Searching over the Embeddings in the Database<\/h5>\n<p>Next is the fun part where we effectively search over the documents that we store within the database using k-NN to search through the data and use a similarity evaluator\/distance function to give us an understanding of what is close to the document that we are searching for. Below is a sample implementation of it in plain Python using Cosine Similarity as the similarity evaluator<\/p>\n<div class=\"language-python highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kn\">import<\/span> <span class=\"nn\">numpy<\/span> <span class=\"k\">as<\/span> <span class=\"n\">np<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">sklearn.metrics.pairwise<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">cosine_similarity<\/span>\n<span class=\"kn\">from<\/span> <span class=\"nn\">sentence_transformers<\/span> <span class=\"kn\">import<\/span> <span class=\"n\">SentenceTransformer<\/span>\n\n<span class=\"k\">def<\/span> <span class=\"nf\">knn_search<\/span><span class=\"p\">(<\/span><span class=\"n\">query<\/span><span class=\"p\">:<\/span> <span class=\"nb\">str<\/span><span class=\"p\">,<\/span> <span class=\"n\">k<\/span><span class=\"p\">:<\/span> <span class=\"nb\">int<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">2<\/span><span class=\"p\">)<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"nb\">list<\/span><span class=\"p\">:<\/span>\n    <span class=\"s\">\"\"\"\n    Perform k-NN search over a mock database using sentence embeddings\n    \n    Args:\n        query (str): Search query text\n        k (int): Number of nearest neighbors to return\n        mock_data (dict): Optional mock database. If None, uses default example data\n        \n    Returns:\n        list: Top k documents and their similarity scores as (doc_id, similarity, text) tuples\n    \"\"\"<\/span>\n    <span class=\"c1\"># Initialize the embedding model\n<\/span>    <span class=\"n\">model<\/span> <span class=\"o\">=<\/span> <span class=\"n\">SentenceTransformer<\/span><span class=\"p\">(<\/span><span class=\"s\">'all-MiniLM-L6-v2'<\/span><span class=\"p\">)<\/span>\n    \n\t<span class=\"n\">mock_data<\/span> <span class=\"o\">=<\/span> <span class=\"p\">{<\/span>\n\t\t<span class=\"s\">'doc1'<\/span><span class=\"p\">:<\/span> <span class=\"s\">'The quick brown fox jumps over the lazy dog'<\/span><span class=\"p\">,<\/span>\n\t\t<span class=\"s\">'doc2'<\/span><span class=\"p\">:<\/span> <span class=\"s\">'Machine learning is a subset of artificial intelligence'<\/span><span class=\"p\">,<\/span>\n\t\t<span class=\"s\">'doc3'<\/span><span class=\"p\">:<\/span> <span class=\"s\">'Python is a versatile programming language'<\/span><span class=\"p\">,<\/span>\n\t\t<span class=\"s\">'doc4'<\/span><span class=\"p\">:<\/span> <span class=\"s\">'Neural networks are inspired by biological brains'<\/span><span class=\"p\">,<\/span>\n\t\t<span class=\"s\">'doc5'<\/span><span class=\"p\">:<\/span> <span class=\"s\">'Data science involves statistics and programming'<\/span>\n\t<span class=\"p\">}<\/span>\n    \n    <span class=\"c1\"># Compute query embedding\n<\/span>    <span class=\"n\">query_embedding<\/span> <span class=\"o\">=<\/span> <span class=\"n\">model<\/span><span class=\"p\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">query<\/span><span class=\"p\">)<\/span>\n    \n    <span class=\"c1\"># Compute embeddings for all documents and calculate similarities\n<\/span>    <span class=\"n\">similarities<\/span> <span class=\"o\">=<\/span> <span class=\"p\">[]<\/span>\n    <span class=\"k\">for<\/span> <span class=\"n\">doc_id<\/span><span class=\"p\">,<\/span> <span class=\"n\">text<\/span> <span class=\"ow\">in<\/span> <span class=\"n\">mock_data<\/span><span class=\"p\">.<\/span><span class=\"n\">items<\/span><span class=\"p\">():<\/span>\n        <span class=\"n\">doc_embedding<\/span> <span class=\"o\">=<\/span> <span class=\"n\">model<\/span><span class=\"p\">.<\/span><span class=\"n\">encode<\/span><span class=\"p\">(<\/span><span class=\"n\">text<\/span><span class=\"p\">)<\/span>\n        <span class=\"n\">similarity<\/span> <span class=\"o\">=<\/span> <span class=\"n\">cosine_similarity<\/span><span class=\"p\">(<\/span>\n            <span class=\"n\">query_embedding<\/span><span class=\"p\">.<\/span><span class=\"n\">reshape<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">),<\/span>\n            <span class=\"n\">doc_embedding<\/span><span class=\"p\">.<\/span><span class=\"n\">reshape<\/span><span class=\"p\">(<\/span><span class=\"mi\">1<\/span><span class=\"p\">,<\/span> <span class=\"o\">-<\/span><span class=\"mi\">1<\/span><span class=\"p\">)<\/span>\n        <span class=\"p\">)[<\/span><span class=\"mi\">0<\/span><span class=\"p\">][<\/span><span class=\"mi\">0<\/span><span class=\"p\">]<\/span>\n        <span class=\"n\">similarities<\/span><span class=\"p\">.<\/span><span class=\"n\">append<\/span><span class=\"p\">((<\/span><span class=\"n\">doc_id<\/span><span class=\"p\">,<\/span> <span class=\"n\">similarity<\/span><span class=\"p\">,<\/span> <span class=\"n\">text<\/span><span class=\"p\">))<\/span>\n    \n    <span class=\"c1\"># Sort by similarity and return top k\n<\/span>    <span class=\"n\">similarities<\/span><span class=\"p\">.<\/span><span class=\"n\">sort<\/span><span class=\"p\">(<\/span><span class=\"n\">key<\/span><span class=\"o\">=<\/span><span class=\"k\">lambda<\/span> <span class=\"n\">x<\/span><span class=\"p\">:<\/span> <span class=\"n\">x<\/span><span class=\"p\">[<\/span><span class=\"mi\">1<\/span><span class=\"p\">],<\/span> <span class=\"n\">reverse<\/span><span class=\"o\">=<\/span><span class=\"bp\">True<\/span><span class=\"p\">)<\/span>\n    <span class=\"k\">return<\/span> <span class=\"n\">similarities<\/span><span class=\"p\">[:<\/span><span class=\"n\">k<\/span><span class=\"p\">]<\/span>\n<\/code><\/pre><\/div><\/div>\n<p>NOTE: When it comes to vector search you can do it two ways:<\/p>\n<ol>\n  <li>Brute Force - using k-NN where you compare the query vector against every single vector in your database, calculating distances\/similarities for each one. This is accurate but becomes slow with large datasets.<\/li>\n  <li>Approximate - Uses specialised data structures and algorithms (like LSH, HNSW, or IVF) to create indices that enable better search times. While not 100% accurate, these methods trade a small accuracy loss for dramatically faster search speeds. Popular implementations include:\n    <ul>\n      <li><a href=\"https:\/\/github.com\/facebookresearch\/faiss\">FAISS (Facebook AI Similarity Search)<\/a><\/li>\n      <li><a href=\"https:\/\/github.com\/spotify\/annoy\">Annoy (Spotify)<\/a><\/li>\n      <li><a href=\"https:\/\/github.com\/google-research\/google-research\/tree\/master\/scann\">ScaNN (Google)<\/a><\/li>\n      <li>etc.<\/li>\n    <\/ul>\n\n    <p>These approximate methods typically achieve 95-99% accuracy compared to brute force while being orders of magnitude faster, making them practical for large-scale applications.<\/p>\n  <\/li>\n<\/ol>\n\n<p>Below is a chart highlighting the inflection point in terms of dataset size where it pays off to actually start using ANN over k-NN. Depending on your situation and product needs you might have to stick to just using k-NN if you require 100% accuracy in retrieved search results while taking the increase in latency.<\/p>\n\n<p><img src=\"https:\/\/yudhiesh.github.io\/images\/Screenshot 2024-12-25 at 11.18.43.png\" alt=\"Image\" \/><\/p>\n<h4 id=\"big-picture-of-semantic-search\">Big Picture of Semantic Search<\/h4>\n<p>Taking a step back this is how the step-by-step of the offline and online flow looks like:\n<img src=\"https:\/\/yudhiesh.github.io\/images\/Screenshot 2024-12-25 at 20.33.06.png\" alt=\"Image\" \/><\/p>\n<h4 id=\"pro-tip-leverage-opensearch-pipelines\">Pro Tip: Leverage OpenSearch Pipelines<\/h4>\n<p>Trying to implement this is quite a challenge especially considering the fact that we have two different stages the online and offline stage. Its very easy to mess things up and introduce what is known as <em>training-serving skew<\/em> where there are differences between the offline and online section of Machine Learning systems. In this scenario we would have to ensure that the embedding model that we use for the offline and online system are exactly the same and more importantly use the exact same parameters such as the:<\/p>\n<ul>\n  <li><em>maximum sequence length<\/em><\/li>\n  <li><em>text processing parameters<\/em><\/li>\n  <li>etc.<\/li>\n<\/ul>\n\n<p>OpenSearch has this neat functionality where you can <a href=\"https:\/\/opensearch.org\/docs\/latest\/ml-commons-plugin\/pretrained-models\/\">deploy Machine Learning Models<\/a> within the same OpenSearch cluster and leverage <a href=\"https:\/\/opensearch.org\/docs\/latest\/ingest-pipelines\/\">ingest pipelines<\/a> in order to setup a pipeline that can be used for converting documents during ingestion time(offline) and the query(online) into embeddings for you to process:<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"err\">PUT<\/span><span class=\"w\"> <\/span><span class=\"err\">\/_ingest\/pipeline\/nlp-ingest-pipeline<\/span><span class=\"w\">\n<\/span><span class=\"p\">{<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"description\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"A text embedding pipeline\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"processors\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">[<\/span><span class=\"w\">\n    <\/span><span class=\"p\">{<\/span><span class=\"w\">\n      <\/span><span class=\"nl\">\"text_embedding\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n        <\/span><span class=\"nl\">\"model_id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"bQ1J8ooBpBj3wT4HVUsb\"<\/span><span class=\"p\">,<\/span><span class=\"w\"> <\/span><span class=\"err\">#<\/span><span class=\"w\"> <\/span><span class=\"err\">MODEL_ID<\/span><span class=\"w\"> \n        <\/span><span class=\"nl\">\"field_map\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n          <\/span><span class=\"nl\">\"passage_text\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"passage_embedding\"<\/span><span class=\"w\">\n        <\/span><span class=\"p\">}<\/span><span class=\"w\">\n      <\/span><span class=\"p\">}<\/span><span class=\"w\">\n    <\/span><span class=\"p\">}<\/span><span class=\"w\">\n  <\/span><span class=\"p\">]<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<p>In the k-NN index you would then set the pipeline to use via the <code class=\"language-plaintext highlighter-rouge\">default-pipeline<\/code> to use parameter:<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"err\">PUT<\/span><span class=\"w\"> <\/span><span class=\"err\">\/my-nlp-index<\/span><span class=\"w\">\n<\/span><span class=\"p\">{<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"settings\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"index.knn\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"kc\">true<\/span><span class=\"p\">,<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"default_pipeline\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"nlp-ingest-pipeline\"<\/span><span class=\"w\"> <\/span><span class=\"err\">#<\/span><span class=\"w\"> <\/span><span class=\"err\">HERE<\/span><span class=\"w\">\n  <\/span><span class=\"p\">},<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"mappings\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n    <\/span><span class=\"nl\">\"properties\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n      <\/span><span class=\"nl\">\"id\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n        <\/span><span class=\"nl\">\"type\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"text\"<\/span><span class=\"w\">\n      <\/span><span class=\"p\">},<\/span><span class=\"w\">\n      <\/span><span class=\"nl\">\"passage_embedding\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n        <\/span><span class=\"nl\">\"type\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"knn_vector\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n        <\/span><span class=\"nl\">\"dimension\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">768<\/span><span class=\"p\">,<\/span><span class=\"w\">\n        <\/span><span class=\"nl\">\"method\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n          <\/span><span class=\"nl\">\"engine\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"lucene\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n          <\/span><span class=\"nl\">\"space_type\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"l2\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n          <\/span><span class=\"nl\">\"name\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"hnsw\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n          <\/span><span class=\"nl\">\"parameters\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{}<\/span><span class=\"w\">\n        <\/span><span class=\"p\">}<\/span><span class=\"w\">\n      <\/span><span class=\"p\">},<\/span><span class=\"w\">\n      <\/span><span class=\"nl\">\"passage_text\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"p\">{<\/span><span class=\"w\">\n        <\/span><span class=\"nl\">\"type\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"text\"<\/span><span class=\"w\">\n      <\/span><span class=\"p\">}<\/span><span class=\"w\">\n    <\/span><span class=\"p\">}<\/span><span class=\"w\">\n  <\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<p>By leveraging OpenSearch pipelines we do not have to perform the steps that are highlighted in green, which simplifies the overall process.<\/p>\n\n<p><img src=\"https:\/\/yudhiesh.github.io\/images\/Screenshot 2024-12-27 at 23.33.04.png\" alt=\"Image\" \/><\/p>\n\n<p>Be warned this ease does come with some downsides:<\/p>\n<ul>\n  <li><em>colocation of Machine Learning workflows with Search workflows on the same nodes<\/em>, especially when using the managed offering for OpenSearch on AWS you do not have the ability to specify that the Machine Learning models deployed on the OpenSearch cluster are deployed on specific nodes just for Machine Learning models, this however can be done if you self-host OpenSearch and specify a node\u2019s role via the <a href=\"https:\/\/opensearch.org\/docs\/latest\/ml-commons-plugin\/cluster-settings\/\">ML Commons cluster settings<\/a>.<\/li>\n  <li><em>less flexibility in Machine Learning model deployment frameworks<\/em>, as OpenSearch ML Commons uses <a href=\"https:\/\/djl.ai\/\">Deep Java Library<\/a>to deploy ML models I would prefer to use my current stack which has been battle-tested and supports Monitoring &amp; Observability out-of-the box.<\/li>\n  <li><em>limited support for custom remote ML model endpoints<\/em>, this is true if you are using the Managed OpenSearch offering where although it might seem like it supports a lot of different options as per the <a href=\"https:\/\/github.com\/opensearch-project\/ml-commons\/tree\/main\/docs\/remote_inference_blueprints\">docs<\/a>, on the contrary it only works with publicly exposed API Endpoint due to the fact that a managed service on AWS is deployed within AWS\u2019s own private account with VPC access from a customers AWS account to said AWS account but not the other way around due to the <a href=\"https:\/\/docs.aws.amazon.com\/whitepapers\/latest\/building-scalable-secure-multi-vpc-network-infrastructure\/aws-privatelink.html\">unidirectional nature of AWS PrivateLink<\/a>.<\/li>\n<\/ul>\n\n<h2 id=\"feature-flags-to-the-rescue\">Feature Flags to the Rescue!<\/h2>\n\n<p>Okay I have been rambling on about Semantic Search a lot and you must be wondering <em>\u201cGeez Yudhiesh get to your point already!\u201d<\/em>, now the biggest issue with all of this was that I had to do all of these steps into a codebase that I was:<\/p>\n<ul>\n  <li>completely new to in terms of contributing<\/li>\n  <li>it was in Java which I have not touched since university and never had much fun coding in<\/li>\n<\/ul>\n\n<p>Plus I had to do it <em>quick<\/em> and with <em>zero impact on the current search experience<\/em> which was being A\/B tested by Data Scientists that were monitoring key metrics such as Click-through Rate(CTR).<\/p>\n\n<h3 id=\"what-are-feature-flags\">What are Feature Flags?<\/h3>\n\n<p>Now going back to our problem statement, a very simple thing to do would be to ensure that only I could interact with said feature. In doing so we would be able to solve said issues due to the fact that if I am the only person interacting with the feature:<\/p>\n<ul>\n  <li>impact is centered around my own experience instead of end users.<\/li>\n  <li>we can relaxen our requirements to push the feature out, perhaps we don\u2019t have to push for 100% test coverage, etc. and instead can trial out the feature to prove it solves the problem in the first place prior to investing more time and effort into it<\/li>\n<\/ul>\n\n<p>Our Search API would take in as the minimum the following payload:<\/p>\n<div class=\"language-json highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"p\">{<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"query\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"s2\">\"Food\"<\/span><span class=\"p\">,<\/span><span class=\"w\">\n  <\/span><span class=\"nl\">\"userId\"<\/span><span class=\"p\">:<\/span><span class=\"w\"> <\/span><span class=\"mi\">123456789<\/span><span class=\"w\">\n<\/span><span class=\"p\">}<\/span><span class=\"w\">\n<\/span><\/code><\/pre><\/div><\/div>\n<p>Now since we had a good culture of <a href=\"https:\/\/en.wikipedia.org\/wiki\/Eating_your_own_dog_food\">dog fooding<\/a>, I already had my own account for our mobile app.<\/p>\n<blockquote>\n  <p>Side note, if you work at an organization and don\u2019t even use the product offered, how can you even improve it in any way?<\/p>\n<\/blockquote>\n\n<p>In my code based on this, I could do something like this where I expose the feature out to my <code class=\"language-plaintext highlighter-rouge\">userId<\/code> exclusively<\/p>\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kd\">public<\/span> <span class=\"kd\">class<\/span> <span class=\"nc\">SearchService<\/span> <span class=\"o\">{<\/span>\n    <span class=\"kd\">private<\/span> <span class=\"kd\">static<\/span> <span class=\"kd\">final<\/span> <span class=\"kt\">long<\/span> <span class=\"no\">MY_USER_ID<\/span> <span class=\"o\">=<\/span> <span class=\"mi\">123456789<\/span><span class=\"o\">;<\/span>\n    \n    <span class=\"kd\">public<\/span> <span class=\"nc\">SearchResponse<\/span> <span class=\"nf\">search<\/span><span class=\"o\">(<\/span><span class=\"nc\">SearchRequest<\/span> <span class=\"n\">request<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n        <span class=\"k\">if<\/span> <span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">.<\/span><span class=\"na\">getUserId<\/span><span class=\"o\">()<\/span> <span class=\"o\">==<\/span> <span class=\"no\">MY_USER_ID<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n            <span class=\"k\">return<\/span> <span class=\"nf\">semanticSearch<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">);<\/span>\n        <span class=\"o\">}<\/span>\n        <span class=\"k\">return<\/span> <span class=\"nf\">standardSearch<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">);<\/span>\n    <span class=\"o\">}<\/span>\n    \n    <span class=\"kd\">private<\/span> <span class=\"nc\">SearchResponse<\/span> <span class=\"nf\">semanticSearch<\/span><span class=\"o\">(<\/span><span class=\"nc\">SearchRequest<\/span> <span class=\"n\">request<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n        <span class=\"c1\">\/\/ New semantic search implementation<\/span>\n        <span class=\"k\">return<\/span> <span class=\"nc\">SearchResponse<\/span><span class=\"o\">.<\/span><span class=\"na\">builder<\/span><span class=\"o\">()<\/span>\n                <span class=\"o\">.<\/span><span class=\"na\">results<\/span><span class=\"o\">(<\/span><span class=\"n\">semanticSearchEngine<\/span><span class=\"o\">.<\/span><span class=\"na\">search<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">.<\/span><span class=\"na\">getQuery<\/span><span class=\"o\">()))<\/span>\n                <span class=\"o\">.<\/span><span class=\"na\">build<\/span><span class=\"o\">();<\/span>\n    <span class=\"o\">}<\/span>\n    \n    <span class=\"kd\">private<\/span> <span class=\"nc\">SearchResponse<\/span> <span class=\"nf\">standardSearch<\/span><span class=\"o\">(<\/span><span class=\"nc\">SearchRequest<\/span> <span class=\"n\">request<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n        <span class=\"c1\">\/\/ Existing search implementation<\/span>\n        <span class=\"k\">return<\/span> <span class=\"nc\">SearchResponse<\/span><span class=\"o\">.<\/span><span class=\"na\">builder<\/span><span class=\"o\">()<\/span>\n                <span class=\"o\">.<\/span><span class=\"na\">results<\/span><span class=\"o\">(<\/span><span class=\"n\">searchEngine<\/span><span class=\"o\">.<\/span><span class=\"na\">search<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">.<\/span><span class=\"na\">getQuery<\/span><span class=\"o\">()))<\/span>\n                <span class=\"o\">.<\/span><span class=\"na\">build<\/span><span class=\"o\">();<\/span>\n    <span class=\"o\">}<\/span>\n<span class=\"o\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n<blockquote>\n  <p>In reality there was a separate service to translate a <code class=\"language-plaintext highlighter-rouge\">user's id -&gt; user's email<\/code> instead of trying to manually figure this out.<\/p>\n<\/blockquote>\n\n<p>Essentially what we have done here is setup a very basic feature flag for our application!<\/p>\n\n<blockquote>\n  <p>Feature flags are a software development concept that allow you to enable or disable a feature without modifying the source code or requiring a redeploy.<\/p>\n<\/blockquote>\n\n<p>But how would we handle the following situations:<\/p>\n<ul>\n  <li>adding in more user\u2019s to the target pool to be shown semantic search results?<\/li>\n<\/ul>\n\n<p>With the current implementation we would not adhere to the definition of a feature flag and instead would be require a redeployment of the application each time we had to alter the target users to expose this feature flag to.<\/p>\n\n<h3 id=\"feature-flag-platforms\">Feature Flag Platforms<\/h3>\n\n<p>With the aforementioned limitation, a feature flag management platform comes in to solve the problem. These platforms allow you to wrap all your feature flags behind an API that you interact with and more importantly allow you to make changes to them quickly via a simple UI.<\/p>\n\n<p>Here are some example platforms:<\/p>\n<ul>\n  <li><a href=\"https:\/\/launchdarkly.com\/\">LaunchDarkly<\/a><\/li>\n  <li><a href=\"https:\/\/www.split.io\/\">Split.io<\/a><\/li>\n<\/ul>\n\n<p><img src=\"https:\/\/www.split.io\/wp-content\/uploads\/Homepage-Release.png\" alt=\"Feature Flag Management Platform\" \/><\/p>\n\n<p>These platforms enable sophisticated flag management:<\/p>\n\n<ol>\n  <li><strong>Targeting Control<\/strong>\n    <ul>\n      <li>Individual user targeting by ID, email, or custom attributes<\/li>\n      <li>Bulk user targeting via CSV uploads<\/li>\n      <li>Percentage-based rollouts<\/li>\n      <li>Geographic targeting<\/li>\n      <li>Device\/platform specific releases<\/li>\n    <\/ul>\n  <\/li>\n  <li><strong>Advanced Features<\/strong>\n    <ul>\n      <li>Real-time flag updates without code deployments<\/li>\n      <li>Detailed audit logs for flag changes<\/li>\n      <li>A\/B testing and experimentation tools<\/li>\n      <li>Flag dependencies and prerequisites<\/li>\n      <li>SDKs for multiple programming languages<\/li>\n    <\/ul>\n  <\/li>\n<\/ol>\n\n<h3 id=\"integrating-feature-flag-platforms-into-our-ml-system\">Integrating Feature Flag Platforms into our ML System<\/h3>\n<p>This integration needed to happen in two phases.<\/p>\n\n<h4 id=\"phase-1-data-ingestion\">Phase 1: Data Ingestion<\/h4>\n<p>First, we needed to ensure documents were being indexed into OpenSearch alongside our existing search engine. In our setup we had a Kafka topic that we listened to for new documents to be ingested which had to write new data to the OpenSearch index with the k-NN index setup. I also had to reindex the new k-NN index with data from the original index used for lexical search but this code has been excluded. This required:<\/p>\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"nd\">@Service<\/span>\n<span class=\"nd\">@Slf4j<\/span>\n<span class=\"kd\">public<\/span> <span class=\"kd\">class<\/span> <span class=\"nc\">DocumentIngestionService<\/span> <span class=\"o\">{<\/span>\n    <span class=\"kd\">private<\/span> <span class=\"kd\">final<\/span> <span class=\"nc\">LaunchDarkly<\/span> <span class=\"n\">ldClient<\/span><span class=\"o\">;<\/span>\n    <span class=\"kd\">private<\/span> <span class=\"kd\">final<\/span> <span class=\"nc\">OpenSearchClient<\/span> <span class=\"n\">openSearchClient<\/span><span class=\"o\">;<\/span>\n    <span class=\"kd\">private<\/span> <span class=\"kd\">static<\/span> <span class=\"kd\">final<\/span> <span class=\"nc\">String<\/span> <span class=\"no\">OPENSEARCH_INGESTION_FLAG<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"enable-opensearch-ingestion\"<\/span><span class=\"o\">;<\/span>\n    \n    <span class=\"nd\">@KafkaListener<\/span><span class=\"o\">(<\/span><span class=\"n\">topics<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"documents-topic\"<\/span><span class=\"o\">)<\/span>\n    <span class=\"kd\">public<\/span> <span class=\"kt\">void<\/span> <span class=\"nf\">processDocument<\/span><span class=\"o\">(<\/span><span class=\"nc\">ConsumerRecord<\/span><span class=\"o\">&lt;<\/span><span class=\"nc\">String<\/span><span class=\"o\">,<\/span> <span class=\"nc\">Document<\/span><span class=\"o\">&gt;<\/span> <span class=\"n\">record<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n        <span class=\"nc\">LDUser<\/span> <span class=\"n\">systemUser<\/span> <span class=\"o\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nc\">LDUser<\/span><span class=\"o\">.<\/span><span class=\"na\">Builder<\/span><span class=\"o\">(<\/span><span class=\"s\">\"system\"<\/span><span class=\"o\">)<\/span>\n                <span class=\"o\">.<\/span><span class=\"na\">custom<\/span><span class=\"o\">(<\/span><span class=\"s\">\"environment\"<\/span><span class=\"o\">,<\/span> <span class=\"n\">getEnvironment<\/span><span class=\"o\">())<\/span>\n                <span class=\"o\">.<\/span><span class=\"na\">build<\/span><span class=\"o\">();<\/span>\n                \n        <span class=\"kt\">boolean<\/span> <span class=\"n\">enableOpenSearchIngestion<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ldClient<\/span><span class=\"o\">.<\/span><span class=\"na\">boolVariation<\/span><span class=\"o\">(<\/span>\n            <span class=\"no\">OPENSEARCH_INGESTION_FLAG<\/span><span class=\"o\">,<\/span>\n            <span class=\"n\">systemUser<\/span><span class=\"o\">,<\/span>\n            <span class=\"kc\">false<\/span>\n        <span class=\"o\">);<\/span>\n        \n        <span class=\"k\">if<\/span> <span class=\"o\">(<\/span><span class=\"n\">enableOpenSearchIngestion<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n            <span class=\"k\">try<\/span> <span class=\"o\">{<\/span>\n                <span class=\"nc\">IndexRequest<\/span><span class=\"o\">&lt;<\/span><span class=\"nc\">Document<\/span><span class=\"o\">&gt;<\/span> <span class=\"n\">request<\/span> <span class=\"o\">=<\/span> <span class=\"nc\">IndexRequest<\/span><span class=\"o\">.<\/span><span class=\"na\">of<\/span><span class=\"o\">(<\/span><span class=\"n\">r<\/span> <span class=\"o\">-&gt;<\/span> <span class=\"n\">r<\/span>\n                    <span class=\"o\">.<\/span><span class=\"na\">index<\/span><span class=\"o\">(<\/span><span class=\"s\">\"documents\"<\/span><span class=\"o\">)<\/span>\n                    <span class=\"o\">.<\/span><span class=\"na\">id<\/span><span class=\"o\">(<\/span><span class=\"n\">record<\/span><span class=\"o\">.<\/span><span class=\"na\">key<\/span><span class=\"o\">())<\/span>\n                    <span class=\"o\">.<\/span><span class=\"na\">document<\/span><span class=\"o\">(<\/span><span class=\"n\">record<\/span><span class=\"o\">.<\/span><span class=\"na\">value<\/span><span class=\"o\">())<\/span>\n                <span class=\"o\">);<\/span>\n                <span class=\"n\">openSearchClient<\/span><span class=\"o\">.<\/span><span class=\"na\">index<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">);<\/span>\n                <span class=\"n\">log<\/span><span class=\"o\">.<\/span><span class=\"na\">info<\/span><span class=\"o\">(<\/span><span class=\"s\">\"Document indexed in OpenSearch: {}\"<\/span><span class=\"o\">,<\/span> <span class=\"n\">record<\/span><span class=\"o\">.<\/span><span class=\"na\">key<\/span><span class=\"o\">());<\/span>\n            <span class=\"o\">}<\/span> <span class=\"k\">catch<\/span> <span class=\"o\">(<\/span><span class=\"nc\">Exception<\/span> <span class=\"n\">e<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n                <span class=\"n\">log<\/span><span class=\"o\">.<\/span><span class=\"na\">error<\/span><span class=\"o\">(<\/span><span class=\"s\">\"Failed to index document in OpenSearch: {}\"<\/span><span class=\"o\">,<\/span> <span class=\"n\">record<\/span><span class=\"o\">.<\/span><span class=\"na\">key<\/span><span class=\"o\">(),<\/span> <span class=\"n\">e<\/span><span class=\"o\">);<\/span>\n            <span class=\"o\">}<\/span>\n        <span class=\"o\">}<\/span>\n        \n        <span class=\"c1\">\/\/ Continue with existing processing<\/span>\n        <span class=\"n\">processExistingSystem<\/span><span class=\"o\">(<\/span><span class=\"n\">record<\/span><span class=\"o\">);<\/span>\n    <span class=\"o\">}<\/span>\n<span class=\"o\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n\n<h4 id=\"phase-2-search-implementation\">Phase 2: Search Implementation<\/h4>\n<p>Only after confirming successful data ingestion did we enable the semantic search feature.<\/p>\n<div class=\"language-java highlighter-rouge\"><div class=\"highlight\"><pre class=\"highlight\"><code><span class=\"kd\">public<\/span> <span class=\"kd\">class<\/span> <span class=\"nc\">SearchService<\/span> <span class=\"o\">{<\/span>\n   <span class=\"kd\">private<\/span> <span class=\"kd\">final<\/span> <span class=\"nc\">LaunchDarkly<\/span> <span class=\"n\">ldClient<\/span><span class=\"o\">;<\/span>\n   <span class=\"kd\">private<\/span> <span class=\"kd\">static<\/span> <span class=\"kd\">final<\/span> <span class=\"nc\">String<\/span> <span class=\"no\">SEMANTIC_SEARCH_FLAG<\/span> <span class=\"o\">=<\/span> <span class=\"s\">\"semantic-search-enabled\"<\/span><span class=\"o\">;<\/span>\n   \n   <span class=\"kd\">public<\/span> <span class=\"nf\">SearchService<\/span><span class=\"o\">(<\/span><span class=\"nc\">LaunchDarkly<\/span> <span class=\"n\">ldClient<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n       <span class=\"k\">this<\/span><span class=\"o\">.<\/span><span class=\"na\">ldClient<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ldClient<\/span><span class=\"o\">;<\/span>\n   <span class=\"o\">}<\/span>\n   \n   <span class=\"kd\">public<\/span> <span class=\"nc\">SearchResponse<\/span> <span class=\"nf\">search<\/span><span class=\"o\">(<\/span><span class=\"nc\">SearchRequest<\/span> <span class=\"n\">request<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n       <span class=\"nc\">LDUser<\/span> <span class=\"n\">user<\/span> <span class=\"o\">=<\/span> <span class=\"k\">new<\/span> <span class=\"nc\">LDUser<\/span><span class=\"o\">.<\/span><span class=\"na\">Builder<\/span><span class=\"o\">(<\/span><span class=\"nc\">String<\/span><span class=\"o\">.<\/span><span class=\"na\">valueOf<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">.<\/span><span class=\"na\">getUserId<\/span><span class=\"o\">()))<\/span>\n               <span class=\"o\">.<\/span><span class=\"na\">build<\/span><span class=\"o\">();<\/span>\n               \n       <span class=\"kt\">boolean<\/span> <span class=\"n\">semanticSearchEnabled<\/span> <span class=\"o\">=<\/span> <span class=\"n\">ldClient<\/span><span class=\"o\">.<\/span><span class=\"na\">boolVariation<\/span><span class=\"o\">(<\/span>\n           <span class=\"no\">SEMANTIC_SEARCH_FLAG<\/span><span class=\"o\">,<\/span> \n           <span class=\"n\">user<\/span><span class=\"o\">,<\/span> \n           <span class=\"kc\">false<\/span>  <span class=\"c1\">\/\/ fallback value if flag evaluation fails<\/span>\n       <span class=\"o\">);<\/span>\n       \n       <span class=\"k\">if<\/span> <span class=\"o\">(<\/span><span class=\"n\">semanticSearchEnabled<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n           <span class=\"k\">return<\/span> <span class=\"nf\">semanticSearch<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">);<\/span>\n       <span class=\"o\">}<\/span>\n       <span class=\"k\">return<\/span> <span class=\"nf\">standardSearch<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">);<\/span>\n   <span class=\"o\">}<\/span>\n   \n   <span class=\"kd\">private<\/span> <span class=\"nc\">SearchResponse<\/span> <span class=\"nf\">semanticSearch<\/span><span class=\"o\">(<\/span><span class=\"nc\">SearchRequest<\/span> <span class=\"n\">request<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n       <span class=\"k\">return<\/span> <span class=\"nc\">SearchResponse<\/span><span class=\"o\">.<\/span><span class=\"na\">builder<\/span><span class=\"o\">()<\/span>\n               <span class=\"o\">.<\/span><span class=\"na\">results<\/span><span class=\"o\">(<\/span><span class=\"n\">semanticSearchEngine<\/span><span class=\"o\">.<\/span><span class=\"na\">search<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">.<\/span><span class=\"na\">getQuery<\/span><span class=\"o\">()))<\/span>\n               <span class=\"o\">.<\/span><span class=\"na\">build<\/span><span class=\"o\">();<\/span>\n   <span class=\"o\">}<\/span>\n   \n   <span class=\"kd\">private<\/span> <span class=\"nc\">SearchResponse<\/span> <span class=\"nf\">standardSearch<\/span><span class=\"o\">(<\/span><span class=\"nc\">SearchRequest<\/span> <span class=\"n\">request<\/span><span class=\"o\">)<\/span> <span class=\"o\">{<\/span>\n       <span class=\"k\">return<\/span> <span class=\"nc\">SearchResponse<\/span><span class=\"o\">.<\/span><span class=\"na\">builder<\/span><span class=\"o\">()<\/span>\n               <span class=\"o\">.<\/span><span class=\"na\">results<\/span><span class=\"o\">(<\/span><span class=\"n\">searchEngine<\/span><span class=\"o\">.<\/span><span class=\"na\">search<\/span><span class=\"o\">(<\/span><span class=\"n\">request<\/span><span class=\"o\">.<\/span><span class=\"na\">getQuery<\/span><span class=\"o\">()))<\/span>\n               <span class=\"o\">.<\/span><span class=\"na\">build<\/span><span class=\"o\">();<\/span>\n   <span class=\"o\">}<\/span>\n<span class=\"o\">}<\/span>\n<\/code><\/pre><\/div><\/div>\n<p>Now with that I was able to safely and quickly deploy a very experimental feature out and test it in Production with <em>zero<\/em> impact to end users, isn\u2019t that neat.<\/p>\n\n<h2 id=\"references\">References<\/h2>\n<ul>\n  <li><a href=\"https:\/\/eugeneyan.com\/writing\/system-design-for-discovery\/\">System Design for Recommendations and Search<\/a><\/li>\n  <li><a href=\"https:\/\/opensearch.org\/blog\/semantic-search-solutions\/\">Building a semantic search engine in OpenSearch<\/a><\/li>\n  <li><a href=\"https:\/\/martinfowler.com\/articles\/feature-toggles.html\">Feature Toggles<\/a><\/li>\n<\/ul>\n\n\n<p><a href=\"https:\/\/yudhiesh.github.io\/2024\/12\/27\/feature-flag-driven-development-in-ml\/\">Read this post on Bits &amp; Backprops<\/a> for the full layout and any interactive views.<\/p>"}]}