
Ever tried searching for “a red tie and a white shirt in a formal setting” on a fashion site ? You probably got… shirts. Maybe some red ones. Maybe some ties. But definitely not a guy wearing both in the combination you wanted.
That’s because most e-commerce search still works like keyword matching, manual tags, and rigid filters with the help of humans. It sees “red,” “tie,” “white,” “shirt” as separate words, not a specific look you’re imagining.
I built something different. This blog breaks down how I combined Vision-Language Models, semantic search, and a smart re-ranking system to create a fashion search engine that actually gets compositional queries like this.it works way better than just throwing CLIP at the problem
This leads to a fundamental research question:
Can we build a search system that truly understands fashion imagery the way humans do ?
Answering it requires rethinking the entire search pipeline from first principles.
1. Why Vanilla CLIP Falls Short
CLIP (Contrastive Language-Image Pre-training) by OpenAI revolutionized vision-language understanding. Its elegant approach jointly training image and text encoders on 400 million image-text pairs enables zero-shot transfer across domains.
The Model : clip-vit-large-patch14
So why we not just use CLIP directly?
- The Problem with Direct Matching
Here’s how vanilla CLIP works:
Image : CLIP image encodes and : Gets a vector like ( 512 Dim )
Query : CLIP text encodes and : Gets a vector like ( 512 Dim )
Match = How similar are these vectors ?
Ex : Similarity = cosine(image_vec, text_vec)
Simple Fast But here’s what goes wrong
2. It Doesn’t Really “See” Fashion
When you search for “a red tie and a white shirt in a formal setting” CLIP looks at images and creates vectors, but it doesn’t explicitly understand:
- That you want both a red tie and a white shirt together
- That “formal setting” means office/indoor, not casual outdoor
- The difference between “red tie with white shirt” vs “white tie with red shirt”
so overcame this limitation I make such a system which is first write down “man wearing red tie, white dress shirt, standing in office interior,” and then we search.
2. Proposed Architecture: A Multi-Stage Intelligence Pipeline.
Our system introduces a paradigm shift : instead of direct image-to-query matching, we create an explicit semantic abstraction layer through language.
2.1 Indexing Pipeline :

The pipeline starts with your raw fashion images. Each image is first sent to Qwen2-VL-2B, which generates a detailed caption describing what’s in the image clothing items, colors, and overall context.
That caption is then cleaned up by Qwen2.5–0.5B, which removes fluff and standardizes everything into a simple, structured format (for example: items, colors, and setting). This normalized text is what keeps the system consistent and searchable.
Both the original caption and the normalized version are stored in PostgreSQL with a unique ID and image path. The normalized text is also converted into an embedding using BGE-Large and saved in FAISS for fast similarity search.
This indexing step runs once (about 15–20 minutes for 3,000 images). After that, the whole dataset is ready for instant search.
2.2 Retrieval Pipeline :

When you search for something like “navy blazer with white shirt and red tie on a city street,” the system follows the *same steps used during indexing.* First, your query is normalized by Qwen2.5–0.5B into a clean, structured format so it matches how the images were processed.
That normalized query is then turned into an embedding by same model which is used in indexing pipeline BGE-Large and sent to FAISS, which quickly finds the most similar image vectors using cosine similarity. This step narrows thousands of images down to about Top N strong candidates in just a few milliseconds.
Next, the system pulls those images and runs CLIP re-ranking. CLIP directly compares your original text query with the actual image content, refining the results and catching details that text-only matching can miss. Finally, the Top K best matches are returned all in under 100 milliseconds.
Complete Architecture :

3. Deep Dive: The Four Pillars of Intelligent Fashion Search
Pillar I . Vision-Language Captioning (Image to Text)
The Model: Qwen2-VL-2B-Instruct
Why we are not just use a regular image classifier ?
like our old approaches (ResNet, EfficientNet) look at images and spit out labels like “shirt” or “formal” But that’s useless for a query like “red tie and white shirt in formal setting” we need actual descriptions, not just categories.
That’s where Vision-Language Models come in Qwen2-VL looks at an image and writes a sentence about what it sees like a human would.
What it captures :
- What clothes the person is wearing (blazer, shirt, tie)
- What colors everything is
- Accessories (watch, bag, glasses)
- Where they are (office, park, street)
How I prompt it in :
"texts": """
You are a professional fashion image caption generator for an intelligent fashion search engine.
Describe the image in ONE clear, short, and accurate sentence.
Include ONLY the following if clearly visible:
- Upper body clothing with type and color (e.g., black shirt)
- Lower body clothing with type and color (e.g., blue jeans)
- Visible accessories with color (e.g., red tie, black hat)
- Background or environment if relevant (e.g., office, indoor, city street, park)
- Posture or action if visible (e.g., standing, walking, sitting)
Rules:
- Focus only on visible and factual details
- Do NOT guess, infer, or add extra information
- Do NOT describe emotions, style, or intent
"""
Example Output:

