You don't need a massive dataset, a GPU cluster, or a complicated ML pipeline to understand how modern recommendation systems retrieve relevant items.
With PyTorch, FAISS, and 60 lines of Python, you can build a working two-tower recommender that learns user preferences, generates item embeddings, and retrieves the top 100 unseen candidates for a user.
But there is a catch.
Those 100 candidates are not necessarily what you should show in your production feed.
In this tutorial, we'll build the retrieval model from scratch and explore where its responsibilities end.
For the full conceptual breakdown of how two-tower models work, see this guide to two-tower recommendation models.
What are we building?
Our recommendation system will use:
- PyTorch for model training.
- NumPy for synthetic interaction data.
- FAISS for vector similarity search.
- 100 users with different preferences.
- 500 recommendable items.
- 32-dimensional embeddings.
- Top-100 candidate retrieval.
Everything runs on a CPU.
No external dataset, API key, or cloud infrastructure is required.
1. Install the dependencies
Create a Python virtual environment and install the dependencies:
python -m venv .venv Activate it on macOS or Linux:
source .venv/bin/activate On Windows:
.venv\Scripts\activate Install the libraries:
pip install torch numpy faiss-cpu We're ready to build.
2. Understand the two-tower architecture
A two-tower recommendation model uses two independently computable neural networks.
User tower: Converts a user's features into an embedding.
Item tower: Converts an item's features into an embedding.
Both towers produce vectors in the same embedding space.
User ID Item ID | | User Tower Item Tower | | User Embedding Item Embedding | | +---- Similarity -------+ | Relevance Score During training, the model learns to assign higher similarity scores to user-item pairs that have interacted.
During inference, we calculate the user embedding and search against precomputed item embeddings.
This separation makes two-tower models particularly useful for candidate retrieval.
3. Build the two-tower recommender in 60 lines
Create a file called two_tower.py and paste the following code.
import numpy as np import torch from torch import nn from torch.nn import functional as F import faiss torch.manual_seed(42) torch.set_num_threads(1) rng = np.random.default_rng(42) U, I, D, TOPICS = 100, 500, 32, 5 # Synthetic implicit feedback: each user prefers one topic. topics = np.arange(I) % TOPICS seen = [rng.choice(np.where(topics == u % TOPICS)[0], size=30, replace=False) for u in range(U)] pairs = torch.tensor([(u, i) for u in range(U) for i in seen[u]]) class TwoTower(nn.Module): def __init__(self): super().__init__() self.user = nn.Sequential(nn.Embedding(U, 64), nn.Linear(64, D)) self.item = nn.Sequential(nn.Embedding(I, 64), nn.Linear(64, D)) def encode_users(self, ids): return F.normalize(self.user(ids), dim=-1) def encode_items(self, ids): return F.normalize(self.item(ids), dim=-1) model = TwoTower() optimizer = torch.optim.Adam(model.parameters(), lr=0.01) all_items = torch.arange(I) model.train() for epoch in range(30): for batch in pairs[torch.randperm(len(pairs))].split(256): users, positives = batch.T query = model.encode_users(users) items = model.encode_items(all_items) logits = (query @ items.T) / 0.07 loss = F.cross_entropy(logits, positives) optimizer.zero_grad() loss.backward() optimizer.step() if (epoch + 1) % 10 == 0: print(f"epoch {epoch + 1}: loss={loss.item():.3f}") # Precompute item embeddings and build an exact cosine index. model.eval() with torch.no_grad(): vectors = model.encode_items(all_items).numpy() query = model.encode_users(torch.tensor([7])).numpy() index = faiss.IndexFlatIP(D) index.add(vectors) _, ids = index.search(query, 130) blocked = set(seen[7]) top100 = [int(i) for i in ids[0] if i not in blocked][:100] assert len(top100) == 100 print("Top 100:", top100) print("First 10:", top100[:10]) print("Preferred-topic hits:", int((topics[top100] == 7 % TOPICS).sum())) Run it:
python two_tower.py You now have a complete two-tower candidate retrieval pipeline.
4. What happens during training?
Our synthetic dataset contains 3,000 positive user-item interactions.
Each user has interacted with 30 items belonging to their preferred topic.
The model does not receive those topic labels as input. It must learn preferences from interaction patterns.
The important calculation is:
logits = (query @ items.T) / 0.07 This calculates similarity between each user embedding and every item embedding.
We then use PyTorch's cross-entropy loss to encourage higher scores for observed positive items.
Because our catalog contains only 500 items, scoring the entire catalog during training is manageable.
Production implementations with millions of items commonly use sampled negatives or in-batch negatives instead.
One limitation of this simplified training approach is that other relevant items may be treated as negatives even when the user would potentially like them.
5. Precompute item embeddings with FAISS
The architectural advantage of a two-tower model appears during inference.
We don't need to run the item tower separately for every user request.
Instead, we calculate all item embeddings in advance:
vectors = model.encode_items(all_items).numpy() Then add them to a FAISS index:
index = faiss.IndexFlatIP(32) index.add(vectors) At request time, we only need to generate the user embedding and search the index.
Since both towers return normalized vectors, inner product is equivalent to cosine similarity, as explained in the official FAISS similarity metrics documentation.
Our example uses IndexFlatIP, which performs exact similarity search.
For much larger catalogs, FAISS also provides approximate search indexes such as HNSW and IVF. These trade-offs are covered in its index selection guide.
6. Retrieve the top 100 candidates
For user 7, the model returns a similarity-ordered list of candidate items.
An example from testing the training code with equivalent exact NumPy similarity search:
epoch 10: loss=4.487 epoch 20: loss=4.100 epoch 30: loss=3.898 First 10: [202, 167, 122, 117, 472, 352, 262, 317, 382, 397] Preferred-topic hits: 65 The complete script prints all 100 retrieved item IDs.
We retrieve 130 candidates initially because the user has already interacted with 30 items. Removing those previously seen items still leaves enough candidates to return 100 results.
Interestingly, 65 of the returned items belong to the user's preferred topic.
Since only 70 unseen items remain in that topic, the result demonstrates that the model has learned useful preference patterns on this synthetic dataset.
This is a toy retrieval diagnostic, not a production recommendation-quality benchmark.
7. The developer's surprise: You haven't built a feed
Here's where things get interesting.
Your model successfully retrieves 100 candidates.
But imagine you're building a real marketplace.
Those candidates might contain:
- Out-of-stock products.
- Listings from suspended sellers.
- Products the user recently viewed.
- Too many listings from one seller.
- Items with outdated prices.
- Eligible sponsored products.
Your two-tower model does not automatically enforce those constraints.
It returns candidates ordered by embedding similarity.
That is a retrieval result, not necessarily a production-ready feed.
8. Retrieval vs ranking vs sponsored placement
A production recommendation system generally separates these responsibilities.
Retrieval: Find potentially relevant candidates from a large inventory.
Ranking: Determine which candidates should appear first using additional contextual and behavioral signals.
Filtering and re-ranking: Enforce availability, safety, diversity, freshness, and other product constraints.
Sponsored placement: Determine where eligible paid items can appear without bypassing marketplace policies.
Your production architecture might look like this:
Catalog: 1,000,000 items | Two-Tower Retrieval + FAISS | 100 candidates | Eligibility Filtering | Ranking + Business Rules | Sponsored Placement | Final 20-item Feed | Outcome Tracking The numbers are illustrative, but the architectural separation matters.
Google's recommendation system architecture similarly separates candidate generation, scoring, and re-ranking.
Once retrieval works, the next engineering challenge is deciding what to do with those retrieved candidates.
9. Where a ranking API fits
You don't necessarily need to replace your two-tower model when adding more sophisticated ranking or monetization.
Keep PyTorch and FAISS responsible for retrieval.
Then introduce a decision layer that receives the candidate IDs, features, user context, and relevant business constraints.
For example, a ranking API like Gortex can operate on application-supplied candidates rather than replacing the retrieval system.
The application retains control over eligibility and inventory, while the decision layer can handle final ordering and configured sponsored placements.
This is especially relevant for marketplaces and consumer platforms that want organic discovery and paid visibility to coexist within the same user experience.
Retrieval and final decisioning remain separate architectural responsibilities.
Final thoughts
In 60 lines of Python, we built a two-tower recommender that:
- Generates synthetic interaction data.
- Trains separate user and item towers.
- Produces normalized embeddings.
- Precomputes item vectors.
- Uses FAISS for similarity search.
- Retrieves 100 unseen candidates.
That is a useful foundation.
But production recommendations require more than finding similar vectors.
Retrieval finds what could be shown. Ranking determines what should be shown.
Understanding that distinction can save you from building an increasingly complicated recommendation model when what you actually need is a better decision layer.

