<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mikhail Korotkov on Medium]]></title>
        <description><![CDATA[Stories by Mikhail Korotkov on Medium]]></description>
        <link>https://medium.com/@ma-korotkov?source=rss-c98d7807594f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*66FoYJnFy19kRxM8NvRUZg.jpeg</url>
            <title>Stories by Mikhail Korotkov on Medium</title>
            <link>https://medium.com/@ma-korotkov?source=rss-c98d7807594f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 00:20:33 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ma-korotkov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Handling multimodality in Vector Search]]></title>
            <link>https://medium.com/@ma-korotkov/handling-multimodality-in-vector-search-9be46a6fec05?source=rss-c98d7807594f------2</link>
            <guid isPermaLink="false">https://medium.com/p/9be46a6fec05</guid>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <dc:creator><![CDATA[Mikhail Korotkov]]></dc:creator>
            <pubDate>Wed, 09 Jul 2025 07:42:37 GMT</pubDate>
            <atom:updated>2025-07-09T07:42:37.079Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kKBsSmwTUORhrkTigA5Elw.png" /><figcaption>Synthetic object embedding pipeline</figcaption></figure><h3>The introduction</h3><p>Vector search is a technique for finding and retrieving similar items in large data-sets by comparing their <strong>vector representations</strong>.<br>Unlike traditional search, which relies on exact matches, vector search looks for similarity in meaning or context. It already powers image retrieval, recommendation systems and modern search engines. With the rise of RAG applications and AI agents the ability to search effectively across complex objects is becoming critical.</p><p>But the more complex your items, the more sophisticated the search pipeline. Below we explore several approaches for building robust pipelines around <strong>multimodal</strong> items.</p><h3>Vector search pipeline in one minute</h3><p>If you want get a better understanding of the Vector Search concept in general, you can take a look at the introductory article about the Vector Search <a href="https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907">here</a>:</p><p>Basically, it consists of three steps:</p><ul><li><strong>Encode</strong> — turn each item into one or more vectors and store them in a vector DB</li><li><strong>Retrieve</strong> — run a version of KNN search to get top <em>K</em> most relevant items</li><li><strong>Post-process</strong> — re-score, re-rank, feed results into a RAG chain, etc.</li></ul><p>The third stage varies with the application, while steps 1–2 look similar for most workloads — until your items become truly complex and multimodal.</p><h3>Why multimodal items need special treatment</h3><p>Real-world objects rarely fit into one tidy column.<br>Take a <strong>YouTube channel</strong>:</p><ul><li><strong>visual</strong> — videos, account avatar</li><li><strong>text</strong> — titles, descriptions, subtitles, even Wikipedia pages about the influencer</li><li><strong>structured</strong> — subscriber count, growth %, language, etc.</li></ul><p>Retrieving such entities is a <strong>fusion</strong> problem: we must decide how to combine several signals so that nearest neighbours <strong>feel similar</strong> to the query. No single recipe wins everywhere, the best choice depends on your data and user needs. Below are the five most common fusion strategies, with pros, cons and best-fit scenarios.</p><h3>Fusion recipes</h3><h4>Early Fusion — one big vector</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfNuwY6Te3C2k5FZ3NmAiQ.png" /><figcaption>Early Fusion pipeline</figcaption></figure><p>Concatenate or mean-pool every modality embedding, store <strong>one</strong> dense vector per item, run a single ANN search.</p><p><strong>Pros</strong></p><ul><li>Easy to implement</li><li>Fast embedding creation: minimal additional logic + you can encode each modality independently</li><li>Fast search: one search per query</li><li>Easy to store and search: one vector per item + no weighting logic</li></ul><p><strong>Cons</strong></p><ul><li>Mean-pooling multiple unrelated signals lead to less informative embeddings</li><li>Concatenating embeddings leads to dimensionality exploding in case of many modalities</li><li>No weighting logic</li><li>You can only use same multimodal encoders if you want to apply mean pooling</li><li><a href="https://openreview.net/forum?id=S7Evzt9uit3">Modality Gap</a> problem (most of the CLIP-like models have different similarity scores distribution for different modalities which makes any model aggregating embeddings of different modalities less robust)</li></ul><p><strong>Good for</strong> quick MVPs where signals are of similar strength.<br><strong>Poor for</strong> rich metadata or when different user intents require re-weighting on the fly. For example, Youtube creators could have dozens of videos with hundreds of images frames per video, subtitles, bio captions even Wikipedia page about them. Mean pooling the embeddings Wikipedia article embeddings with a frame of a specific video will certainly give you a headache.</p><h4>Late Fusion — score-level blending</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6R4Vg_7nmmGo5h4DqpP2Hg.png" /><figcaption>Late Fusion Pipeline</figcaption></figure><p>As mixing different modalities in a single vector leads to problems, then why not to store multiple vectors per item? For example, any Youtube video could be represented as a pair of visual embedding and textual embedding, like here (Qdrant multiple embeddings per item example):</p><pre>from qdrant_client import QdrantClient<br>from qdrant_client.http.models import VectorParams, Distance<br><br>client = QdrantClient()<br>client.create_collection(<br>   collection_name=&quot;youtube_videos&quot;,<br>   vectors_config={<br>       &quot;text&quot;: VectorParams(<br>           size=1024,<br>           distance=Distance.COSINE,<br>       ),<br>       &quot;image&quot;: VectorParams(<br>           size=1024,<br>           distance=Distance.COSINE,<br>       ),<br>   }<br>)</pre><p>In this case you can apply separate searches for the most relevant candidates by text and visual embeddings separately and then apply weighting function for your results:</p><p><em>final_score = α ⋅ image_score​ + β ⋅ text_score</em></p><p>You can even go further and use <a href="https://weaviate.io/blog/hybrid-search-fusion-algorithms">hybrid search</a> for your textual queries combining dense and sparse textual embeddings.</p><p><strong>Pros</strong></p><ul><li>Easy to implement</li><li>Fast embedding creation: almost no additional logic + you can encode each modality independently</li><li>Per-query control of weights</li><li>Independent ANN parameters per modality</li><li>Easy to add/remove a modality later</li><li>No Modality Gap</li><li>You could change weighting logic on the fly without changing the pipeline</li></ul><p><strong>Cons</strong></p><ul><li>Custom weighting logic is hard to optimise</li><li>Storage: Multiple embeddings per item</li><li>Speed: Multiple searches per query</li><li>One embedding per modality could still not be enough (mean pooling subtitle embeddings of different videos could lead to quality issues)</li></ul><p><strong>Good for</strong> cases when different modalities are strongly independent but each modality is easy to encode. Or if user can directly choose which component is more important in his case (choose search by photo, search by text, etc.)<br><strong>Poor for</strong> cases where a joint representation is more rich than a separate ones (for example, a book illustration could help to better understand the place described in text, or an image caption could provide additional details about the persons on the photo)</p><h4>Superlinked Unified Vector — avoiding reranking step</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WuC7iekYnq76Kb_BL5uKcg.png" /><figcaption>Superlined-based unified embeddings pipeline</figcaption></figure><p>While late reranking could be useful in some cases, it is still an additional step making your pipeline more complex. <a href="https://superlinked.com/vectorhub/articles/why-do-not-need-re-ranking">Superlinked</a> encodes each signal in its own space, handles scaling (log for counts, one-hot for categories), then <strong>concatenates &amp; normalises</strong> into a single vector, so you don’t need late fusion or manual re-ranking.<br>(Here is a simple example of Superlinked combining textual and numerical information in a single vector)</p><pre>import pandas as pd<br>from superlinked import framework as sl<br><br><br>class Image(sl.Schema):<br>    id: sl.IdField<br>    image: sl.Blob<br>    description: sl.String<br><br><br>image = Image()<br><br># Image space utilizes the specified Vision Transformer model to encode image (and text)<br>image_embedding_space = sl.ImageSpace(image=image.image, model=VIT_MODEL_ID, model_handler=sl.ModelHandler.OPEN_CLIP)<br># Embed descriptions using a text embedding model<br>description_space = sl.TextSimilaritySpace(text=image.description, model=&quot;Alibaba-NLP/gte-large-en-v1.5&quot;)<br><br># construct an index<br>composite_index = sl.Index([image_embedding_space, description_space])<br><br>source: sl.InMemorySource = sl.InMemorySource(image)<br>executor = sl.InMemoryExecutor(sources=[source], indices=[composite_index])<br>app = executor.run()<br><br>source.put(json_data)  # json_data is the data with 3 fields, id, image and description<br><br>combined_query = (<br>    sl.Query(<br>        composite_index,<br>        weights={<br>            description_space: sl.Param(&quot;description_weight&quot;),<br>            image_embedding_space: sl.Param(&quot;image_embedding_weight&quot;),<br>        },<br>    )<br>    .find(image)<br>    .similar(description_space, sl.Param(&quot;text_search&quot;))<br>    .similar(image_embedding_space.image, sl.Param(&quot;image_search&quot;))<br>    .similar(image_embedding_space.description, sl.Param(&quot;text_in_image_search&quot;))<br>    .select_all()<br>    .limit(LIMIT)<br>)<br><br>result_text = app.query(<br>    combined_query,<br>    description_weight=1,<br>    text_search=TEXT_TO_SEARCH_WITH,<br>)</pre><p><strong>Pros</strong></p><ul><li>Supports any field types</li><li>Numeric / categorical weights calibrated automatically</li><li>Easy to implement and to search: single vector representation</li><li>Quality is better than simple concatenation</li><li>No custom reranking step needed</li></ul><p><strong>Cons</strong></p><ul><li>Still has pros and cons of the concatenation approach: if your object is very complex it will be tricky to achieve great search quality</li><li>Another dependency in the stack</li></ul><p><strong>Good for</strong> datasets with <em>dozens</em> of structured fields (engagement, geo buckets, tags) plus text &amp; images, especially if you want clear structured, easy to use code.<br><strong>Poor for</strong> complex data objects</p><h4>Joint Multimodal Embedding — train your own embedding model</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gzCwZ3OMXPs1eylbQ-btug.png" /><figcaption>Custom trained embeddings pipeline</figcaption></figure><p>The next idea is to train your own embeddings specifically for your task. You can still use pretrained embeddings as encoders for certain modalities, but train additional model head on top of them aggregating this separate embeddings into a single vector using Contrastive Loss. Potentially it would be the most powerful approach, because you will have the power to optimise the your vector representation for the requests specific for your system.</p><p><strong>Pros</strong></p><ul><li>Potentially utilising cross-modalities information</li><li>Fast and easy search: one vector per item + no reranking logic</li><li>You can implement the model architecture that suites your data</li></ul><p><strong>Cons</strong></p><ul><li>Data and model training: usually, it is difficult to collect enough triplets for training the Metric Learning model of the high quality.</li><li>You need ML Engineers to train the proper model</li><li>You can’t calculate the embeddings independently as you will need to run a separate model head to create the final vector representation</li><li>Still not ideal for numeric / categorical data</li><li>Couldn’t apply any pretrained reranking models</li></ul><p><strong>Good for</strong> cases when you naturally have millions of good triplets for training and the resources to do it<br><strong>Poor for</strong> cases when you don’t have such type of data triplets naturally</p><h4>LLM-Generated search object</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lADP-OE2deCAPe0Q8TnzVQ.png" /><figcaption>Synthetic object embeddings pipeline</figcaption></figure><p>But what if your data still too complex, but you have not data or resources to train your own embeddings? You can create your own search object using some multimodal LLM, like Mistral AI pixtral-large-latest, Open AI models or any other LLM model with visual capabilities. For example, you can create a Youtube channel/creator biography by combining all data modalities together in a single context. It takes almost no time to add additional data to the context and it is very easy to manipulate the output structure of the LLM response. Also, if you will need you can finetune the model to create summaries following specific structure and of specific length. Then you can encode this summary instead of the original data. Models like <a href="https://jina.ai/news/jina-embeddings-v4-universal-embeddings-for-multimodal-multilingual-retrieval"><strong>jina-embeddings-v4</strong></a><strong> </strong>supports 32k context window which makes it possible to convert quite a long summary into single embedding.</p><p><strong>Pros</strong></p><ul><li>Easy to tackle any complex data</li><li>Can manage the summary structure</li><li>Can use pretrained rerankers for the summary</li><li>Easy to add more data into the model without changing the architecture</li><li>Surprisingly good if summaries are high-quality</li><li>No Modality Gap</li><li>No need for manual weight management</li></ul><p><strong>Cons</strong></p><ul><li>LLM cost</li><li>Still need some prompting work to optimise summary structure</li><li>Additional summary creation layer make pipeline more complex</li></ul><p><strong>Good for</strong> cases when different data types complement each other. Also, if you are able to take LLM-cost under control.<br><strong>Poor for</strong> objects with independent data blocks. If you understand that some features of the object are totally independent from the others, probably you should separate them into multiple embeddings regardless of the approach.</p><h3>Conclusion</h3><p>Navigating through complex multimodal data is not easy and there is no single correct solution how to solve such task. As always, everything depends on your data. Hope, this brief guide will help you to get more ideas!</p><h3>Links</h3><ul><li><a href="https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907">A Gentle introduction to Vector Search</a></li><li><a href="https://jina.ai/news/the-what-and-why-of-text-image-modality-gap-in-clip-models/">About the Modality Gap</a></li><li><a href="https://weaviate.io/blog/hybrid-search-fusion-algorithms">Hybrid search explained in Weaviate blog</a></li><li><a href="https://superlinked.com/vectorhub/articles/why-do-not-need-re-ranking">Superlinked</a></li><li><a href="https://jina.ai/news/jina-embeddings-v4-universal-embeddings-for-multimodal-multilingual-retrieval">Jina Embeddings V4</a></li><li><a href="https://medium.com/@ma-korotkov/niche-search-enhancing-instagram-account-search-with-metric-learning-and-qdrant-946af0cbec99">Training custom embeddings with Metric Learning</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9be46a6fec05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Finding viral Creators using Qdrant and JinaAI Embeddings]]></title>
            <link>https://medium.com/@ma-korotkov/finding-viral-creators-using-qdrant-and-jinaai-embeddings-6c2f9690f4ca?source=rss-c98d7807594f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6c2f9690f4ca</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[qdrant]]></category>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[influencer-marketing]]></category>
            <dc:creator><![CDATA[Mikhail Korotkov]]></dc:creator>
            <pubDate>Mon, 07 Oct 2024 11:43:23 GMT</pubDate>
            <atom:updated>2024-10-07T11:43:23.453Z</atom:updated>
            <content:encoded><![CDATA[<h3>Finding viral Creators using Qdrant and JinaAI Embeddings. How we built Multilingual, Multimodal TikTok Vector Search at HypeAuditor</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PAF9r3nv_qQUpwYQEbwptA.png" /><figcaption>Discovery tool</figcaption></figure><h3>Introduction</h3><p>In today’s fast-paced influencer marketing world, finding relevant TikTok creators requires more than analysing the number of likes and subscribers. At HypeAuditor, we help brands discover influencers whose content, audience, and authenticity align with campaign goals. Traditional keyword searches often fail with video-heavy platforms like TikTok, so we developed a <strong>multimodal, multilingual semantic search engine</strong> using <strong>Qdrant</strong> and <strong>JinaAI embeddings</strong>. This allows us to semantically search and filter 100 million TikTok creators based on both content and metadata.</p><h3>The Approach</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lfs9TLFmJr5YlmDnvsLmvQ.png" /><figcaption>TikTok creator search pipeline</figcaption></figure><h4>1. Building the Discovery Database</h4><p>Our database includes over <strong>100 million TikTok creators</strong>. For each account, we collect a range of data:</p><ul><li><strong>Raw Account Metadata</strong>: followers count, likes count, account bio, etc.</li><li><strong>Content Data</strong>: post videos, descriptions.</li><li><strong>Complex features:</strong> engagement rate, bots percentage, audience geo distribution, etc.</li></ul><p>Navigating such data, especially when filtering by criteria like location or audience quality, is challenging. This is where embedding creator content comes into play.</p><h4>2. Multimodal Embedding with jina-clip-v1</h4><p>We use a <strong>CLIP-like image encoder</strong> to generate embeddings for each keyframe of a TikTok video. By averaging embeddings across all frames and videos, we produce an account-level embedding that represents the creator’s content. We also embed text data (e.g., bio, video descriptions) to combine multiple modalities for more comprehensive insights.</p><p>This approach is very convenient as it makes it very easy to combine this image data with any additional text data you may have, like creator biography from Wikipedia, for example:</p><ul><li>Extract <strong>keyframes</strong> from the video</li><li>Embed each keyframe with the <strong>jina-clip-v1 </strong>model</li><li>Compute an average embedding for each video. Then aggregate these embeddings to generate an <strong>account-level embedding</strong>, which represents the entire creator’s content</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cVMmyhPGySZ1pJxlhXXQYw.png" /><figcaption>TikTok creator embedding</figcaption></figure><h4>3. Choosing an embedding model</h4><p>As we needed a CLIP-like embedding model for our data we also faced a choice between several different approaches.</p><p>First option is to train your own account embeddings using <a href="https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907"><strong>Metric Learning</strong></a>, which is:</p><ul><li>a good choice when you have lots of domain-specific data and resources</li><li>a bad choice when you don’t have enough labeled data or resources to label it</li></ul><p>The second option is to use pretrained embedding models like <strong>OpenAI CLIP</strong>, <strong>clip-ViT-B-32-multilingual-v1</strong>, <strong>EVA-CLIP</strong> or <strong>jina-clip-v1</strong>. So we defined basic requirements we needed to follow to make this work:</p><ul><li>embeddings should handle the long context (&gt;1000 tokens) as we work with long creator summaries sometimes (like Wikipedia articles, for example) and it requires the model to be able to capture this data.</li><li>embeddings should be trained on up-to-date data (crucial for dynamic platforms like TikTok).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NnC5_DEkUnFgd-_187DZGQ.png" /><figcaption>Source: jina.ai</figcaption></figure><p>Summarising this we have chosen<strong> </strong><a href="https://jina.ai/news/jina-clip-v1-a-truly-multimodal-embeddings-model-for-text-and-image/"><strong>jina-clip-v1</strong></a><strong> embeddings. Jina Embeddings </strong>image encoder is build on top of <strong>EVA-02</strong> model which makes it the best choice for image search today. It also has <strong>8k tokens context</strong> which is ideal for our case and is much more suitable for text retrieval tasks as well as it <strong>bridges the gap between different modalities</strong> much better then other CLIP models.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*C3vPnHTOWrjg4No7.png" /><figcaption>Distribution of cosine similarity values between matching image-text pairs and text-text pairs in Jina CLIP. (Source: Jina.ai)</figcaption></figure><p>The <strong>modality gap</strong> is a serious problem for multimodal retrieval as it makes it difficult to aggregate embeddings of different modalities and makes it difficult to use it for text-text and text-image search at the same time. You can read more about it in this article:</p><ul><li><a href="https://jina.ai/news/the-what-and-why-of-text-image-modality-gap-in-clip-models">The What and Why of Text-Image Modality Gap in CLIP Models</a></li></ul><h4>4. Indexing in Qdrant</h4><p>We chose <strong>Qdrant</strong> as our vector database for its open-source nature, ability to perform complex searches with reranking and hybrid search features and simply being the fastest production-ready implementation of <a href="https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907">AKNN</a>. Qdrant efficiently handles our large dataset, storing both embeddings and metadata (e.g., bio, follower count). After we calculate the account embeddings for all 100 millions of TikTok creators in our database we create a <strong>Qdrant </strong>collection to store this embeddings and search through them. Alongside the embeddings, we store metadata such as the account bio, raw account data like followers count and more complex metrics. Here the challenges appear, as having more than 100 additional payload fields make your RAM consumption skyrocket.</p><p>To manage RAM consumption when handling large payloads, you can utilise techniques like:</p><ul><li>Storing payloads <strong>on disk</strong> (it will probably be slower, but sometimes it is not that important + you can manage which payload fields to store on disk).</li><li>Using <strong>smaller or quantised vectors</strong> (the quality of the search will decrease).</li><li>Optimising <strong>number of fields</strong> in your payload (sometime you can optimise the structure of some field to make them smaller or just avoid using that many filtering options).</li></ul><h4>5. Hybrid Search: Vector and Metadata</h4><p>After indexing all data in the vector database, you have the tool to get navigate through multiple TikTok accounts and using multiple filters alongside searching by their content vectors. To get the most relevant search candidates using <a href="https://qdrant.tech/documentation/concepts/hybrid-queries/#hybrid-search"><strong>Qdrant</strong> <strong>Hybrid search</strong></a> we can not only use the basic vector search but combine it with sparse keyword search starting from simple text index to <strong>BM42</strong>. It will help you to find exact text matches which are sometimes difficult to capture using vectors and combine them effectively with creators found by vectors using <a href="https://plg.uwaterloo.ca/~gvcormac/cormacksigir09-rrf.pdf"><strong>Reciprocal Rank Fusion</strong></a>. It is especially effective if you are searching for some specific terms, abbreviations or names. Not all embedding models could effectively handle names, brands or abbreviations like NFT.</p><pre># an example of Hybrid search using Qrant<br>from qdrant_client import QdrantClient, models<br><br>client = QdrantClient(url=&quot;http://localhost:6333&quot;)<br><br>client.query_points(<br>    collection_name=&quot;{collection_name}&quot;,<br>    prefetch=[<br>        models.Prefetch(<br>            query=models.SparseVector(indices=[1, 42], values=[0.22, 0.8]),<br>            using=&quot;sparse&quot;,<br>            limit=20,<br>        ),<br>        models.Prefetch(<br>            query=[0.01, 0.45, 0.67, ...],  # &lt;-- dense vector<br>            using=&quot;dense&quot;,<br>            limit=20,<br>        ),<br>    ],<br>    query=models.FusionQuery(fusion=models.Fusion.RRF),<br>)</pre><h4>5. Reranking</h4><p>Now you basically have the solution that could give you pretty good results. But it has one serious problem. Compare this two images:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*kuKekOmkESxYC_RCMiHYPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*pZY-wUcpcwWFIgbnoThHjw.png" /><figcaption>Results without/with reranking</figcaption></figure><p>On both images the results are relevant to the request “german shepherd dog”. But the accounts on the left are pretty small and much less relevant for someone who search for a creator to work with. They could also be fraudulent, inactive or lack proper amount of content.</p><p>Actually, <strong>not always results the most relevant to the search query are also the ones the most anticipated by the user</strong>. This leads us to the idea that all candidates sampled from Qdrant should be reranked according to their use for the users, not by vector similarity only.</p><p>If you have a textual data you can also apply <strong>Cross-Encoders</strong> for better reranking of the documents sampled initially from a vector store. You can also utilise tools like <strong>LangChain </strong>or<strong> LlamaIndex </strong>to make this two-step pipeline more convenient.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/0*HOkiW3-FPCGjU3BL.png" /><figcaption>Source: LlamaIndex</figcaption></figure><p>Unfortunately, in our case reranking module should be pretty unique, as we use custom features like Bots Percentage or Engagement Rate. There are multiple <strong>Learning to Rank</strong> methodologies and the ranking task itself is pretty unique giving you multiple ways to formulate the task. Which one to apply depends mostly on your data and business metric.</p><p>Anyway, it is not the topic of this article, but you can check a brilliant article about different <strong>Ranking</strong> methodologies here:</p><ul><li><a href="https://towardsdatascience.com/learning-to-rank-a-complete-guide-to-ranking-using-machine-learning-4c9688d370d4">https://towardsdatascience.com/learning-to-rank-a-complete-guide-to-ranking-using-machine-learning-4c9688d370d4</a></li></ul><h3>Conclusion</h3><p>Finally, after adding Reranking module our AI search tool is ready to go. Our vector search tool leverages <strong>Qdrant</strong> and <strong>Jina embeddings</strong> to help brands find the right TikTok creators. With reranking and hybrid search in place, we optimise discovery, saving brands time and enhancing the relevance of search results. This solution ensures brands can efficiently navigate millions of creators to find those who are truly aligned with their campaign needs.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/692/1*MLawOZgapByJp5QIwClNVA.gif" /><figcaption>Search example</figcaption></figure><p>Hope this article was interesting for you. Take care!</p><h3>Acknowledgement</h3><ul><li><a href="https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907">About vector search</a></li><li><a href="https://medium.com/@ma-korotkov/niche-search-enhancing-instagram-account-search-with-metric-learning-and-qdrant-946af0cbec99">Instagram Niche Search</a></li><li><a href="https://hypeauditor.com/">HypeAuditor</a></li><li><a href="https://qdrant.tech/">Qdrant</a></li><li><a href="https://jina.ai/">JinaAI</a></li><li><a href="https://towardsdatascience.com/learning-to-rank-a-complete-guide-to-ranking-using-machine-learning-4c9688d370d4">Reranking</a></li><li><a href="https://jina.ai/news/the-what-and-why-of-text-image-modality-gap-in-clip-models">Modality Gap</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6c2f9690f4ca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Niche search: Enhancing Instagram Account Search with Metric Learning and Qdrant]]></title>
            <link>https://medium.com/@ma-korotkov/niche-search-enhancing-instagram-account-search-with-metric-learning-and-qdrant-946af0cbec99?source=rss-c98d7807594f------2</link>
            <guid isPermaLink="false">https://medium.com/p/946af0cbec99</guid>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[metric-learning]]></category>
            <category><![CDATA[qdrant]]></category>
            <category><![CDATA[pytorch-lightning]]></category>
            <category><![CDATA[multimodality]]></category>
            <dc:creator><![CDATA[Mikhail Korotkov]]></dc:creator>
            <pubDate>Sat, 18 Nov 2023 19:45:26 GMT</pubDate>
            <atom:updated>2023-11-18T19:46:24.700Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, we delve into the process of developing a vector search for Instagram accounts using multimodal data and Qdrant vector storage.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RtISTflLUTxs3sLfvvOHSQ.png" /><figcaption>Instagram Niche Account Search</figcaption></figure><h3>Introduction</h3><p>I’m Mikhail, the Data Science Team Lead at <a href="https://hypeauditor.com/">HypeAuditor</a>. HypeAuditor is an advanced analytics platform that specialises in influencer marketing on social media, particularly Instagram. It provides brands and marketing agencies with detailed insights about Instagram influencers, helping them identify the most effective influencers for collaborations and manage successful advertising campaigns.</p><p>Within HypeAuditor, “Discovery” product serves as a powerful search and analysis tool that allows brands and marketing agencies to sift through a vast database of influencers based on specific criteria such as audience demographics, engagement rates, and content relevance.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CkJHkmycL6ZaN8muDtonow.png" /><figcaption>Discovery search example</figcaption></figure><p>A few months ago<strong> </strong>our platform functioned as an extensive database featuring nearly 50 million Instagram influencers. Users had to navigate through this vast pool using various filters, ranging from basic ones like influencer size to more complex ones like keywords or categories. Our classification system, a simple text-based softmax-ending classifier, was efficient and quick. However, we encountered several challenges:</p><ol><li>Customisation Difficulty: Each client has unique needs, and retraining our model to add new categories required significant time for data collection, model training, and app integration. This process was not only time-consuming but also limited the number of classes we could add without compromising the user experience.</li><li>Specificity Limitations: The high-level categories we offered often didn’t meet the specific needs of users. For example, a user interested in the beauty category might be looking for content specifically about sunscreen or skincare, which our categories were too broad to address effectively.</li><li>Model Scalability: Continuously adding classes to our softmax classifier led to a decline in model performance. We realised that to maintain the precision of our model, we might need to consider implementing a modification like ArcFace to ensure better distinction between classes.</li></ol><p>We started our project with the concept of developing a comprehensive Instagram account embedding model. This model would integrate all of an influencer’s content into a single vector, subsequently utilised for efficient retrieval. By shifting from the traditional “database with filters” approach to a vector search model, we aimed to enhance user experience. This new method ensures that users consistently receive the most relevant results, streamlining the querying and filtering process. Moreover, these joint embeddings could serve a variety of purposes, ranging from basic classification tasks to more complex challenges like recommendations and finding similar accounts.</p><h3>Defining the task and requirements</h3><p>To meet the key desired system requirements, the system must:</p><ul><li>Have the capability to find any account within our database efficiently.</li><li>Ensure low latency during the search process, as it operates in real-time. The maximum time for processing a request should not exceed 300 milliseconds.</li><li>Allow the usage of additional filters to refine the search results, such as filtering by subscriber count.</li><li>Consistently deliver a specific number of account results.</li></ul><p>These requirements are essential to ensure that the system operates effectively, offering both speed and precision in the search functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jV-4iDPpFvlYwIOiX-pe9Q.png" /><figcaption>Instagram Niche Account Search general pipeline</figcaption></figure><p>These considerations steered us towards adopting a Metric Learning pipeline, complemented by a vector storage system for account vectors. For those looking to brush up on various basic Metric Learning loss types, this <a href="https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-1-6310a4e5476">article</a> is a helpful resource.</p><p>To effectively implement this pipeline, the following steps are essential:</p><ul><li>Designing and training account and query embedding models to transform data into a unified vector space.</li><li>Setting up a vector storage to enable quick retrieval from a large volume of stored vectors.</li><li>Start querying</li></ul><p>Let’s dive deeper into the details of this pipeline!</p><h3>Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-Hj22cvN_lWIDYg199BTQg.png" /></figure><h4>Architecture. General pipeline</h4><p>In the next phase, we’re going to train a custom PyTorch encoder for both accounts and queries using Contrastive Loss and cosine similarity metric. The end goal is to transform our entire database into account embeddings, indexed within Qdrant’s efficient vector storage. From there, we’ll harness the power of Approximate Nearest Neighbour Search (AKNN) to connect queries with the most relevant accounts.</p><p>So, how does this all come together? Let’s break down our pipeline into a series of engaging steps, diving into the nitty-gritty of each:</p><ul><li>Collecting Accounts Data: Our first stop is collecting Instagram data. Think of it as gathering the essence of each account, from the personality-infused descriptions to the post images and post descriptions.</li><li>Collection Queries Data: The next step is to compile request data that is essential for querying against the accounts we’ve amassed.</li><li>Model Development: Here, we focus on creating a text query encoder model and a joint account data encoder model. These are trained to transform different types of inputs into a single vector space, suitable for information retrieval.</li></ul><h4>Architecture. Account embedding model</h4><p>As seen on a picture above simple model we need consists of:</p><ul><li>image encoder</li><li>text encoder</li><li>average pooling layers for post images and post description</li><li>some MLP to join image and text blocks</li></ul><p>We will use pretrained CLIP Image encoder (<em>ViT-B32</em>) as an image encoder here for post images and <em>sentence-transformer/paraphrase-multilingual-miniLM-L12–2</em> as a text encoder for account and post descriptions. We will also have a simple MLP block converting multiple encoded images and text into one 128-dimensional vector. As the result, it incorporates almost all existing content-related information about account we have.</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br><br>class AccountEncoder(nn.Module):<br>    def __init__(self, n_dim=128, image_enc_dim=512, text_enc_dim=384):<br>        super(AccountEncoder, self).__init__()<br>        self.n_dim = n_dim<br>        self.linear1 = nn.Linear(text_enc_dim * 2 + image_enc_dim, self.n_dim * 2)<br>        self.linear2 = nn.Linear(self.n_dim * 2, self.n_dim)<br><br>    def forward(self, x):<br>        post_emb = x[&#39;post_embedding&#39;]<br>        bio_emb = x[&#39;bio_embedding&#39;]<br>        image_emb = x[&#39;images_embedding&#39;]<br><br>        concat_emb = torch.cat((post_emb, bio_emb, image_emb), dim=-1)<br>        output = F.silu(self.linear1(concat_emb))<br>        output = F.normalize(self.linear2(output), dim=0)<br><br>        return output</pre><p>We are using quite small output embeddings (128) for now to reduce the vector size and make it simpler to fit them all in storage further.</p><h4>Architecture. Query processing</h4><p>The next part of this pipeline is query processing, where we will have two main requirements:</p><ul><li>QueryEncoder outputs must have the same size as the AccountEmbedding model outputs (128).</li><li>QueryEncoder must be able to work fast enough (less then 100ms per query) as it will be working in real-time.</li><li>It must be multilingual.</li></ul><p>So we decided to use the same pretrained <em>sentence-transformer/paraphrase-multilingual-miniLM-L12–2</em> model for query embeddings, followed by small MLP layer converting it to 128-dimensional vectors.</p><pre>class QueryEncoder(nn.Module):<br>    def __init__(self, n_dim=128, text_enc_dim=384):<br>        super(QueryEncoder, self).__init__()<br>        self.n_dim = n_dim<br>        self.linear1 = nn.Linear(text_enc_dim, self.n_dim * 2)<br>        self.linear2 = nn.Linear(self.n_dim * 2, self.n_dim)<br><br>    def forward(self, query_emb):<br>        output = F.silu(self.linear1(query_emb))<br>        output = F.normalize(self.linear2(output), dim=0)<br><br>        return output</pre><p>Great! Now we have the full model architecture, let’s start training!</p><h3>Model training</h3><p>As mentioned above, we are going to train AccountEncoder and QueryEncoder to transform account and query data into the same vector space using Contrastive Loss. As we use pretrained models for text and image embeddings, we only need to train several MLP layers, which doesn’t sound difficult, but we still need a dataset for training.</p><h4>Model training. Data collection</h4><p>If you want to train a model with Contrastive Loss, you will need positive and negative account examples for each request. But where to find useful query examples and how distinguish positive ones from negatives? As a B2B company, we do not have enough client requests with relevant feedback to train at, so the main idea we used was to preprocess post hashtags instead of user requests. This data is cheap and easy to collect and use. You also can vary the relevancy level of this hashtags during dataset collection if you see that you don’t like the results. On the other hand, you will also get hashtags that could not be encoded correctly (as brand names, abbreviations or slang). You could also have some kind of trash hashtags as #viral which are not suitable for training. Nevertheless, this is the easiest way to collect data in a really sufficient amounts, and with careful preprocessing it will bring you lots of benefits.</p><p>For this model specifically, we had collected top 100k unique hashtags from 10 million of unique Instagram accounts.</p><h4>Model training. Enriching dataset with ChatGPT</h4><p>Method mentioned above could be very efficient and fast to implement, but what if you want to find more accounts relevant to unique queries not presented well enough by hashtags? We could still try to create top categories map and collect most popular terms for this category using some LLM like ChatGPT. You could expand this process to brand names, celebrities, keywords or similar hashtags as well as to expand your map to additional subtopics making your dataset even bigger.</p><p>Here is an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gZQeXX6u6zXmO9wuc8n5tw.png" /><figcaption>Hierarchical niche structure example</figcaption></figure><p>After collecting such synthetic data you could easily use categories and subcategories names as queries and accounts with such terms in bio / posts as positive examples for Contrastive Loss. You could also vary the “purity” of the data by number of times some of terms were included in accounts descriptions or posts. And the most intriguing part here is that the whole pipeline could be easily automised by basic scripting and careful post-processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gmA0AHIH1hWrHzHU9JyIdA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pJpE4dFz8etGAV8vTr4QBA.png" /><figcaption>ChatGPT request examples</figcaption></figure><p>This method may still require some human supervision, but the amount of time spent on validation is less than manual labelling and could increase the dataset size significantly.</p><p>Additionally, the hierarchical structure of this map could be beneficial when collecting negative examples during different training stages. For instance, at the beginning of training, the great idea is to select negative examples from different categories. This strategy helps the model to grasp basic dependencies and connections between classes. Later, for more refined training and to understand complex dependencies, you can use negative examples from the same category but different subcategories.</p><p>If you’re interested in learning more about Contrastive Loss, you can take a look at one of my previous <a href="https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-1-6310a4e5476">articles</a>. So here below are main model classes used in this models. As you can see, their architecture is very simple.</p><pre>import torch<br>import torch.nn as nn<br>import numpy as np<br>import pytorch_lightning as pl<br><br><br># NicheDataset objects structure<br># {<br>#     &#39;features&#39;: {<br>#         &#39;post_embedding&#39;: self.features[user][&#39;post_embedding&#39;],<br>#         &#39;bio_embedding&#39;: self.features[user][&#39;bio_embedding&#39;],<br>#         &#39;images_embedding&#39;: self.features[user][&#39;images_embedding&#39;]<br>#     }, <br>#     &#39;query_embedding&#39;: kw_encodings[kw],<br>#     &#39;label&#39;: label  # 1 for positive and -1 for negative ones<br># }<br><br><br>class SimilarityLearning(pl.LightningModule):<br>    def __init__(self, account_encoder, query_encoder, margin=0.5):<br>        super().__init__()<br>        self.acc_encoder = account_encoder<br>        self.query_encoder = query_encoder<br>        self.сontrastive_loss = nn.CosineEmbeddingLoss(margin=margin)<br><br>    def training_step(self, batch, batch_idx):<br>        account_features = batch[&#39;features&#39;]<br>        query_features = batch[&#39;query_embedding&#39;]<br>        labels = batch[&#39;label&#39;]<br>        account_emb = self.acc_encoder(account_features)<br>        query_emb = self.query_encoder(query_features)<br>        loss = self.сontrastive_loss(account_emb, query_emb, labels)<br>        self.log(&quot;train_loss&quot;, loss, on_step=True, on_epoch=True,prog_bar=True, logger=True)<br>        <br>        return loss<br>    <br>    def validation_step(self, batch, batch_idx):<br>        # this is the validation loop<br>        account_features = batch[&#39;features&#39;]<br>        query_features = batch[&#39;query_embedding&#39;]<br>        labels = batch[&#39;label&#39;]<br>        account_emb = self.acc_encoder(account_features)<br>        query_emb = self.query_encoder(query_features)<br>        val_loss = self.сontrastive_loss(account_emb, query_emb, labels)<br>        self.log(&quot;val_loss&quot;, val_loss, on_step=True, on_epoch=True,prog_bar=True, logger=True)<br>    <br>    def configure_optimizers(self):<br>        optimizer = torch.optim.Adam(self.parameters(), lr=0.0001)<br>        sch = torch.optim.lr_scheduler.StepLR(<br>            optimizer, <br>            step_size=5, <br>            gamma=0.5,<br>        )<br><br>        return {<br>            &quot;optimizer&quot;:optimizer,<br>            &quot;lr_scheduler&quot; : {<br>                &quot;scheduler&quot; : sch,<br>                &quot;monitor&quot; : &quot;train_loss&quot;,<br>            }<br>        }</pre><p>So basic PyTorch Lightning training code will look somehow like this:</p><pre>import pytorch_lightning as pl<br>from pytorch_lightning.callbacks.early_stopping import EarlyStopping<br>from torch.utils.data import DataLoader<br><br><br>train_set = NicheDataset(train_data)<br>val_set = NicheDataset(val_data)<br><br>train_loader = DataLoader(train_set, batch_size=256, shuffle=True)<br>val_loader = DataLoader(val_set, batch_size=256, shuffle=True)<br><br>n_dim = 128<br>acc_encoder = AccountEncoder(n_dim)<br>qry_encoder = QueryEncoder(n_dim)<br><br>model = SimilarityLearning(<br>    account_encoder=acc_encoder, <br>    query_encoder=qry_encoder,<br>    margin=0.5<br>)<br><br>early_stop_callback = EarlyStopping(monitor=&quot;val_loss&quot;, min_delta=0.00, patience=6, verbose=False, mode=&#39;min&#39;)<br>trainer = pl.Trainer(max_epochs=1, callbacks=[])<br>trainer.fit(model, train_loader, val_loader)</pre><h3>Vector Storage</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J0FZ8WJ56dnI91AIDhNJNQ.png" /><figcaption>Image from official Qdrant <a href="https://qdrant.tech/benchmarks/#benchmarking-vector-search-engines">documentation</a></figcaption></figure><p>After training and locally testing the model on a smaller sample, the next challenge was deploying it in a production environment. Given our extensive account database, which includes around 50 million Instagram accounts, and the need for real-time search capabilities, we required a robust vector storage search solution. Initially, we turned to ElasticSearch, which we had used in our previous Discovery version, and experimented with their AKNN search. However, it proved to be extremely slow. With the size of our database and our setup, it took an average of about 3 seconds per query to find the top 1000 relevant accounts.</p><p>Consequently, we began exploring the most promising vector search solutions available on the market, including Milvus, Qdrant, Weaviate, and Pinecone. We set up each platform and conducted a comparative analysis of their performance.</p><h4>Vector Storage. Qdrant as vector search engine</h4><p>Here is the official benchmarks for top vector search vendors:</p><p><a href="https://qdrant.tech/benchmarks/">Benchmarks F.A.Q.</a></p><p>And here is the actual performance comparison on our data with dataset around 1 million of account vectors:</p><pre>|| Vector database || Search time ||<br>|==================||==============|<br>|| Milvus          || 789 ms      ||<br>|| Pinecone        || 400 ms      ||<br>|| Qdrant          || 112 ms      ||<br>|| ElasticSearch   || 2987 ms     ||<br>|==================================|</pre><p>If you want to dive deeper to understand the difference between all of this products, take a look at a brilliant <a href="https://towardsdatascience.com/milvus-pinecone-vespa-weaviate-vald-gsi-what-unites-these-buzz-words-and-what-makes-each-9c65a3bd0696?source=user_profile---------0----------------------------">Vector podcast</a> where you can find more detailed comparisons between the platforms as well as interviews with their creators.</p><p>In our situation we primarily focus on this three aspects:</p><ul><li>it must be fast enough for real-time usage even with 50 million database</li><li>it must support different filter types (as we have a long list of additional filters with different types in Discovery product)</li><li>it must have an open-source version with adequate documentation</li></ul><p>So we stopped our choice at Qdrant, as it appeared to have the fastest AKNN implementation among all other competitors, it supported all of our existing filters (or we were able to recreate it in a similar way) and had an open-source version with brilliant documentation.</p><h4>Vector Storage. Setting up Qdrant</h4><p>To start using Qdrant you can easily run it in Docker container using:</p><pre>docker pull qdrant/qdrant<br>docker run -p 6333:6333 -v $(pwd)/qdrant_storage:/qdrant/storage:z qdrant/qdrant</pre><p>Under the default configuration all data will be stored in the ./qdrant_storage directory.</p><p>Then you can use a python client to connect to the database, create a collection for your vectors and load your data and start writing simple queries:</p><pre>from qdrant_client import QdrantClient<br>from qdrant_client.http.models import Distance, VectorParams<br>from qdrant_client.http.models import PointStruct<br>from qdrant_client.http.models import Filter, FieldCondition, MatchValue<br><br><br>YOUR_VECTORS_DIM = 4<br>COLLECTION_NAME = &quot;YOUR_COLLECTION_NAME&quot;<br><br><br># use locally running Qdrant<br>client = QdrantClient(&quot;localhost&quot;, port=6333)<br><br># create collection for your data and specify vector size and similarity measure<br>client.create_collection(<br>    collection_name=COLLECTION_NAME,<br>    vectors_config=VectorParams(size=YOUR_VECTORS_DIM, distance=Distance.COSINE),<br>)<br><br># add data points to this new collection<br>operation_info = client.upsert(<br>    collection_name=COLLECTION_NAME,<br>    wait=True,<br>    points=[<br>        PointStruct(id=1, vector=[0.05, 0.61, 0.76, 0.74], payload={&quot;city&quot;: &quot;Berlin&quot;}),<br>        PointStruct(id=2, vector=[0.19, 0.81, 0.75, 0.11], payload={&quot;city&quot;: &quot;London&quot;}),<br>        PointStruct(id=3, vector=[0.36, 0.55, 0.47, 0.94], payload={&quot;city&quot;: &quot;Moscow&quot;}),<br>        PointStruct(id=4, vector=[0.18, 0.01, 0.85, 0.80], payload={&quot;city&quot;: &quot;New York&quot;}),<br>        PointStruct(id=5, vector=[0.24, 0.18, 0.22, 0.44], payload={&quot;city&quot;: &quot;Beijing&quot;}),<br>        PointStruct(id=6, vector=[0.35, 0.08, 0.11, 0.44], payload={&quot;city&quot;: &quot;Mumbai&quot;}),<br>    ],<br>)<br><br># make a simple query with filters<br>search_result = client.search(<br>    collection_name=COLLECTION_NAME,<br>    query_vector=[0.2, 0.1, 0.9, 0.7],<br>    query_filter=Filter(<br>        must=[FieldCondition(key=&quot;city&quot;, match=MatchValue(value=&quot;London&quot;))]<br>    ),<br>    limit=3,<br>)</pre><p>This example is valid, but in reality, you will also encounter couple of details. First of all, you will need to look precisely at the default Qdrant <a href="https://github.com/qdrant/qdrant/blob/master/config/config.yaml">config</a> as it may be better for your case to choose another parameters.</p><p><strong>Choosing HNSW index configuration</strong></p><pre>hnsw_index:<br>    # Number of edges per node in the index graph. Larger the value - more accurate the search, more space required.<br>    m: 16<br>    # Number of neighbours to consider during the index building. Larger the value - more accurate the search, more time required to build index.<br>    ef_construct: 100<br>    # Minimal size (in KiloBytes) of vectors for additional payload-based indexing.<br>    # If payload chunk is smaller than `full_scan_threshold_kb` additional indexing won&#39;t be used -<br>    # in this case full-scan search should be preferred by query planner and additional indexing is not required.<br>    # Note: 1Kb = 1 vector of size 256<br>    full_scan_threshold_kb: 10000<br>    # Number of parallel threads used for background index building. If 0 - auto selection.<br>    max_indexing_threads: 0<br>    # Store HNSW index on disk. If set to false, index will be stored in RAM. Default: false<br>    on_disk: false<br>    # Custom M param for hnsw graph built for payload index. If not set, default M will be used.<br>    payload_m: null</pre><p>First of all, you need to decide if you are ready to store <a href="https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907">HNSW</a> index on disk or in RAM. You also need to decide which precision level you want to have, choosing <em>m</em> value (that is the number of edges per node in the index graph and it affects the index size). To understand the quality levels for each m<em> </em>value better, you can use Qdrant’s own benchmarks.</p><p><strong>Adding payload indexes</strong></p><p>If you want additional filters to work fast for a big database you will need to add indexes for them.</p><pre>FIELD_NAME = &quot;subscribers_count&quot;<br>FIELD_TYPE = &quot;integer&quot;<br><br>client.create_payload_index(<br>    collection_name=COLLECTION_NAME,<br>    field_name=FIELD_NAME,<br>    field_schema=FIELD_TYPE,<br>    wait=False,<br>)</pre><p>As payload indexes are usually stored in RAM the great idea will be to estimate the amount of RAM you will need for Qdrant to operate properly on your data. You should better follow the official Qdrant <a href="https://qdrant.tech/articles/memory-consumption/">article</a> about memory optimisations, but generally it states the simplified formula:</p><pre>memory_size = number_of_vectors * vector_dimension * 4 bytes * 1.5</pre><p>But be cautious, memory required for your payload indexes could be several times more in certain cases, especially if you have multiple payload indexes. For example, our RAM usage was around 4 times more than we were estimating in the beginning. Also, to be fair we were using less optimised 1.4 version of Qdrant, so after update to 1.6 version our RAM usage dropped almost in a half.</p><h3>The result</h3><p>After setting up Qdrant and filling it with vectors and payload, nothing is stopping us from testing the results.</p><p>Here we go:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*E35N5gnTJ3qdpdbUKZSAUw.gif" /><figcaption>HypeAuditor Account Niche Search process</figcaption></figure><h3>Outcomes</h3><p>Current search implementation appeared to be much more convenient for users and significantly reduced average search time. We have also easily created several content-based recommendation models using that joint account embeddings, account tagging model and several classifiers. Talking about future, this system could be improved by applying additional reranker after extracting top 1000 more relevant documents. Recent studies shows that this could improve the search relevancy significantly.</p><p>We also are planning to create similar models for Youtube and Tiktok accounts and incorporate additional data within the vectors, like Wikipedia information, locations and information from connected accounts from different social networks.</p><p>Hope this article was interesting for you. Take care!</p><h3>Acknowledgement</h3><ul><li><a href="https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907">About vector search</a></li><li><a href="https://qdrant.tech/">Qdrant</a></li><li><a href="https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-1-6310a4e5476">Contrastive loss</a></li><li><a href="https://hypeauditor.com/">HypeAuditor</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=946af0cbec99" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unveiling Brand Logo Detection: Leveraging Ultralytics YOLOv8 and Roboflow]]></title>
            <link>https://medium.com/@ma-korotkov/unveiling-brand-logo-detection-leveraging-ultralytics-yolov8-and-roboflow-abc3ab42b06f?source=rss-c98d7807594f------2</link>
            <guid isPermaLink="false">https://medium.com/p/abc3ab42b06f</guid>
            <category><![CDATA[roboflow]]></category>
            <category><![CDATA[computer-vision]]></category>
            <category><![CDATA[object-detection]]></category>
            <category><![CDATA[logo-detection]]></category>
            <category><![CDATA[yolo]]></category>
            <dc:creator><![CDATA[Mikhail Korotkov]]></dc:creator>
            <pubDate>Thu, 02 Nov 2023 12:35:23 GMT</pubDate>
            <atom:updated>2023-11-02T12:44:16.662Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zIWipp9DpLcqVc-A" /><figcaption>Nike Logo tracking</figcaption></figure><p><em>The purpose of this article is to demonstrate how to easily build and train a logo detection model from scratch using the Roboflow data platform and Ultralytics YOLOv8, and subsequently convert this model into a service. The entire process will be demonstrated using Nike brand logos as an example but can be readily adapted to any other logos. If you’ve ever considered building such a product or if you’re intrigued by another real-world application of YOLO object detection, this article might capture your interest!</em></p><h3>The idea</h3><p>In today’s digital landscape, the identification and recognition of brand logos plays a pivotal role in marketing, brand monitoring, and consumer behaviour analysis. With the rapid growth of image-centric social platforms such as Instagram and the ubiquity of visual content, the need for efficient and accurate logo detection systems has become more crucial than ever.</p><p>Personally, I encountered this challenge while developing a Market Analysis tool for a <a href="https://hypeauditor.com/">Hypeauditor</a> influencer marketing analytical platform. The core idea behind this tool was to offer major brands, exemplified by giants like Nike, a comprehensive understanding of their position within the influencer marketing domain. This involved comparing their standing against competitors. However, the real challenge lay in distinguishing posts that prominently featured Nike’s symbol or were advertisements, from those that were not.</p><p>Determining the sponsored nature of a post and recognizing the brands involved could significantly impact the analysis. A common method involved scrutinizing the post descriptions for any mentions or hashtags, which did offer some insights. However, this method lacked depth in describing the accurate state of market landscape. Influencers often wear Nike apparel without any explicit mentions, and there were also non-advertisement posts that scarcely featured brand references.</p><p>So the idea was to create a model detecting which brands influencers usually wear and the easiest way to do so was to train custom logo detection models. That motivated me to make a brief instruction how to easily build a logo detection model on your raw data using Roboflow data management platform and YOLOv8. This example demonstrates Nike logos detection package, but that could easily be applied for any other logos of your choice.</p><p>This led me to explore the development of a solution — a model capable of detecting the brands that influencers typically wore. The most viable approach was to train custom logo detection models as almost all brands use logos on their products, they are quite standard and as that how the human usually can solve this type of task. This inspired me to share this simple guide on constructing a logo detection model using the Roboflow data management platform and YOLOv8.</p><h3>The data collection</h3><p>Given that data forms the cornerstone of all machine learning models, the process begins with the collection of images featuring corresponding brand logos. An efficient approach involves downloading images from official brand accounts (such as @nike, @nikesportswear, @nikefootball, @nikewomen) utilizing the Instagram API (or scraping data directly from web). These accounts typically have logos on most of the images, maintain higher image quality, and contain a lesser number of irrelevant images. The drawback is that most of this photos could be quite similar in terms of quality, light and style. In cases where this source proves insufficient, one may also explore sourcing images through brand-specific hashtags, external datasets, or even utilizing video frames from advertisements.</p><p>As the target model domain is relatively broad, we will significantly benefit from diversifying and increasing the amount of training data. The most of external logo datasets lack “live” images that are the primary component of the Instagram, so adding such posts will help the model to learn real life dependancies better and shift the training data distribution a little bit towards the inference distribution.</p><h3>The labelling process using Roboflow</h3><p>Alright, now you’ve gathered a group of images likely to contain required brand logos. Should you wish to train an object detection model, such as YOLO, you’ll need to identify target bounding boxes and convert this information into YOLO format for seamless training — a process easily facilitated by the Roboflow platform. All you’ll require is to establish a Roboflow project, upload the images, and start labeling. If you want to speed up the labelling process you can also assign labelling tasks to multiple annotators. Moreover, if you want to label video frames you can do it directly from youtube video link, choosing desired number of frames per second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i2uKzqLy6aT5rCQirY19Hg.png" /><figcaption>You can add annotating jobs independently from different data sources and assign them to different annotators and create new dataset version anytime during the labelling process.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qtLh0w6ucRRzjREoZkT-QA.png" /><figcaption>Labeled images</figcaption></figure><h3>Resulting Dataset reference</h3><p>After successfully labeling the desired number of images, you can commence constructing the final dataset for model training and evaluation. During this stage, the Roboflow platform can significantly streamline your process by effortlessly dividing your images into train, validation, and test datasets in desired proportions. It also offers the flexibility to easily rebalance these datasets whenever required. Additionally, with just one click, the platform can apply custom preprocessing steps or various augmentations to the images within your training dataset, thereby saving you a considerable amount of time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*OVNTV7qItuOOMFRgp75--Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*stlZTIekFltf2KJMgues2A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*M53MIMMEe4_wSHBhtoUIOw.png" /><figcaption>Preparing the final dataset</figcaption></figure><p>After that step the only thing left will be to publish the dataset. The dataset version used for Nike logos model training could found <a href="https://universe.roboflow.com/mikhail-korotkov/brand-logos-f5red">here</a>:</p><h3>Ultralytics YOLOv8 model training</h3><p><a href="https://ultralytics.com/">Ultralytics</a> <a href="https://github.com/ultralytics/ultralytics">YOLOv8</a> represents the newest iteration of the highly praised real-time object detection and image segmentation model. Built on the latest advancements in deep learning and computer vision, YOLOv8 delivers unparalleled performance concerning speed and accuracy. For a comprehensive understanding of the fundamentals of the YOLO architecture, consider reading the <a href="https://medium.com/analytics-vidhya/yolo-explained-5b6f4564f31">article</a> covering its main architectural principles. Additionally, to discern the differences among various YOLO versions, explore this brilliant <a href="https://medium.com/cord-tech/yolov8-for-object-detection-explained-practical-example-23920f77f66a">article</a>.</p><p>Interestingly, after properly preparing the dataset, the training process transforms into just several lines of code.</p><pre>from roboflow import Roboflow<br>from ultralytics import YOLO<br><br><br># load Roboflow dataset<br>rf = Roboflow(api_key=&quot;YOUR_ROBOFLOW_API_KEY&quot;)<br>project = rf.workspace(&quot;mikhail-korotkov&quot;).project(&quot;brand-logos-f5red&quot;)<br>dataset = project.version(11).download(&quot;yolov8&quot;)<br><br># Load a model<br>model = YOLO(&#39;yolov8x.yaml&#39;)  # build a new model from scratch<br>model = YOLO(&#39;yolov8x.pt&#39;)  # load a pretrained model (recommended for training)<br><br># Train the model<br>results = model.train(data=&#39;data.yaml&#39;, epochs=100, verbose=True)</pre><p>Obviously, you still can experiment with different training strategies to get the best out of your model with the help of Ultralytics <a href="https://docs.ultralytics.com/">documentation</a>. The actual yolov8x training (100 epochs on mentioned dataset) on RTX 4090 took around 5 hours.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nRBfU2Ogp1R6YrTLbmlRfw.png" /></figure><p>Now the model is trained, let’s check the results!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*4NeH7ZSnc_x7ftWm" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*CFN6mVg4wh-h0fFzeS8jdQ.jpeg" /></figure><p>As YOLOv8 also provides tracking pipeline, you can also check the tracking quality out of the box. Ok, lets try the model on some simple stock video and something more difficult like well-known Nike football advertisement filmed by Guy Ritchie (shortened for conveniency)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*Gc8-BicbB_VjPps1" /><figcaption>Nike Logo tracking</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*zIWipp9DpLcqVc-A" /><figcaption>Nike Logo tracking</figcaption></figure><p>Surprisingly, even without any significant model customisation and with a small amount of training data, the results appear quite stable in this fast-paced, low-quality video!</p><h3>Building a package and an API</h3><p>After training the model and evaluating its quality and performance you can also build a package or an API for logo detection. Here you can find the <a href="https://github.com/LiahimRatman/BrandLogoDetection/tree/main">repository</a> with Nike logo detection package and an instruction how to set up a simple FastAPI for it. You can also install the existing Nike detection package using pip:</p><pre>pip install nike_detector==0.0.18</pre><p>and test it yourself using:</p><pre>from PIL import Image<br>from nike_detector.nike_detector.service.service import init_nike_model, predict<br><br># initialize model<br>model = init_nike_model()<br><br># load image<br>im = Image.open(&quot;your_image_name.jpg&quot;)<br><br># run detection<br>results = predict(im)<br>```</pre><p>Similar for tracking:</p><pre>```<br>from nike_detector.nike_detector.service.service import init_nike_model, track<br><br>video = &#39;you_video_name.mp4&#39;<br><br># initialize model<br>model = init_nike_model()<br><br># run tracking<br>results = track(video, False, False)<br>```</pre><p>You can also run this model in a Docker container. It is a basic version of FastAPI with one endpoint &quot;vectorize_batch&quot; for detection. You can easily build this image using:</p><pre>docker build -f Dockerfile -t you_image_name:v1.0.0 .</pre><p>and run it with:</p><pre>docker run -p 8021:8021 you_image_name:v1.0.0</pre><h3>Conclusion</h3><p>As you can see, the process of constructing an object detection pipeline, such as brand logo detection, can be streamlined using frameworks like Roboflow and Ultralytics YOLOv8. By following the same steps, you can create a similar pipeline within just a couple of hours and seamlessly integrate it into your applications. It is hoped that this article will assist in revealing how straightforward the entire process can be and how you can leverage the capabilities of YOLO for brand logo detection!</p><h3>References</h3><ul><li><a href="https://github.com/LiahimRatman/BrandLogoDetection/tree/main">Nike Logo Detection repository</a></li><li><a href="https://medium.com/analytics-vidhya/yolo-explained-5b6f4564f31">YOLO explained</a></li><li><a href="https://medium.com/cord-tech/yolov8-for-object-detection-explained-practical-example-23920f77f66a">article</a></li><li><a href="https://universe.roboflow.com/mikhail-korotkov/brand-logos-f5red">Dataset</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abc3ab42b06f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A gentle introduction to Vector Search]]></title>
            <link>https://medium.com/@ma-korotkov/a-gentle-introduction-to-vector-search-dc6e54e34907?source=rss-c98d7807594f------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc6e54e34907</guid>
            <category><![CDATA[nearest-neighbor-search]]></category>
            <category><![CDATA[vector-database]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[deep-learning]]></category>
            <category><![CDATA[hnsw]]></category>
            <dc:creator><![CDATA[Mikhail Korotkov]]></dc:creator>
            <pubDate>Wed, 21 Jun 2023 20:03:42 GMT</pubDate>
            <atom:updated>2023-06-21T20:03:42.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CZzeBaRzWvo34V5W.png" /><figcaption>Vector Search pipeline</figcaption></figure><p><em>· </em><a href="#331e"><em>Introduction to Neural Networks Embeddings</em></a><em><br> ∘ </em><a href="#e369"><em>Recap of basics</em></a><em><br> ∘ </em><a href="#d51d"><em>What is Embedding?</em></a><em><br> ∘ </em><a href="#dc11"><em>Intuitive Explanation</em></a><em><br> ∘ </em><a href="#2477"><em>Why embeddings?</em></a><em><br> ∘ </em><a href="#1e80"><em>Various Applications of Embeddings</em></a><em><br>· </em><a href="#5788"><em>Vector search</em></a><em><br> ∘ </em><a href="#a20d"><em>Concept</em></a><em><br> ∘ </em><a href="#6f35"><em>What if data is huge?</em></a><em><br>· </em><a href="#bdb6"><em>HNSW gentle introduction</em></a><em><br> ∘ </em><a href="#2f67"><em>Probability Skip List</em></a><em><br> ∘ </em><a href="#003e"><em>Navigable Small World Graphs</em></a><em><br> ∘ </em><a href="#2460"><em>Creating HNSW</em></a><em><br> ∘ </em><a href="#9130"><em>Graph Construction</em></a><em><br> ∘ </em><a href="#e0c6"><em>Vector databases and frameworks overview</em></a><em><br>· </em><a href="#1a4c"><em>Conclusion</em></a><em><br> ∘ </em><a href="#ccb8"><em>Links</em></a></p><h3>Introduction to Neural Networks Embeddings</h3><p>This article aims to shed some light on vector search magic and may be helpful for anyone who is not well-versed in the current vector hype. This article can be particularly useful for developers who work with this technology in their companies and wish to gain a better understanding of its functioning.</p><h4>Recap of basics</h4><p>The concept of embeddings and vector search heavily relies on the Neural Network concept and its terminology. To comprehend this topic, it is essential to have a basic understanding of vectors, matrix operations, model weights and biases, as well as loss functions. If these ideas are unfamiliar to you, I recommend reading a brilliant <a href="https://towardsdatascience.com/the-basics-of-neural-networks-neural-network-series-part-1-4419e343b2b">article</a> that covers the basics of Neural Networks.</p><p>In the real world, this example would involve much more complex architectures and training strategies. Our data could be far more unstructured than a simple array of numbers, encompassing various formats such as images, text, audio, graphs, and multimodal structures. Not all layers in a Neural Network are as simple as the one given, and the output data could also be very complex, so are the loss functions for different tasks. The NN architectures itself may range from being as simple as the one mentioned above to being extremely huge, involving billions of trainable parameters. However, the underlying principle remains the same.</p><p><strong>In simple terms, training a Neural Network means finding the optimal weights that yield the best predictions for a given input.</strong></p><h4>What is Embedding?</h4><p>Now, let’s assume that we have trained a Neural Network for our task. During the prediction stage, we feed data to our model, which passes through the network layer-by-layer. As the input data passes through each layer, it undergoes transformations and transitions into a new vector space. This transformed data is referred to as an <strong>embedding</strong>.</p><p>To provide a clearer definition, an <strong>embedding</strong> is a relatively low-dimensional space into which you can translate high-dimensional vectors. Embeddings make it easier to do machine learning on large inputs like sparse vectors representing words. Ideally, an embedding captures some of the semantics of the input by placing semantically similar inputs close together in the embedding space. An embedding can be learned and reused across models.</p><p>In general, any intermediate data representation within the neural network could be referred to as an embedding, but typically we focus on the last flattened layer of the network, excluding task-specific model prediction head (like task-specific classification head, for example). Therefore, if we perceive the network as a black box function, it operates in the following manner:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*5Nn-OTASASult9Bs.jpg" /><figcaption>Input data → Black box NN as embedding model → low-dimensional vector (embedding) representing our input data</figcaption></figure><h4>Intuitive Explanation</h4><p>Normally, embeddings are saved as vectors. Each vector has its own position in vector space <strong>and the neighbour points are more similar to each other and thus should be classified into the same groups. </strong>This phenomenon, often referred to as “semantic proximity,” is a desirable property of embeddings. It means that words, images or other input data with related meanings or similar information tend to be located in close proximity in the embedding space. For example, the embeddings of “cat” and “dog” are expected to be closer to each other compared to the embeddings of “cat” and “car.” The reason similar embeddings represent similar objects is that the training algorithm captures and encodes the inherent relationships and similarities present in the training data. Therefore, we tend to use embeddings for community detection or group clustering with the help of cosine similarity. And it is generally used in classification tasks as well.</p><p>To illustrate the idea mentioned above, what we can do is use dimension deduction techniques (PCA, UMAP, etc.) to reduce the size of the high dimensional vectors to 2D/3D and draw the points on a plot. Here is a blog that specifically shows you how to achieve that in a 3D space:</p><p><a href="https://towardsdatascience.com/visualize-high-dimensional-network-data-with-3d-360-degree-animated-scatter-plot-d583932d3693">Visualize High-Dimensional Network Data with 3D 360-Degree-Animated Scatter Plot</a></p><h4>Why embeddings?</h4><p>Ok, now we see what actually are embeddings, but why do we need them. The most important point in this concept is that <strong>embedding is a valid vector representation of your data.</strong></p><p>First, current <strong>machine learning models continue to favour numerical values as inputs</strong>. However, when researching computer vision or voice recognition, we are unlikely to be able to collect or only collect numerical data for our targets/dependent variables.</p><p>Second, it helps <strong>reduce dimensions</strong>. Someone may argue that the one-hot-encoding technique is how we handle categorical variables. However, in today’s data science world, it has proven to be much less effective.</p><p>Yet, consider the following scenario: we are researching consumer feedback for three products. We would only have one variable for each observation — the review content. We can build a term-document matrix and then put it into a classifier or some other algorithms. However, let’s suppose we have 50 thousand reviews for each product, and the number of total unique words in the corpus is one million. Then we will end up with a matrix whose shape is (150K x 1M). This is a ridiculously large input for any model. And that is when we need to bring in the idea of embedding.</p><p>The third reason is to <strong>reduce complexity</strong>. It is kind of like the extension of the second reason. Embedding also can help translate very complex information into a vector of numbers. Here is an example of social network analysis:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k2lCeNTofI_mH88Fry44Sw.png" /><figcaption>Converting graph to an embedding</figcaption></figure><p>Initially, we collected the data from social media and converted it into a social network analysis graph. In the graph, we can use the distance between the nodes and the color of the ties to interpret the similarities between the nodes. However, it is complicated and hard to read. Right now, we only have 9 nodes in the graph, and it is already a mess. Can you imagine what would happen if we were to investigate 100 nodes? This is referred to as complex (high-dimensional) data. However, by using certain techniques to aid in dimensionality reduction, we can transform the graph into a list of embeddings. As a result, instead of the jumbled graph, we now have a new, clean “dictionary” for the nodes. We can use the “dictionary” to make a human-readable visualisation.</p><h4>Various Applications of Embeddings</h4><p>You must have been excited to see some popular applications of embeddings after discovering what it is. In real world tasks, we usually have different NN architectures for different data types and tasks. Here are just couple of basic network architectures that are widely implemented today and often used as a backbone for a more specific networks or for extracting embeddings from data:</p><ul><li><strong>Natural Language Processing</strong>: <a href="https://paperswithcode.com/method/bert">BERT</a> (<a href="https://towardsdatascience.com/bert-explained-state-of-the-art-language-model-for-nlp-f8b21a9b6270">explained</a> here)</li><li><strong>Computer Vision: </strong><a href="https://paperswithcode.com/method/resnet">ResNet</a> (<a href="https://towardsdatascience.com/introduction-to-resnets-c0a830a288a4">explained</a> here)</li><li><strong>Social Network Analysis: </strong><a href="https://paperswithcode.com/method/gcn">GCN</a> (<a href="https://towardsdatascience.com/graph-convolutional-networks-explained-d88566682b8f">explained</a> here)</li></ul><h3>Vector search</h3><h4>Concept</h4><p>Now, let’s assume that we have a general understanding of how Neural Networks work and how to transform our input data into low-dimensional vectors. Let’s consider how we can apply this knowledge to a real-world problem, such as a text-image search task. To clarify, the objective is to provide our users with a list of the most relevant images based on a given text query.</p><p>The first and most obvious approach would be to treat this task as a classification problem. Each text query would represent a different class, and for each image, we would aim to predict the probability of it corresponding to a particular class (request).</p><p>If we have a limited and consistent categorisation map, it would be a simple and efficient solution. However, what if we have huge number of classes? Or if we are unaware of all the potential classes? In some cases, a user’s request may be entirely unique, leaving us with the following options:</p><ul><li>Retraining the model with a new class (which is impossible if there are numerous classes)</li><li>Utilising a “similar” class instead of the exact request (although this may result in a decrease in quality)</li><li>Use an alternative method</li></ul><p>The idea is to move away from the setup of a classification task and instead focus on the last layer embeddings of the Neural Network. As we know, if properly trained, these embeddings can represent aggregated data information in a low-dimensional vector space. Therefore, the concept is to obtain image embeddings for the images and obtain text embeddings of the same size for the request text. The goal is to determine if they are similar or not.</p><p>However, a challenge arises because <strong>the vector spaces for these two types of embeddings are not the same</strong>. Even if two similar images have close image embeddings and two similar requests have close text embeddings, it does not necessarily mean that the image and text embeddings will be close when the request is relevant to the image. Hence, our task is to design a joint model that can be trained to transform both types of input data into a joint vector space. In this vector space, the input request should be close to a relevant image based on a similarity measure such as cosine distance.</p><p>To train such a NN, special loss functions like Contrastive Loss are utilised. This loss function is calculated for each request-image pair used in training. For a more in-depth understanding of Contrastive Loss and its alternatives, I invite you to refer to my previous <a href="https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-1-6310a4e5476">article</a>.</p><p>Alright, let’s now consider the scenario where we have trained such a model. At this point, our embeddings are close for images that are relevant to users’ requests, based on a certain measure.</p><p>Now, if we have a database filled with numerous images, we could calculate the embeddings of all of these images. Additionally, we can calculate the embedding of an input request. By computing the cosine similarity between the input request embedding and the embeddings of each image, we can identify the most similar images based on the measure used. <strong>This approach would certainly work well for a small number of images</strong>.</p><p>However, what if we are dealing with a database containing billions of images and we require our recommendations to be real-time?</p><h4>What if data is huge?</h4><p>If you need to calculate cosine similarity between 128-dim request embedding and 4 billions of 128-dim image embeddings it will require 256 operation for each image and around <em>10**12</em> operations or around 6 minutes for hypothetical 3GHZ processor. Seems a lot and definitely not real time… So what to do? Let’s find out how not to compare request embedding with all embeddings in database.</p><p>There are lots of different approximate search algorithms, but here will cover briefly HNSW or Hierarchical Navigable Small World algorithm, which now appears to be an industry standard for large-scale vector search. It has many different variations and is implemented in many search frameworks such as QDrant, Pinecone, Milvus and others.</p><h3>HNSW gentle introduction</h3><h4>Probability Skip List</h4><p>The probability skip list was introduced way back in 1990 by William Pugh. It allows fast search like a sorted array, while using a linked list structure for easy (and fast) insertion of new elements.</p><p>Skip lists work by building several layers of linked lists. On the first layer, we find links that <em>skip</em> many intermediate nodes/vertices. As we move down the layers, the number of <em>skips</em> by each link is decreased.</p><p>To search a skip list, we start at the highest layer with the longest <em>skips</em> and move along the edges towards the right (below). If we find that the current node key is greater than the key we are searching for — we know we have overshot our target, so we move down to previous node in the next level.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xO7vuzqJob_VQtYWH6rgjA.png" /><figcaption>Skip list (image by Pinecone)</figcaption></figure><p>HNSW inherits the same layered format with longer edges in the highest layers (for fast search) and shorter edges in the lower layers (for accurate search).</p><h4>Navigable Small World Graphs</h4><p>Vector search using Navigable Small World (NSW) graphs was introduced over the course of several papers from 2011 to 2014. The idea is that if we take a proximity graph but build it so that we have both long-range and short-range links, then search times are reduced to logarithmic complexity.</p><p>Each vertex in the graph connects to several other vertices. We call these connected vertices <em>friends</em>, and each vertex keeps a <em>friend list</em>, creating our graph.</p><p>When searching an NSW graph, we begin at a pre-defined <em>entry-point</em>. This entry point connects to several nearby vertices. We identify which of these vertices is the closest to our query vector and move there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uihfVLzds8saouv5y4s-QA.png" /><figcaption>NSW graph example (image by Pinecone)</figcaption></figure><p>We repeat the <em>greedy-routing search</em> process of moving from vertex to vertex by identifying the nearest neighbouring vertices in each friend list. Eventually, we will find no nearer vertices than our current vertex — this is a local minimum and acts as our stopping condition.</p><p>Our <em>stopping condition</em> is finding no nearer vertices in our current vertex’s friend list. Because of this, we are more likely to hit a local minimum and stop too early when having fewer links (less likely to find a nearer vertex).</p><p>To minimise the probability of stopping early (and increase recall), we can increase the average degree of vertices, but this increases network complexity (and search time). So we need to balance the average degree of vertices between recall and search speed.</p><h4>Creating HNSW</h4><p>HNSW is a natural evolution of NSW, which borrows inspiration from hierarchical multi-layers from Pugh’s probability skip list structure.</p><p>Adding hierarchy to NSW produces a graph where links are separated across different layers. At the top layer, we have the longest links, and at the bottom layer, we have the shortest.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dbtRIczdyH593lbfhNF_Vg.png" /><figcaption>Spreading nodes of HNSW graph over different layers (image by Pinecone)</figcaption></figure><p>During the search, we enter the top layer, where we find the longest links.</p><p>We traverse edges in each layer just as we did for NSW, greedily moving to the nearest vertex until we find a local minimum. Unlike NSW, at this point, we shift to the current vertex in a lower layer and begin searching again. We repeat this process until finding the local minimum of our bottom layer — layer 0.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MhmQsaEaZYSeH7zwUTW_Yg.png" /><figcaption>HNSW search algorithm visualisation (image by Pinecone)</figcaption></figure><h4>Graph Construction</h4><p>Nodes in HNSW are inserted sequentially one by one. Every node is randomly assigned an integer <em>l</em> indicating the maximum layer at which this node can present in the graph. For example, if <em>l = 1</em>, then the node can only be found on layers 0 and 1. The authors select <em>l</em> randomly for each node with an <em>exponentially decaying probability distribution </em>normalised by the non-zero multiplier <em>mL (mL = 0 </em>results in a single layer in HNSW and non-optimized search complexity<em>)</em>. Normally, the majority of <em>l</em> values should be equal to 0, so most of the nodes are present only on the lowest level. The larger values of <em>mL</em> increase the probability of a node appearing on higher layers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wTDPCe4Ta7LnZz9l.png" /><figcaption>L — number of layers, l — maximum layer at which this node can present in the graph</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y-flDPgkiv-dNMzHvMvZtg.png" /><figcaption>Choosing a layer for a new node (image by Pinecone)</figcaption></figure><p>Graph construction starts at the top layer. After entering the graph the algorithm greedily traverse across edges, finding the <em>ef</em> nearest neighbors to our inserted vector <em>q</em> — at this point <em>ef = 1</em>.</p><p>After finding the local minimum, it moves down to the next layer (just as is done during search). This process is repeated until reaching our chosen <em>insertion layer (l)</em>. Here begins phase two of construction.</p><p>The <em>ef</em> value is increased to <em>ef_construction</em> (a parameter we set), meaning more nearest neighbours will be returned. In phase two, these nearest neighbours are candidates for the links to the new inserted element <em>q</em> and as entry points to the next layer.</p><p><em>M</em> neighbors are added as links from these candidates — the most straightforward selection criteria are to choose the closest vectors. After working through multiple iterations, there are two more parameters that are considered when adding links. <em>Mₘₐₓ</em>, which defines the maximum number of links a vertex can have, and <em>Mₘₐₓ₀</em>, which defines the same but for vertices in <em>layer 0</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_DLlMa0Kl5ZSEC0h38PNFA.png" /><figcaption>Rebuilding HNSW graph vertices after adding a new node (image by Pinecone)</figcaption></figure><p>The insertion stopping condition is reaching the local minimum in <em>layer 0</em>.</p><h4>Vector databases and frameworks overview</h4><p>Most of today’s vector search solutions incorporate implementations of HNSW or similar algorithms. Here is a brief list of the most popular solutions and their algorithms:</p><ul><li>QDrant: <a href="https://github.com/qdrant/qdrant/tree/master/lib/segment/src/index/hnsw_index">Custom</a> HNSW implementation in Rust.</li><li>Milvus: Allows multiple ANN algorithm based indexes: FAISS, ANNOY, HNSW, RNSG.</li><li>Pinecone: Exact KNN powered by FAISS; ANN powered by proprietary algorithm. All major distance metrics are supported: cosine (default), dot product and Euclidean.</li><li>Vespa: HNSW (modified for realtime CRUD and metadata filtering); a suite of <a href="https://docs.vespa.ai/en/ranking.html">reranking</a> and dense retrieveal methods.</li><li>Weaviate: custom-implemented HNSW, tuned to scale, and to support full CRUD. The system supports <a href="https://www.semi.technology/developers/weaviate/current/vector-index-plugins/#can-weaviate-support-multiple-vector-index-ann-plugins">plug-in</a> ANN algorithms as long as they can do CRUD.</li><li>Vald: Based on the fastest algorithm: <a href="https://github.com/yahoojapan/NGT">NGT</a>, which is faster than many strong algorithms, such as Scann and HNSW.</li></ul><p>Take a look at a brilliant <a href="https://towardsdatascience.com/milvus-pinecone-vespa-weaviate-vald-gsi-what-unites-these-buzz-words-and-what-makes-each-9c65a3bd0696">article</a> written by Dmitri Khan comparing most of current solutions.</p><p>Benchmarks could also be helpful:</p><ul><li><a href="https://qdrant.tech/benchmarks/">https://qdrant.tech/benchmarks/</a></li><li><a href="https://jina.ai/news/benchmark-vector-search-databases-with-one-million-data/">https://jina.ai/news/benchmark-vector-search-databases-with-one-million-data/</a></li><li><a href="https://github.com/qdrant/vector-db-benchmark">https://github.com/qdrant/vector-db-benchmark</a></li></ul><p>Some vector databases like QDrant also allow you to combine vector search with additional filtering, which might be crucial if you need to get best result not over the whole data but in some part of it. For example, if you want to filter most relevant images for request posted during last month.</p><h3>Conclusion</h3><p>Hope this article will help to shed some light on the vector search concept, algorithms, practical application and usage.</p><p>Stay safe!</p><h4>Links</h4><ul><li><a href="https://www.pinecone.io/learn/hnsw/">https://www.pinecone.io/learn/hnsw/</a></li><li><a href="https://towardsdatascience.com/the-basics-of-neural-networks-neural-network-series-part-1-4419e343b2b">https://medium.com/r/?url=https%3A%2F%2Ftowardsdatascience.com%2Fthe-basics-of-neural-networks-neural-network-series-part-1-4419e343b2b</a></li><li><a href="https://towardsdatascience.com/similarity-search-part-4-hierarchical-navigable-small-world-hnsw-2aad4fe87d37">https://towardsdatascience.com/similarity-search-part-4-hierarchical-navigable-small-world-hnsw-2aad4fe87d37</a></li><li><a href="https://qdrant.tech/benchmarks/">https://qdrant.tech/benchmarks/</a></li><li><a href="https://jina.ai/news/benchmark-vector-search-databases-with-one-million-data/">https://jina.ai/news/benchmark-vector-search-databases-with-one-million-data/</a></li><li><a href="https://github.com/qdrant/vector-db-benchmark">https://github.com/qdrant/vector-db-benchmark</a></li><li><a href="https://towardsdatascience.com/milvus-pinecone-vespa-weaviate-vald-gsi-what-unites-these-buzz-words-and-what-makes-each-9c65a3bd0696">https://medium.com/r/?url=https%3A%2F%2Ftowardsdatascience.com%2Fmilvus-pinecone-vespa-weaviate-vald-gsi-what-unites-these-buzz-words-and-what-makes-each-9c65a3bd0696</a></li><li><a href="https://towardsdatascience.com/visualize-high-dimensional-network-data-with-3d-360-degree-animated-scatter-plot-d583932d3693">https://medium.com/r/?url=https%3A%2F%2Ftowardsdatascience.com%2Fvisualize-high-dimensional-network-data-with-3d-360-degree-animated-scatter-plot-d583932d3693</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc6e54e34907" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building multimodal image search with Pytorch (part 2)]]></title>
            <link>https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-2-5923e20b296a?source=rss-c98d7807594f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5923e20b296a</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[multimodal]]></category>
            <category><![CDATA[vector-search]]></category>
            <category><![CDATA[image-search]]></category>
            <category><![CDATA[deep-learning]]></category>
            <dc:creator><![CDATA[Mikhail Korotkov]]></dc:creator>
            <pubDate>Fri, 12 May 2023 10:32:24 GMT</pubDate>
            <atom:updated>2023-06-18T18:40:11.944Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*vkBM9WQWhtlifxPA" /><figcaption>Modified Scene Text Aware Cross Modal Retrieval architecture (MStacMR)</figcaption></figure><h3>Recap</h3><p>In <a href="https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-1-6310a4e5476">Part 1</a> of this article we have discussed cross-modal retrieval task setup, CTC dataset and Loss functions that can be helpful for this setup. In Part 2 we will dive deeper into separate blocks architecture and show how it could be applied for a real world application. In this part we will use <a href="https://arxiv.org/abs/2012.04329">StacMR</a> paper as a baseline and change several blocks to make the whole pipeline better in terms of quality and performance.</p><p>We will start easy with Caption Encoder which will remain similar to original version and then move to new Image Encoder architecture, new OCR block, recap of GCN architecture (for image regions), additional Image Captioning head for better quality and finish with resulting metrics and brief search implementation architecture.</p><h3>Caption Encoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-egjXE_JdBNw8qfN5TSdyA.png" /><figcaption>LSTM and GRU blocks</figcaption></figure><p>The goal of caption encoder is to generate image description embeddings in the same vector space with image embeddings. For example, we can use simple GRU model to aggregate text information into one description embedding.</p><p>We first remove stop-words from captions and scene-text annotations and encode each remaining word with Word2Vec vectors trained on Google News dataset. The semantic relevance between two words is defined as the cosine similarity between their Word2Vec embeddings.</p><h3>Image Encoder</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*XiPrugyDH2g-xg8l" /><figcaption>Image encoder</figcaption></figure><p>The aim of the image encoder is to capture the essence of a given image by representing it in a vector space similar to that of image captions. This representation effectively encapsulates most of the important information from the image. To achieve this transformation, we employ the concept of <strong>Bottom Up Attention</strong>. Imagine yourself in an unfamiliar place, like a new restaurant, searching for the restroom. You don’t know exactly what it looks like, so you scan the surroundings, identifying key elements that might guide you towards your goal. Similarly, we identify salient regions in the image without explicitly solving the task at hand.</p><p>In the original approach described in the StacMR paper, the image encoder utilized a <strong>Faster-RCNN</strong> detection model trained on the <strong>Visual Genome Dataset</strong> to detect 200 classes of objects. Its purpose was to extract visual features from all regions of interest. These features were then processed through GCN layers to connect information from different salient regions, and a GRU block was used to aggregate the information into a unified embedding.</p><p>However, we have identified a few limitations in this image encoder architecture, and we propose the following improvements:</p><ol><li>Replacing Faster-RCNN with YoloV5 for faster region-of-interest detection.</li><li>Training the YoloV5 model to detect objects belonging to 500 main classes from the Visual Genome Dataset (unlike 200 classes in original paper)</li><li>Create full inference pipeline, addressing the absence of a proper inference pipeline in the original model, which relied on precomputed embeddings.</li><li>Instead of directly using region embeddings from the last layer of Faster-RCNN, we now independently crop and process each detected region using the Visual Transformer (ViT32) employed in CLIP. This results in region embeddings.</li><li>We still utilize GCN to aggregate the embeddings from different regions.</li><li>Replace GRU block with average pooling, which offers a more efficient approach.</li></ol><p>Taking a step back to observe the revised pipeline, it begins with the <strong>YoloV5</strong> object detector, which identifies <strong>16 salient regions</strong> in each image. These regions are then passed through a <strong>pre-trained ViT32 image encoder</strong>, producing <strong>512-dimensional embeddings</strong> for each region. These embeddings are subsequently processed by the <strong>GCN</strong>, which enhances the representations and generate a single image embedding using average pooling.</p><h3>OCR</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hzJ42maqW7RXCnVJ9RUX_g.png" /><figcaption>Images rich with text information</figcaption></figure><p>Let’s consider a scenario where we have a resource filled with images that contain abundant <strong>scene texts</strong>. It is highly likely that utilising this textual information can be extremely beneficial.</p><p>In real-world data, we frequently come across images that contain important text information. Surprisingly, this textual content sometimes surpasses the visual aspects in terms of significance. Therefore, it becomes an intriguing idea to introduce an additional modality to our model. The goal of this model architecture is to investigate whether incorporating scene text features can improve our model’s understanding of images and enable more effective searches. To achieve this, we will create an OCR (Optical Character Recognition) branch that works alongside the image encoder, generating image scene text embeddings.</p><p>As it often occurs in real data some images contain important text information which could be even more important than visual so it could be a good idea to add another modality for our model. The goal of this model architecture is to find whether adding scene text features would help our model to get more information from image and perform better search. For this purpose we will build additional OCR branch that will run in parallel with image encoder to build image scene text embedding if such text exists.</p><p>If we revisit the original StacMR paper, the authors introduced this additional modality using the <strong>Google OCR API</strong>. However, let’s consider the advantages of developing our own custom model, one that we can manage, refine, and seamlessly implement in real-world applications. The utilisation of external APIs, such as the Google OCR API, may pose certain challenges. It can lead to controversies when integrating it into our own applications, and changes in API versions might hinder result reproducibility. Moreover, it can be costly for small startups or incompatible with sensitive private data. If our objective is to create an independent, reproducible, and easily deployable pipeline, choosing a custom OCR solution is a preferable option.</p><p>In this scenario, we utilize the open-source <strong>Keras-OCR</strong> (which will not be covered in this article). However, you have the flexibility to choose any custom OCR solution to extract text from the image. Following that, you will require a model to encode the detected text sequences, similar to how we encoded image regions using ViT32. We will use MUSE (<a href="https://tfhub.dev/google/universal-sentence-encoder-multilingual/3">Google MultiLingual Sentence Encoder</a>), but you can use any other sentence encoder as well.</p><h3>GCN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JueMQL_kPZjDM6q9w2LZnQ.png" /><figcaption>GCN</figcaption></figure><p>If you are familiar with <a href="https://machinelearningmastery.com/convolutional-layers-for-deep-learning-neural-networks/">convolution layers in Convolutional Neural Networks</a>, ‘convolution’ in <strong>GCN</strong>s (Graph Convolutional Network) is basically the same operation. It refers to multiplying the input neurons with a set of weights that are commonly known as filters or kernels<em>. </em>The filters act as a sliding window across the whole image and enable <strong>CNN</strong>s to learn features from neighbouring cells. Within the same layer,<em> </em>the same filter will be used throughout image, this is referred to as <strong>weight sharing</strong>. For example, using CNN to classify images of cats vs non-cats, the same filter will be used in the same layer to detect the nose and the ears of the cat.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*do3ulMin_hWPqLSw.png" /><figcaption>The same weight (or kernel, or filter in CNNs) is applied throughout the image</figcaption></figure><p>GCNs perform similar operations where the model learns the features by inspecting neighbouring nodes. The major difference between CNNs and GCNs is that CCNs are specially built to operate on regular (Euclidean) structured data, while GCNs are the generalised version of CNNs where the numbers of nodes connections vary and the nodes are unordered (irregular on non-Euclidean structured data).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/0*fM2wswfXzD7UivqY.png" /><figcaption>Illustration of 2D Convolutional Neural Networks (left) and Graph Convolutional Networks (right), via <a href="https://arxiv.org/pdf/1901.00596.pdf">source</a></figcaption></figure><p>As different detected regions of the image could be represented as different nodes of the graph, we could benefit from that graph structure and use power of Graph neural networks to extract even more information from image date. For both modalities (image and scene text) we use a GCN to obtain richer representations. The inputs to GCN are embeddings with 512-dimensions and 16 regions.</p><pre>import torch<br>from torch import nn<br><br><br>class Rs_GCN(nn.Module):<br>    def __init__(self, in_channels, inter_channels, bn_layer=True):<br>        super(Rs_GCN, self).__init__()<br><br>        self.in_channels = in_channels<br>        self.inter_channels = inter_channels<br><br>        if self.inter_channels is None:<br>            self.inter_channels = in_channels // 2<br>            if self.inter_channels == 0:<br>                self.inter_channels = 1<br><br>        conv_nd = nn.Conv1d<br>        bn = nn.BatchNorm1d<br><br>        self.g = conv_nd(in_channels=self.in_channels,<br>                         out_channels=self.inter_channels,<br>                         kernel_size=1,<br>                         stride=1,<br>                         padding=0)<br><br>        if bn_layer:<br>            self.W = nn.Sequential(<br>                conv_nd(in_channels=self.inter_channels,<br>                        out_channels=self.in_channels,<br>                        kernel_size=1,<br>                        stride=1,<br>                        padding=0),<br>                bn(self.in_channels)<br>            )<br>            nn.init.constant_(self.W[1].weight, 0)<br>            nn.init.constant_(self.W[1].bias, 0)<br>        else:<br>            self.W = conv_nd(in_channels=self.inter_channels,<br>                             out_channels=self.in_channels,<br>                             kernel_size=1,<br>                             stride=1,<br>                             padding=0)<br>            nn.init.constant_(self.W.weight, 0)<br>            nn.init.constant_(self.W.bias, 0)<br><br>        self.theta = None<br>        self.phi = None<br><br>        self.theta = conv_nd(in_channels=self.in_channels,<br>                             out_channels=self.inter_channels,<br>                             kernel_size=1,<br>                             stride=1,<br>                             padding=0)<br>        self.phi = conv_nd(in_channels=self.in_channels,<br>                           out_channels=self.inter_channels,<br>                           kernel_size=1,<br>                           stride=1,<br>                           padding=0)<br><br>    def forward(self, v):<br>        batch_size = v.size(0)<br><br>        g_v = self.g(v).view(batch_size, self.inter_channels, -1)<br>        g_v = g_v.permute(0, 2, 1)<br><br>        theta_v = self.theta(v).view(batch_size, self.inter_channels, -1)<br>        theta_v = theta_v.permute(0, 2, 1)<br>        phi_v = self.phi(v).view(batch_size, self.inter_channels, -1)<br>        R = torch.matmul(theta_v, phi_v)<br>        N = R.size(-1)<br>        R_div_C = R / N<br><br>        y = torch.matmul(R_div_C, g_v)<br>        y = y.permute(0, 2, 1).contiguous()<br>        y = y.view(batch_size, self.inter_channels, *v.size()[2:])<br>        W_y = self.W(y)<br>        v_star = W_y + v<br><br>        return v_star</pre><h3>Additional Image Captioning Model Head</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*udTzX08w1ReVLF2O.jpg" /><figcaption>Encoder Decoder architecture example for machine translations. In our case, we use final visual embeddings features instead of input text sequence.</figcaption></figure><p>In order to provide the model with a stronger supervision signal, the learned image representation is also used to generate a caption as an auxiliary task. We train the third encoder so that the generated caption equals to а given one. This sequence to sequence model uses an attention mechanism and we optimise the log-likelihood of the predicted output caption given the final visual features and the previous generated word.</p><h3>Training</h3><p>Ok, now we have all blocks of the system set, lets recap, what parts of the system we have now and what should be trained using our CTC-5k data.<br>We do have:</p><ul><li>YoloV5 trained to detect 500 classes from Visual Genome dataset.</li><li>ViT32 for embedding cropped image regions, proposed from YoloV5</li><li>Pretrained Keras-OCR and MUSE for OCR branch</li></ul><p>So now to train the whole pipeline jointly, we should freeze OCR branch + first part of Image Encoder (detection regions and embedding them). After that we train GCN blocks, Caption Encoder, Image Captioning block and all other with Triplet Ranking Loss mentioned in previous part.</p><h3>Metrics</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KGaTJ_s0CgnLzunhFiqaqg.png" /><figcaption>Final metrics comparison</figcaption></figure><p>We’ll evaluate our results in terms of Recall@K (R@K). We’ll compare our architecture with StacMR architecture on the same CTC-5k dataset.</p><p>As we could see, adding scene text information to the model could be very crucial for some types of datasets. Also, the final model without GoogleOCR even outperforms initial version mostly by using better image encoder.</p><h3>Implementation</h3><p>Ok, from this moment we know how to convert images and their text captions to some unite vector space, we have the whole pipeline trained and ready to calculate some image vectors for us. Now we can perform some search using this vectors! What do we need for that?</p><p>First of all, we need some similarity measure such as cosine similarity we have discussed in <a href="https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-1-6310a4e5476">Part 1</a>. But computing cosine similarity with every image in the corpus would be very computationally inefficient, especially, if we have huge number of images. At the same time, it might require a huge amount of physical memory to store the vector representation of images.</p><p>To solve this problem, we could take a look at the <strong>HNSW</strong> algorithm (Hierarchical Navigable Small World), which could be extremely helpful when your dataset is huge. To dive deeper into this concept you could take a look at this brilliant <a href="https://towardsdatascience.com/ivfpq-hnsw-for-billion-scale-similarity-search-89ff2f89d90e#57a8">article</a> written by Peggy Chang.</p><p>Going further, HNSW is only an algorithm, so we might need a database to store this vectors and some framework to perform this HNSW algorithm (or you could use vector database with HNSW implemented as some custom version of Approximate KNN search). Vector databases and frameworks solutions are growing rapidly during last couple of years so now we have plenty of interesting solutions from vector search plugins in <strong>ElasticSearch</strong> (AKNN from 8.x version) to modern vector databases such as <strong>Qdrant</strong>, <strong>Milvus</strong>, <strong>Pinecone</strong> or vector frameworks such as <strong>FAISS</strong>. Following example is using ElasticSearch AKNN which is NOT a great solution as it is comparatively slow, but it works well enough to demonstrate the concept.</p><p>You could also use a nice <a href="https://medium.com/towards-data-science/milvus-pinecone-vespa-weaviate-vald-gsi-what-unites-these-buzz-words-and-what-makes-each-9c65a3bd0696">article</a> about different <strong>Vector Databases</strong> written by creator of Vector Podcast <a href="https://medium.com/@dmitry-kan?source=---two_column_layout_sidebar----------------------------------">Dmitry Kan</a>.</p><h4>Get started with approximate k-NN in Elasticsearch</h4><p>To use the KNN plugin’s approximate search functionality, you must first create a KNN index with setting index.knn to true. This setting tells the plugin to create HNSW graphs for the index.</p><p>Additionally, if you are using the approximate k-nearest neighbour method, you should specify knn.space_type to the space that you are interested in. This setting cannot be changed after it is set. To see what spaces we support, please refer to the <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/knn/approximate-knn/#spaces">spaces section</a>. By default, index.knn.space_type is l2. For more information on index settings, such as algorithm parameters that can be tweaked to tune performance, please refer to the <a href="https://opendistro.github.io/for-elasticsearch-docs/docs/knn/settings#index-settings">documentation</a>.</p><p>Next, you must add one or more fields of the knn_vector data type. Here is an example that creates an index with two knn_vector fields and uses cosine similarity:</p><pre>PUT my-knn-index-1<br>{<br>  &quot;settings&quot;: {<br>    &quot;index&quot;: {<br>      &quot;knn&quot;: true,<br>      &quot;knn.space_type&quot;: &quot;cosinesimil&quot;<br>    }<br>  },<br>  &quot;mappings&quot;: {<br>    &quot;properties&quot;: {<br>      &quot;my_vector1&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 2<br>      },<br>      &quot;my_vector2&quot;: {<br>        &quot;type&quot;: &quot;knn_vector&quot;,<br>        &quot;dimension&quot;: 4<br>      }<br>    }<br>  }<br>}</pre><p>The knn_vector data type supports a vector of floats that can have a dimension of up to 10,000, as set by the dimension mapping parameter.</p><p>After you create the index, you can add some data to it:</p><pre>POST _bulk<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;1&quot; } }<br>{ &quot;my_vector1&quot;: [1.5, 2.5], &quot;price&quot;: 12.2 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;2&quot; } }<br>{ &quot;my_vector1&quot;: [2.5, 3.5], &quot;price&quot;: 7.1 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;3&quot; } }<br>{ &quot;my_vector1&quot;: [3.5, 4.5], &quot;price&quot;: 12.9 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;4&quot; } }<br>{ &quot;my_vector1&quot;: [5.5, 6.5], &quot;price&quot;: 1.2 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;5&quot; } }<br>{ &quot;my_vector1&quot;: [4.5, 5.5], &quot;price&quot;: 3.7 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;6&quot; } }<br>{ &quot;my_vector2&quot;: [1.5, 5.5, 4.5, 6.4], &quot;price&quot;: 10.3 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;7&quot; } }<br>{ &quot;my_vector2&quot;: [2.5, 3.5, 5.6, 6.7], &quot;price&quot;: 5.5 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;8&quot; } }<br>{ &quot;my_vector2&quot;: [4.5, 5.5, 6.7, 3.7], &quot;price&quot;: 4.4 }<br>{ &quot;index&quot;: { &quot;_index&quot;: &quot;my-knn-index-1&quot;, &quot;_id&quot;: &quot;9&quot; } }<br>{ &quot;my_vector2&quot;: [1.5, 5.5, 4.5, 6.4], &quot;price&quot;: 8.9 }</pre><p>Then you can execute an approximate nearest neighbor search on the data using the knn query type:</p><pre>GET my-knn-index-1/_search<br>{<br>  &quot;size&quot;: 2,<br>  &quot;query&quot;: {<br>    &quot;knn&quot;: {<br>      &quot;my_vector2&quot;: {<br>        &quot;vector&quot;: [2, 3, 5, 6],<br>        &quot;k&quot;: 2<br>      }<br>    }<br>  }<br>}</pre><p>k is the number of neighbors the search of each graph will return. You must also include the size option. This option indicates how many results the query actually returns. The plugin returns k amount of results for each shard (and each segment) and size amount of results for the entire query. The plugin supports a maximum k value of 10,000.</p><h4>Using approximate k-NN with filters</h4><p>If you use the knn query alongside filters or other clauses (e.g. bool, must, match), you might receive fewer than k results. In this example, post_filter reduces the number of results from 2 to 1:</p><pre>GET my-knn-index-1/_search<br>{<br>  &quot;size&quot;: 2,<br>  &quot;query&quot;: {<br>    &quot;knn&quot;: {<br>      &quot;my_vector2&quot;: {<br>        &quot;vector&quot;: [2, 3, 5, 6],<br>        &quot;k&quot;: 2<br>      }<br>    }<br>  },<br>  &quot;post_filter&quot;: {<br>    &quot;range&quot;: {<br>      &quot;price&quot;: {<br>        &quot;gte&quot;: 5,<br>        &quot;lte&quot;: 10<br>      }<br>    }<br>  }<br>}</pre><h4>Spaces</h4><p>A space corresponds to the function used to measure the distance between 2 points in order to determine the k-nearest neighbours. From the k-NN perspective, a lower score equates to a closer and better result. This is the opposite of how ElasticSearch scores results, where a greater score equates to a better result. To convert distances to ElasticSearch scores, we take 1 / (1 + distance). Currently, the k-NN plugin supports the following spaces:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fVooT46kQzZQ4fLZXpNZug.png" /></figure><h3>Conclusion</h3><p>Building a scalable image search pipeline is a challenging task that demands a thorough comprehension of your specific domain. I trust that this article will assist you in approaching this challenge from a fresh perspective and discovering valuable insights for your own unique solutions. Special thanks to Alexandr Nalitkin and Marina Zavgorodnaya, who also contributed to this project.</p><p>The whole project with datasets, training code and metrics could be found here:</p><ul><li><a href="https://github.com/LiahimRatman/MStacMR">https://github.com/LiahimRatman/MStacMR</a></li></ul><h3>Links</h3><ul><li><a href="https://towardsdatascience.com/understanding-graph-convolutional-networks-for-node-classification-a2bfdb7aba7b">https://towardsdatascience.com/understanding-graph-convolutional-networks-for-node-classification-a2bfdb7aba7b</a></li><li><a href="https://medium.com/towards-data-science/milvus-pinecone-vespa-weaviate-vald-gsi-what-unites-these-buzz-words-and-what-makes-each-9c65a3bd0696">https://medium.com/towards-data-science/milvus-pinecone-vespa-weaviate-vald-gsi-what-unites-these-buzz-words-and-what-makes-each-9c65a3bd0696</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5923e20b296a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building multimodal image search with PyTorch (part 1)]]></title>
            <link>https://medium.com/@ma-korotkov/building-multimodal-image-search-with-pytorch-part-1-6310a4e5476?source=rss-c98d7807594f------2</link>
            <guid isPermaLink="false">https://medium.com/p/6310a4e5476</guid>
            <category><![CDATA[pytorch]]></category>
            <category><![CDATA[contrastive-loss]]></category>
            <category><![CDATA[image-search]]></category>
            <category><![CDATA[triplet-loss]]></category>
            <category><![CDATA[vector-search]]></category>
            <dc:creator><![CDATA[Mikhail Korotkov]]></dc:creator>
            <pubDate>Wed, 25 Jan 2023 22:51:40 GMT</pubDate>
            <atom:updated>2023-01-25T22:51:40.268Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/840/0*K6DiXhf1R44HGoWv" /><figcaption>Cross modal retrieval</figcaption></figure><p>The problem of cross-modal retrieval is becoming more and more popular every day. We mostly use text description to specify our request as it is the most convenient and compact type of information for a human. At the same moment, this test description could be a search request for data of completely different modality like image, video or even more complex structure like Instagram post containing image and text at the same moment.</p><p>Recent models for cross-modal retrieval have benefited from an increasingly rich understanding of visual scenes, afforded by scene graphs and object interactions. This has resulted in an improved matching between the visual representation of an image and the textual representation of its caption. Yet, current visual representations overlook a key aspect: the text appearing in images, which may contain crucial information for retrieval.</p><p>In this article, I will discuss some important aspects of how cross-modal retrieval pipeline could be interpreted and designed and show how to build an example of model for multimodal image retrieval both image-to-text and text-to-image with an extra block for image captioning as well.</p><h3>Text-to-Image search in general</h3><p>As mentioned before, we tackle the problem of multimodal information retrieval. Given one view (image or text), we want to retrieve the most relevant other view from a database. <em>Mathematically, we want to build a system that computes a similarity measure between an image and a text</em>. To do so, we use the machine learning general framework: using a dataset of aligned images and textual descriptions, we try to learn from this dataset a way to compute a similarity between those views.</p><p>For this purpose, we will need:</p><ul><li><strong>Dataset</strong> with image-caption pairs</li><li><strong>Model</strong> <strong>pipeline</strong>, designed to map input data of different modalities to single vector space</li><li><strong>Similarity metric</strong> for computing distance between embeddings</li><li><strong>Loss</strong> for training our pipeline</li><li>Setup for <strong>efficient search</strong> through calculated embeddings</li></ul><p>In this part of the article I will cover the overall task definition from dataset to different types of loss that could be applied and in Part 2 I will dive deeper into certain encoder architectures and search setups.</p><p>Let’s start with the dataset.</p><h3>Dataset</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/968/0*-ykHrBfh1QhTwf_O.png" /></figure><p>We will use the CTC-5k <a href="https://github.com/AndresPMD/StacMR">dataset</a> proposed in paper <a href="https://arxiv.org/abs/2012.04329">StacMR</a> that allows exploration of cross-modal retrieval where images contain scene-text instances. For evaluation purposes, we define two test splits. The first one, which we refer to as CTC-1K, is a subset of CTC explicit. The second test set, CTC-5K, contains the previous 1000 explicit images of CTC-1K plus 4, 000 non-explicit images. The remaining 738 explicit plus 4945 non-explicit images are used for training and validation purposes.</p><h3>Full pipeline architecture</h3><p>You may heard about STARNet (Scene-Text Aware Retrieval Network) model. It is composed of the following modules: a joint encoder for both an image and its scene text, a caption encoder for image caption, and an additional caption generation module.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*2Cw0lH6M8yHoSNIwKvrcMQ.png" /><figcaption>STARNet architecture</figcaption></figure><p>Unfortunately, this architecture possesses several drawback, such as Google API OCR usage, excessive GRU blocks and slow two-stage Faster RCNN detector. Further, we will built similar architecture but avoid Google API OCR module usage as well as avoid usage of precomputed features for image encoder. This will make this pipeline easy to reproduce and improve. We’ll also add more advanced methods for analysing images and text scenes and make the whole pipeline ready for end-to-end inference.</p><p>Talking about cross-modal retrieval in general and text-image retrieval especially the most common method is to transform both entities into similar vector space where similar images and their text captions embeddings will appear close in terms of some distance metrics (like cosine, or euclidean). So, what do we need to create such embeddings?</p><p>Firstly, we will need some encoder for image and some encoder for image caption to convert our data to some vector space. Then we will need some Loss Function to train this embedding pairs to be close for relative captions and distant for irrelevant ones. We may also need another image captioning model head if we want our model to be able to generate captions for a given image.</p><p>That’s how the whole pipeline will look like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*vkBM9WQWhtlifxPA" /><figcaption>Modified Scene Text Aware Cross Modal Retrieval architecture (MStacMR)</figcaption></figure><p>Before diving deeper into certain encoder architectures, lets discuss what types of Loss functions could be applied within such domain, what is Contrastive Loss and Triplet Ranking Loss and how they could be used for cross-modal retrieval.</p><h3>Loss functions for metric-learning</h3><p>Several real-world applications in the industry, ranging from Face Recognition to Object Detection, POS Tagger to Document ranking in NLP, are formulated as a multi-class classification problem. Image retrieval pipeline a first glance looks quite similar to an image classification task where different captions appears as different classes. The most common way dealing with classification task is Softmax function.</p><h4>Softmax</h4><p>The softmax function takes some vector and turn it into numbers in a range of 0 to 1 with the sum of all the numbers equaling 1. One other nice property of softmax is that one of the values is usually much bigger than the others. When calculating the loss for categorical cross-entropy, the first step is to take the softmax of the values, then the negative log of the labeled category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/875/0*b9oPQkGrK16nosy0.png" /><figcaption>Softmax</figcaption></figure><h4>Metric learning</h4><p>Unfortunately, a typical softmax-based deep network wouldn’t help when the number of classes in the output layer is too high because of the sparseness of the network. Rather, this kind of problem can be formulated in a different way. The idea is to learn distributed embeddings representation of data points in a way that in the high dimensional vector space, contextually similar data points are projected in the near-by region whereas dissimilar data points are projected far away from each other.</p><p>In this case the model is trying to solve a <strong>metric learning </strong>problem: to learn some sort of <strong>similarity metric </strong>between images and text captions. The model is trying to reorganise the input space, pull the similar images and texts together in some form of a cluster while pushing dissimilar pairs away.</p><h4>Similarity metric</h4><p>In order to measure how similar two vectors are to each other, we need a way of measuring distance. In 2 or 3 dimensions the euclidian distance is a great choice for measuring the distance between two points. However, in a large dimensional space, all points tend to be far apart by the euclidian measure. In higher dimensions, the angle between vectors is a more effective measure. The cosine distance measures the cosine of the angle between the vectors. The cosine of identical vectors is 1 while orthogonal and opposite vectors are 0 and -1 respectively. More similar vectors will result in a larger number. Calculating the cosine distance could be done by taking the dot product of the vectors.</p><p>So then, some special loss (like Contrastive, Triplet or other) takes the output of the network as a positive example and calculates its distance to an example of the same class and contrasts that with the distance to negative examples. Said another way, the loss is low if positive samples are encoded to similar (closer) representations and negative examples are encoded to different (farther) representations.</p><h3>Contrastive Loss</h3><p>The general formula for Contrastive Loss is shown at Fig. 1.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OeYxe9n_ohq3Wc7h.png" /><figcaption>Figure 1 — Generalised Contrastive Loss</figcaption></figure><p>Y<strong> </strong>term here specifies, whether the two given data points (<strong><em>X₁ </em></strong>and<strong><em> X₂</em></strong>) are similar (<strong><em>Y = 0</em></strong>) or dissimilar (<strong><em>Y = 1</em></strong>). The <strong><em>Ls</em></strong> term in Fig. 1 stands for the loss function, which should be applied to the output if the given samples are similar, the <strong><em>Ld</em></strong> term — a loss function to apply, when the given data points are dissimilar. The <strong><em>Dw</em> </strong>term is the <strong>similarity </strong>(or, rather, dissimilarity) between 2 transformed data points, given by Le Cunn like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*2KpjnHbuYOy_GHsF.png" /><figcaption>Figure 2 — Distance measure between transformed data points</figcaption></figure><p>The <strong>G</strong> in this formula stands for the mapping function itself — i.e. a Neural Network in our case. This is a regular Euclidean distance function (calculated between outputs of the Neural Network), which was used by Le Cunn in the paper — however you can use other similarity metrics like Manhattan distance, Cosine similarity, etc.</p><p>The formula in Fig. 1 is highly reminiscent of the Cross-entropy loss — it has the same structure. The difference is that Cross-entropy loss is a classification loss which operates on class probabilities produced by the network independently for each sample, and Contrastive loss is a metric<strong> </strong>learning loss, which operates on the data points produced by network and their positions relative to each other. This is also part of the reason a cross-entropy loss is not usually used for metric learning tasks like Face Verification — it doesn’t impose any constraints on the distribution on the model’s inner representation of the given data — i.e. the model can learn any features regardless of whether similar data points would be located closely to each other or not after the transformation.</p><p>The exact loss function Le Cunn came up with is presented in Fig. 3.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RRSBU0UzWBb-hsdQ.png" /><figcaption>Figure 3 — Actual Contrastive Loss function</figcaption></figure><p>So <strong><em>Ls</em></strong> (loss for similar data points) is just <strong><em>Dw</em></strong>, distance between them, if two data points are labeled as similar, we will minimise the euclidean distance between them. <strong><em>Ld</em></strong>, on the other hand, needs some explanation. One may think that for two dissimilar data points we just need to <em>maximise distance between them</em> — i.e. minimise<strong> </strong>something like <strong><em>1/Dw</em></strong>. But why didn’t Le Cunn just use <strong><em>1/Dw</em></strong>?</p><p>Time for a little visualisation. Let’s say we have some data point (blue dot) and a couple of other data points, which are similar to it (black dots) and dissimilar (white dots) on Fig. 4. We would naturally like to pull black dots closer to the blue dots and push white dots farther away from it. Specifically, we would like to <em>minimise the intra-class distances </em>(blue arrows) and <em>maximise the inter-class distances </em>(red arrows)<em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/0*bdY9U0zAvBsX6bDh.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/748/0*jskgLYlm-qWGsLdA.png" /><figcaption>Figure 4 — What we would like the algorithm to do. Notice how the white dots that were outside weren’t moved farther away from the margin.</figcaption></figure><p>What we would like to achieve is to make sure that for each group of similar points (in case of Face Recognition task it would be all the photos of the same person) the <em>maximum intra-class distance </em>is smaller<strong> </strong>than the <em>minimum inter-class distance</em>. What this means is that if we define some radius <strong><em>m</em></strong> (<em>margin</em>), all the black dots should fall inside of this margin, and all the white dots — outside (Fig. 4). This way we would be able to use a nearest neighbour algorithm for new data — if a new data point lies within <strong><em>m</em></strong> distance from other, they are similar (belong to same group). The same goes for Face Recognition — if a new face image is located within <strong><em>m</em></strong> distance from another, there is likely the same person on both of them.</p><p>So we need to make sure that black dots are inside the margin <strong><em>m</em></strong>, and white dots are outside of it. And that’s exactly what the function proposed by Le Cunn does! In Fig. 5 you see, that the right part of the loss penalises the model for dissimilar data points having the distance between them <strong><em>Dw &lt;</em></strong> <strong><em>m</em></strong>. If <strong><em>Dw ≥ m</em></strong>, the <strong><em>m-Dw</em></strong> expression is negative and the whole right part of the loss function is thus 0 due to <strong><em>max()</em></strong> operation — and the gradient is also 0, i.e. we don’t force the dissimilar points farther away than necessary.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /><figcaption>Figure 5 — Again, the loss function itself, so that you don’t have to scroll back.</figcaption></figure><h4>Siamese network model architecture</h4><p>Usage of Contrastive Loss leads us to a model architecture that is often called a Siamese Network. (Fig. 6):</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*b31hiO4ynbDLRrXWEFF4aQ.png" /><figcaption>Figure 6 — Siamese network architecture</figcaption></figure><p>For the same Face Verification task you have a convolutional neural network that gets applied to 2 images, then loss is calculated on its outputs and then the back-propagation algorithm is run.</p><p>Called a siamese architecture, it consists of two copies of the function <strong><em>Gw</em> </strong>which share the same set of parameters <strong><em>w</em></strong>, and a cost module. A loss module whose input is the output of this architecture is placed on top of it. The input to the entire system is a pair of images <strong><em>(X₁, X₂)</em></strong> and a label <strong><em>Y</em> </strong>. The images are passed through the functions, yielding two outputs <strong><em>G(X₁)</em></strong> and <strong><em>G(X₂)</em></strong>. The cost module then generates the distance <strong><em>Dw(Gw(X₁), Gw(X₂))</em></strong>. The loss function combines <strong><em>Dw</em></strong> with label <strong><em>Y</em> </strong>to produce the scalar loss <strong><em>Ls</em> </strong>or <strong><em>Ld</em></strong>, depending on the label <strong><em>Y</em> </strong>. The parameter <strong><em>w</em> </strong>is updated using stochastic gradient. The gradients can be computed by back-propagation through the loss, the cost, and the two instances of <strong><em>Gw</em> </strong>. The total gradient is the sum of the contributions from the two instances.</p><h4>Contrastive Loss Summary</h4><ol><li>Contrastive Loss is a <strong>metric learning loss function</strong> introduced by Yann Le Cunn in 2005</li><li>It operates on pairs of embeddings received from the model and on the ground-truth similarity flag — a boolean label, specifying whether these two samples are <strong>similar</strong> or <strong>dissimilar</strong>. So the input must be not one, but 2 data points (images / image-text pair or other)</li><li>It penalises samples for being far from each other in terms of <strong>similarity metric</strong> (Euclidean distance, cosine similarity or other distance metric)</li><li>Dissimilar samples are penalised by being too close to each other, but in a somewhat different way — Contrastive Loss introduces the concept of <strong>margin</strong> — a minimal distance that dissimilar points need to keep. So it penalises dissimilar samples for beings closer than the given margin.</li><li>It can be also applied to cross-modal retrieval task in the following way:</li></ol><ul><li>Train the model on image + caption pairs from the given dataset using captions from given images as positive examples and from different images as negative ones.</li><li>If you want to verify wether some caption is relevant to some image you can at first calculate the embedding of the given image and the embedding of the caption that you are trying to associate with that image.</li><li>Then, calculate the distance between these 2 embeddings (using the same metric you used during training)</li><li>If the distance is smaller than the margin specified during training, these are likely the images relevant to this request, otherwise not.</li><li>If you want to find the most relevant image to given text caption you could sort all image embeddings in database by similarity metric and take most relevant (close by distance) results.</li></ul><p>Contrastive loss, like triplet and magnet loss, is used to map vectors that model the similarity of input items. These mappings can support many tasks, like unsupervised learning, one-shot learning, and other distance metric learning tasks.</p><h3>Triplet Ranking Loss</h3><p>Triplet Loss relies on similar concept but could be even more effective</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*_zVhb118NxpRcSqd.png" /></figure><p>Triplet Loss was first introduced in <a href="https://arxiv.org/abs/1503.03832">FaceNet: A Unified Embedding for Face Recognition and Clustering</a> in 2015, and it has been one of the most popular loss functions for supervised similarity or metric learning ever since. In its simplest explanation, Triplet Loss encourages dissimilar pairs to be distant from any similar pairs by at least a certain margin value. Mathematically, the loss value can be calculated as:</p><blockquote><strong>Triplet Loss</strong><strong><em> = max(Dw(a, p) - Dw(a, n) + m, 0)</em></strong></blockquote><p>where:</p><ul><li><strong><em>p </em></strong>(<em>positive</em>), is a sample that has the same label as <strong><em>a</em></strong> (<em>anchor</em>),</li><li><strong><em>n </em></strong>(<em>negative</em>), is another sample that has a label different from <strong><em>a</em></strong>,</li><li><strong><em>Dw </em></strong>is a function to measure the distance between these three samples,</li><li>and <strong><em>m</em></strong> is a margin value to keep negative samples far apart.</li></ul><p>The paper uses Euclidean distance, but it is equally valid to use any other distance metric, e.g., cosine distance. The function has a learning objective that can be visualised as in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/0*VOXQHiF-hOjIrwvW.png" /><figcaption>Triplet Loss visualisation</figcaption></figure><p>Notice that Triplet Loss does not have a side effect of urging to encode anchor and positive samples into the same point in the vector space as in Contrastive Loss. This lets Triplet Loss tolerate some intra-class variance, unlike Contrastive Loss, as the latter forces the distance between an anchor and any positive essentially to 0. In other terms, Triplet Loss allows to stretch clusters in such a way as to include outliers while still ensuring a margin between samples from different clusters, e.g., negative pairs.</p><p>Additionally, Triplet Loss is less greedy. Unlike Contrastive Loss, it is already satisfied when different samples are easily distinguishable from similar ones. It does not change the distances in a positive cluster if there is no interference from negative examples. This is due to the fact that Triplet Loss tries to ensure a margin between distances of negative pairs and distances of positive pairs. However, Contrastive Loss takes into account the margin value only when comparing dissimilar pairs, and it does not care at all where similar pairs are at that moment. This means that Contrastive Loss may reach a local minimum earlier, while Triplet Loss may continue to organise the vector space in a better state.</p><p>Let’s demonstrate how two loss functions organise the vector space by animations. For simpler visualisation, the vectors are represented by points in a 2-dimensional space, and they are selected randomly from a normal distribution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*mW0KjZIOMlfW7Ks0.gif" /><figcaption>Animation that shows how Contrastive Loss moves points in the course of training.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/0*wKFureQEfcOY0BuX.gif" /><figcaption>Animation that shows how Triplet Loss moves points in the course of training.</figcaption></figure><p>From mathematical interpretations of this two loss functions, it is clear that Triplet Loss is theoretically stronger, but Triplet Loss has additional tricks that help it work better. Most importantly, Triplet Loss introduce online triplet mining strategies for automatically forming the most useful triplets.</p><h4>Why triplet mining matters?</h4><p>An important decision of a training with Triplet Ranking Loss is <strong>negatives selection</strong> or <strong>triplet mining</strong>. The strategy chosen will have a high impact on the training efficiency and final performance.</p><p>The formulation of Triplet Loss demonstrates that it works on three objects at a time:</p><ol><li><em>anchor</em></li><li><em>positive</em> - a sample that has the same label as the anchor,</li><li><em>negative</em> - a sample with a different label from the anchor and the positive.</li></ol><p>Let’s analyse 3 situations of this loss:</p><ul><li><strong>Easy Triplets</strong>: <br><em>Dw(a, n) &gt; Dw(a, p) + m<br>Dw(a, n) &gt; Dw(a, p) + m</em><br>The negative sample is already sufficiently distant from the anchor sample respect to the positive sample in the embedding space. The loss is 0 and the net parameters are not updating.</li><li><strong>Hard Triplets</strong>: <br><em>Dw(a, n) &lt; Dw(a, p) <br>Dw(a, n) &lt; Dw(a, p)</em> <br>The negative sample is closer to the anchor than the positive. The loss is positive (and greater than m).</li><li><strong>Semi-Hard Triplets</strong>: <br><em>Dw(a, p) &lt; Dw(a, n) &lt; Dw(a, p) + m<br>Dw(a, p) &lt; Dw(a, n) &lt; Dw(a, p) + m</em><br>The negative sample is more distant to the anchor than the positive, but the distance is not greater than the margin, so the loss is still positive (and smaller than m).</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/0*O5xQLxt4ppwpg4FW.png" /><figcaption>An obvious appreciation is that training with Easy Triplets should be avoided, since their resulting loss will be 0</figcaption></figure><p>In a naive implementation, we could form such triplets of samples at the beginning of each epoch and then feed batches of such triplets to the model throughout that epoch. This is called <strong><em>offline strategy</em></strong>. However, this would not be so efficient for several reasons:</p><ul><li>It needs to pass <em>3n</em> samples to get a loss value of <em>n</em> triplets</li><li>Not all these triplets will be useful for the model to learn anything and yielding a positive loss value</li><li>Even if we form useful triplets at the beginning of each epoch with one of the methods that I will be implementing in this series, they may become useless at some point in the epoch as the model weights will be constantly updated</li></ul><p>Instead, we can get a batch of <em>n</em> samples and their associated labels, and form triplets on the fly. That is called <strong><em>online strategy</em></strong>. Normally, this gives n³ possible triplets, but only a subset of such possible triplets will be actually valid. Even in this case, we will have a loss value calculated from much more triplets than the offline strategy. Given a triplet of <em>(a, p, n),</em> it is valid only if:</p><ol><li><em>a</em> and <em>p </em>has the same label</li><li><em>a</em> and <em>p</em> are distinct samples</li><li><em>n</em> has a different label from <em>a</em> and <em>p</em></li></ol><p>These constraints may seem to be requiring expensive computation with nested loops, but it can be efficiently implemented with tricks such as distance matrix, masking, and broadcasting.</p><h4>Distance matrix</h4><p>A <strong><em>distance matrix</em></strong> is a matrix of shape (<em>n, n</em>) to hold distance values between all possible pairs made from items in two <em>n</em>-sized collections. This matrix can be used to vectorise calculations that would need inefficient loops otherwise. Its calculation can be optimised as well, and we will implement <a href="https://www.robots.ox.ac.uk/~albanie/notes/Euclidean_distance_trick.pdf">Euclidean Distance Matrix Trick (PDF)</a> explained by Samuel Albanie. You may want to read this three-page document for the full intuition of the trick, but a brief explanation is as follows:</p><ol><li>Calculate the dot product of two collections of vectors, e.g., embeddings in our case.</li><li>Extract the diagonal from this matrix that holds the squared Euclidean norm of each embedding.</li><li>Calculate the squared Euclidean distance matrix based on the following equation: <strong><em>||a-b||² = ||a||² -2(a, b) + ||b||²</em></strong></li><li>Get the square root of this matrix for non-squared distances.</li></ol><p>PyTorch implementation:</p><pre>import torch<br>import torch.nn as nn<br>import torch.nn.functional as F<br><br><br>eps = 1e-8 # an arbitrary small value to be used for numerical stability tricks<br><br><br>def euclidean_distance_matrix(x):<br>  &quot;&quot;&quot;Efficient computation of Euclidean distance matrix<br>  Args:<br>    x: Input tensor of shape (batch_size, embedding_dim)<br>    <br>  Returns:<br>    Distance matrix of shape (batch_size, batch_size)<br>  &quot;&quot;&quot;<br>  # step 1 - compute the dot product<br><br>  # shape: (batch_size, batch_size)<br>  dot_product = torch.mm(x, x.t())<br><br>  # step 2 - extract the squared Euclidean norm from the diagonal<br><br>  # shape: (batch_size,)<br>  squared_norm = torch.diag(dot_product)<br><br>  # step 3 - compute squared Euclidean distances<br><br>  # shape: (batch_size, batch_size)<br>  distance_matrix = squared_norm.unsqueeze(0) - 2 * dot_product + squared_norm.unsqueeze(1)<br><br>  # get rid of negative distances due to numerical instabilities<br>  distance_matrix = F.relu(distance_matrix)<br><br>  # step 4 - compute the non-squared distances<br>  <br>  # handle numerical stability<br>  # derivative of the square root operation applied to 0 is infinite<br>  # we need to handle by setting any 0 to eps<br>  mask = (distance_matrix == 0.0).float()<br><br>  # use this mask to set indices with a value of 0 to eps<br>  distance_matrix += mask * eps<br><br>  # now it is safe to get the square root<br>  distance_matrix = torch.sqrt(distance_matrix)<br><br>  # undo the trick for numerical stability<br>  distance_matrix *= (1.0 - mask)<br><br>  return distance_matrix</pre><h3>Invalid triplet masking</h3><p>Now that we can compute a distance matrix for all possible pairs of embeddings in a batch, we can apply broadcasting to enumerate distance differences for all possible triplets and represent them in a tensor of shape (<em>batch_size, batch_size, batch_size)</em>. However, only a subset of these <em>n³</em> triplets are actually valid as I mentioned earlier, and we need a corresponding <strong><em>mask</em></strong> to compute the loss value correctly. We will implement such a helper function in three steps:</p><ol><li>Compute a mask for distinct indices, e.g., (<em>i != j </em>and<em> j != k</em>)</li><li>Compute a mask for valid anchor-positive-negative triplets, e.g., <br><em>labels[i] == labels[j] </em>and<em> labels[j] != labels[k]</em></li><li>Combine two masks</li></ol><pre>def get_triplet_mask(labels):<br>  &quot;&quot;&quot;compute a mask for valid triplets<br>  Args:<br>    labels: Batch of integer labels. shape: (batch_size,)<br>  Returns:<br>    Mask tensor to indicate which triplets are actually valid. Shape: (batch_size, batch_size, batch_size)<br>    A triplet is valid if:<br>    `labels[i] == labels[j] and labels[i] != labels[k]`<br>    and `i`, `j`, `k` are different.<br>  &quot;&quot;&quot;<br>  # step 1 - get a mask for distinct indices<br><br>  # shape: (batch_size, batch_size)<br>  indices_equal = torch.eye(labels.size()[0], dtype=torch.bool, device=labels.device)<br>  indices_not_equal = torch.logical_not(indices_equal)<br>  # shape: (batch_size, batch_size, 1)<br>  i_not_equal_j = indices_not_equal.unsqueeze(2)<br>  # shape: (batch_size, 1, batch_size)<br>  i_not_equal_k = indices_not_equal.unsqueeze(1)<br>  # shape: (1, batch_size, batch_size)<br>  j_not_equal_k = indices_not_equal.unsqueeze(0)<br>  # Shape: (batch_size, batch_size, batch_size)<br>  distinct_indices = torch.logical_and(torch.logical_and(i_not_equal_j, i_not_equal_k), j_not_equal_k)<br><br>  # step 2 - get a mask for valid anchor-positive-negative triplets<br><br>  # shape: (batch_size, batch_size)<br>  labels_equal = labels.unsqueeze(0) == labels.unsqueeze(1)<br>  # shape: (batch_size, batch_size, 1)<br>  i_equal_j = labels_equal.unsqueeze(2)<br>  # shape: (batch_size, 1, batch_size)<br>  i_equal_k = labels_equal.unsqueeze(1)<br>  # shape: (batch_size, batch_size, batch_size)<br>  valid_indices = torch.logical_and(i_equal_j, torch.logical_not(i_equal_k))<br><br>  # step 3 - combine two masks<br>  mask = torch.logical_and(distinct_indices, valid_indices)<br><br>  return mask</pre><h3>Batch-all strategy for online triplet mining</h3><p>Now we are ready for actually implementing Triplet Loss itself. Triplet Loss involves several strategies to form or select triplets, and the simplest one is to use all valid triplets that can be formed from samples in a batch. This can be achieved in four easy steps thanks to utility functions we’ve already implemented:</p><ol><li>Get a distance matrix of all possible pairs that can be formed from embeddings in a batch</li><li>Apply broadcasting to this matrix to compute loss values for all possible triplets</li><li>Set loss values of invalid or easy triplets to 0</li><li>Average the remaining positive values to return a scalar loss</li></ol><p>Implementation example:</p><pre>class BatchAllTripletLoss(nn.Module):<br>  &quot;&quot;&quot;Uses all valid triplets to compute Triplet loss<br>  Args:<br>    margin: Margin value in the Triplet Loss equation<br>  &quot;&quot;&quot;<br>  def __init__(self, margin=1.):<br>    super().__init__()<br>    self.margin = margin<br>    <br>  def forward(self, embeddings, labels):<br>    &quot;&quot;&quot;computes loss value.<br>    Args:<br>      embeddings: Batch of embeddings, e.g., output of the encoder. shape: (batch_size, embedding_dim)<br>      labels: Batch of integer labels associated with embeddings. shape: (batch_size,)<br>    Returns:<br>      Scalar loss value.<br>    &quot;&quot;&quot;<br>    # step 1 - get distance matrix<br>    # shape: (batch_size, batch_size)<br>    distance_matrix = euclidean_distance_matrix(embeddings)<br><br>    # step 2 - compute loss values for all triplets by applying broadcasting to distance matrix<br><br>    # shape: (batch_size, batch_size, 1)<br>    anchor_positive_dists = distance_matrix.unsqueeze(2)<br>    # shape: (batch_size, 1, batch_size)<br>    anchor_negative_dists = distance_matrix.unsqueeze(1)<br>    # get loss values for all possible n^3 triplets<br>    # shape: (batch_size, batch_size, batch_size)<br>    triplet_loss = anchor_positive_dists - anchor_negative_dists + self.margin<br><br>    # step 3 - filter out invalid or easy triplets by setting their loss values to 0<br><br>    # shape: (batch_size, batch_size, batch_size)<br>    mask = get_triplet_mask(labels)<br>    triplet_loss *= mask<br>    # easy triplets have negative loss values<br>    triplet_loss = F.relu(triplet_loss)<br><br>    # step 4 - compute scalar loss value by averaging positive losses<br>    num_positive_losses = (triplet_loss &gt; eps).float().sum()<br>    triplet_loss = triplet_loss.sum() / (num_positive_losses + eps)<br><br>    return triplet_loss</pre><h3>Triplet Ranking Loss for Multi-Modal Retrieval</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/0*4-rwSmVm331g6EJ5.png" /></figure><p>So, in our case, the anchor sample is the image, the positive sample is the text associated to that image, and the negative sample is the text of another “negative” image. To choose the negative text, we explored different online negative mining strategies, using the distances in the GloVe space with the positive text embedding. Triplets mining is particularly sensible in this problem, since there are not established classes. Given the diversity of the images, we have many easy triplets. But we also have to be careful mining hard-negatives, since the text associated to another image can be also valid for an anchor image.</p><p>Triplet Loss architecture helps us to learn distributed embedding by the notion of similarity and dissimilarity. It’s a kind of neural network architecture where multiple parallel networks are trained that share weights among each other. During prediction time, input data is passed through one network to compute distributed embeddings representation of input data.</p><h3>To be continued…</h3><p>In the next part we’ll discuss the architecture of Image encoder, caption encoder, OCR for text scenes GCN for scene graph reconstruction and the whole pipeline implementation and metrics.</p><h3>Links</h3><p><a href="https://github.com/LiahimRatman/MStacMR">Github project</a></p><p>Articles used for inspiration:<br><a href="https://towardsdatascience.com/triplet-loss-advanced-intro-49a07b7d8905">https://towardsdatascience.com/triplet-loss-advanced-intro-49a07b7d8905</a><br><a href="https://towardsdatascience.com/contrastive-loss-explaned-159f2d4a87ec">https://towardsdatascience.com/contrastive-loss-explaned-159f2d4a87ec</a><br><a href="https://medium.com/@maksym.bekuzarov/losses-explained-contrastive-loss-f8f57fe32246">https://medium.com/@maksym.bekuzarov/losses-explained-contrastive-loss-f8f57fe32246</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6310a4e5476" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>