Vision-Language Model which we are used Qwen2-VL gives the correct and accurate short information / description about the given image .
Pillar II: LLM-Based Text Normalization
The Model: Qwen2.5–0.5B-Instruct (small and fast)
The problem: The caption and your search query use different words for the same thing.
Look at what the Vision-Language Model just generated for our image:
Raw Caption:
"A man in a stylish navy blue blazer, white dress shirt, red tie,
and tan pants walking down a city street, wearing brown leather loafers."
Now imagine you search for: “navy blazer with white shirt and red tie on a city street”
These describe the same image, but the words don’t perfectly align:
- Caption says “stylish navy blue blazer” : we just said “navy blazer”
- Caption says “walking down a city street” : we said “on a city street”
- Caption mentions “white dress shirt” and “tan pants” : we just said only “white shirt”
- Caption has extra details like “brown leather loafers “ : not in our query
Without normalization, the search has to match messy, inconsistent descriptions.
What normalization does:
- Pulls out only the fashion items (blazer, shirt, tie, pants, shoes)
- Standardizes colors (keeps “red”, “white”, “navy blue”)
- Removes fluff words (“stylish”, “walking down”)
- Simplifies the setting (“city street” → “outdoor, urban”)
- Organizes it into a clean format
Example Output :

Before Normalization:
"A man in a stylish navy blue blazer, white dress shirt, red tie,
and tan pants walking down a city street, wearing brown leather loafers."
After Normalization:
"navy blue blazer | white dress shirt | red tie | tan pants | city street | brown leather loafers"
How I prompt it:
"texts" = """
You are a fashion search engine text normalization and keyword extraction model.
Extract ONLY essential fashion-related keywords from the input text.
Rules:
1. Extract clothing items (e.g., shirt, jacket, raincoat, pants, jeans, tie)
2. Extract colors ONLY if explicitly mentioned
3. Extract environment or setting ONLY if explicitly mentioned and relevant
(e.g., office, park, indoor, city street)
4. Do NOT guess or infer missing information
5. Do NOT add, explain, or rephrase anything
6. Do NOT include non-fashion words
7. Output ONLY the extracted keywords separated by ' | '
8. Keep the output minimal, precise, and consistent
Example:
Input: "A person wearing a bright yellow raincoat and black pants,
standing outdoors on a city street."
Output: "yellow | raincoat | black | pants | outdoor | city street"
"""
Why this works:
When you search for “navy blazer with white shirt and red tie on a city street”, your query gets normalized the same way aslo like :
"blazer | navy | shirt | white | tie | red | outdoor | urban"
Now the system can easily match: navy blazer, red tie, outdoor/urban setting Perfect match!
Why This Matters :
This is the most critical part for fashion search.
See, people describe the same clothes in completely different ways. You say “navy blazer,” someone else says “dark blue coat.” Same thing, different words.
If you just convert raw text to vectors ? They won’t match. Your search fails.
But normalize both sides through the same pipeline, and boom:
- Image caption: “stylish navy blue blazer” : “blazer | navy blue”
- Your query: “navy blazer” : “blazer | navy blue”
Perfect match. Same words, same vectors, same results.
Pillar III : Converting Text to Searchable Vectors for ( Semantic Embeddings ) with BGE
The Model: BAAI/bge-large-en-v1.5 (creates 1024-dimensional vectors)
Why BGE over CLIP Text Encoder ?

Once we’ve converted images into normalized text captions, we’re no longer doing image search we’re doing text-to-text matching.
CLIP’s text encoder is designed to match with CLIP’s image encoder. But we’re not using CLIP images anymore we’re using text descriptions.
BGE is purpose-built for exactly this: measuring how similar two pieces of text are. Since both our image captions and user queries are now normalized text, BGE is the better tool for the job.
Plus, the larger embedding size (1024-dim) captures more semantic details, which helps with those tricky compositional queries like “navy blazer with white shirt and red tie.”
Example Output :

Shape: (1024,)
First 10 values: [-0.00959765 -0.03354978 0.00620942 0.02310117 0.024151
-0.02061603 0.00120313 0.01972308 0.00887509 0.02219124]
Vector Storage: FAISS
# Index Configuration :
index = faiss.IndexFlatIP(1024) : Inner Product for cosine similarity
FAISS enables sub-millisecond search across millions of vectors essential for production latency requirements.
Pillar IV: CLIP Re-Ranking (The Final Polish)
The Model: clip-vit-large-patch14: ( OpenAI’s largest public model )
The largest publicly available CLIP model provides the highest quality cross-modal representations for final ranking.
Our Two-Stage Strategy:
- Stage 1 ( FAISS ): Find ALL potentially relevant items : get 50–100 , Top N candidates that might match ( Maximize Recall )
- Stage 2 ( CLIP ): Pick the best ones : narrow down to the perfect 10–15 Top K ( Maximize Precision )
Why not just use CLIP from the start?
Simple , Speed vs. accuracy tradeoff.
- FAISS is super fast (searches millions in milliseconds) but only compares text-to-text
- CLIP is more slower because it needs to process images
So we use FAISS to quickly filter down to Top N candidates, then let CLIP do the heavy lifting on just those few. Best of both worlds.
How Re-ranking Works in My System :
def rerank(query: str, candidate_images: List[str], top_k: int = 10):
# Convert your query to CLIP's text vector
text_embedding = clip_model.encode_text([query])
# Convert candidate images to CLIP's image vectors
image_embeddings = clip_model.encode_images(candidate_images)
# Calculate similarity scores
scores = cosine_similarity(text_embedding, image_embeddings)
# Sort and return top-k best matches
return sorted(zip(candidate_images, scores),
key=lambda x: x[1], reverse=True)[:top_k]
This is where CLIP finally comes in. Not for the initial search, but for the final validation looking at actual images and your actual query to find the truly best matches.
For our “navy blazer with white shirt and red tie” query, CLIP now directly compares your text against the actual image pixels of those 50 candidates. It can see: “Yes, this guy has all three pieces together in the right colors.”
And yeah that’s the precision which we want .
4 . Key Design Decisions
- Why PostgreSQL for Metadata?
CREATE TABLE fashion_images (
image_id SERIAL PRIMARY KEY,
image_path VARCHAR(500) NOT NULL UNIQUE,
caption TEXT,
normalized_text TEXT,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
Simple reason:
FAISS only stores vectors and their IDs nothing else. But you need to store actual information about each image:
- Where’s the image file?
- What was the original caption?
- What’s the normalized version?
- When was it indexed?
PostgreSQL handles all of this and also the Future extensibility (user ratings, click data)
2. Everything Runs Locally (No APIs)
All four models run on your own machine no calling OpenAI or Hugging Face APIs, no data leaving your system.

Total GPU memory needed : ~10GB (runs fine on RTX 3080/4080)
Why this matters:
- No API costs piling up
- No internet dependency
- Complete data privacy
- Full control over the pipeline
- Can run as many queries as you want
For 500–1000 images, indexing takes about 15–20 minutes one time. After that ? Search results come back in under on an avg 980 ms .
5. Experimental Results
We evaluate the retrieval performance of our proposed system and compare it with the CLIP baseline using Precision@5 (P@5) on a dataset of 3,000 samples. As the dataset is limited, we do not get similar results for all queries.
However, for some queries, the system delivers excellent results, which clearly shows the potential of our approach.
Experiments are conducted on :
- 3000-image dataset
Queries are grouped into five categories:
- Attribute-Specific
- Contextual / Place-Based
- Complex Semantic
- Style Inference
- Compositional
Precision@K = ( Number of relevant images in top K ) / K .

P@5 is calculated by checking how many relevant results appear in the top 5 retrieved items for each query and then averaging this value over all test queries.
So when we say P@5 = 0.73 it means that on average about 3 to 4 results out of the top 5 are relevant across the evaluated queries.
Results are averaged over a limited number of manually evaluated queries. Due to dataset size constraints, these numbers reflect observed trends rather than exhaustive benchmarking.
2. Real-Time Retrieval Performance
The system’s end-to-end search latency across different K values. The observed minimum latency was 891.5 ms, and average latency 948.0 ms per query. As K increases, latency shows a slight upward trend due to additional similarity computations, while remaining under 1.1 seconds, demonstrating stable real-time retrieval performance.

6. Conclusion
A building an intelligent fashion search engine isn’t just about throwing powerful models at the problem it’s about designing a system where each piece does what it does best.
By breaking the problem into specialized stages like captioning, normalization, embedding, retrieval, and re-ranking we got results that beat vanilla CLIP . Not because we used bigger models, but because we designed a smarter pipeline.
What actually made the difference:
Semantic Abstraction: Using VLMs to convert images into explicit, searchable text descriptions and raw pixels don’t tell you “navy blazer with red tie” captions do.
Text Normalization: Running both image captions and user queries through the same LLM-based cleanup process. This is what makes “stylish navy blue blazer” match with “navy blazer” they become the same thing.
Two-Stage Retrieval: FAISS gets you 100 candidates in 10 milliseconds. CLIP picks the best 10 by actually looking at the images. Speed meets accuracy.
Production-Ready Design: Everything runs locally, no API calls, scales to millions of images, and you can debug exactly why something matched or didn’t.
The takeaway for anyone building visual search systems: your pipeline architecture matters more than your model size. a well-designed system with smaller models beats a poorly designed system with the latest SOTA models.
7. References / Special Thanks.
- Hugging Face Blog .
- Hugging Face Open Source Model
- Google cloud Discover.
- GFG ML Documentations
- arXiv : )
- Draw.io :)
ref :
- Qwen Team. 2024. “Qwen2-VL: Enhancing Vision-Language Model’s Perception of the World at Any Resolution.” arXiv preprint arXiv:2409.12191.
- Li, X., et al. (2023). Making large language models a better foundation for dense retrieval. arXiv preprint arXiv:2312.15503.
- Radford, Alec, et al. 2021. “Learning Transferable Visual Models From Natural Language Supervision.” arXiv preprint arXiv:2103.00020.
8. Code Availability
The complete implementation is available on GitHub Check it out, and if it helps you , drop a star!
GitHub Repo Link : github.com/PrashantTakale369
The End …………. : )
Thanks for reading! If you’re building something similar or have ideas on how to improve this, let’s chat in the comments.
And if you want more ML system breakdowns like this, hit that follow button.