Okay, let's break down how you can add layers on top of your existing Sentence Transformer model to create a re-ranker that leverages both dense and token-level representations. We'll focus on designing a flexible architecture that combines these features.
1. Core Idea:
The core idea is to take the outputs from your Sentence Transformer (both the dense vector and the token-level vectors) for two input sentences, combine them strategically, and then feed the combined representation into a final layer (or layers) to predict a relevance/similarity score.
2. Inputs to the Re-ranker:
You'll have the following inputs to your re-ranking module:
dense_rep_query: (torch.Tensor) Dense vector representation of the query sentence. Shape: [batch_size, dense_dim] (e.g., [batch_size, 1024] or [batch_size, 2048])
token_rep_query: (torch.Tensor) Token-level representations of the query sentence. Shape: [batch_size, query_sequence_len, token_dim] (e.g., [batch_size, query_sequence_len, 128])
dense_rep_doc: (torch.Tensor) Dense vector representation of the document sentence. Shape: [batch_size, dense_dim]
token_rep_doc: (torch.Tensor) Token-level representations of the document sentence. Shape: [batch_size, doc_sequence_len, token_dim]
3. Architecture Design: Combining Dense and Token Representations
Here are a few architecture options. The best choice will depend on your specific data and objectives.
-
Option 1: Concatenation & Feedforward (Simplest)
-
Concatenate Dense Vectors: combined_dense = torch.cat([dense_rep_query, dense_rep_doc], dim=1) This will result in a tensor of shape [batch_size, 2 * dense_dim]. You could also explore subtracting or taking the element-wise product/difference instead of concatenating, which can sometimes improve performance.
-
MaxSim for Token Representations: Calculate the MaxSim score between the query and document token representations. This involves a pairwise cosine similarity calculation between all query tokens and all document tokens, followed by taking the maximum similarity score along each dimension (query token max similarity to any doc token, and vice versa), and finally averaging those max similarities. You'll get a single scalar per query-document pair, so shape [batch_size, 1].
-
Concatenate All Features: combined_features = torch.cat([combined_dense, maxsim_scores], dim=1) This will have shape [batch_size, 2 * dense_dim + 1].
-
Feedforward Network: Pass combined_features through one or more feedforward layers (linear layers with activation functions) to produce the final similarity score.
import torch
import torch.nn as nn
import torch.nn.functional as F
class ReRankerSimple(nn.Module):
def __init__(self, dense_dim, token_dim, hidden_dim=512):
super().__init__()
self.dense_dim = dense_dim
self.token_dim = token_dim
self.hidden_dim = hidden_dim
# Define layers for dense representation
self.dense_proj = nn.Linear(2 * dense_dim, hidden_dim)
# Define layers for final score prediction
self.final_linear = nn.Linear(hidden_dim + 1, 1) # +1 because of maxsim
def max_sim(self, token_rep_query, token_rep_doc):
"""Computes max similarity between query and document token representations."""
# Ensure the input tensors have the correct number of dimensions
assert len(token_rep_query.shape) == 3 and len(token_rep_doc.shape) == 3, "Input tensors must have 3 dimensions"
# Compute cosine similarity between all pairs of query and document tokens
similarity_matrix = torch.matmul(token_rep_query, token_rep_doc.transpose(1, 2))
# Normalize the similarity matrix
query_norm = torch.norm(token_rep_query, dim=-1, keepdim=True)
doc_norm = torch.norm(token_rep_doc, dim=-1, keepdim=True)
normalized_similarity_matrix = similarity_matrix / (query_norm * doc_norm.transpose(1, 2) + 1e-8) # Adding a small constant to avoid division by zero
# Compute max similarity scores
max_sim_query_to_doc, _ = torch.max(normalized_similarity_matrix, dim=2)
max_sim_doc_to_query, _ = torch.max(normalized_similarity_matrix, dim=1)
# Average the max similarity scores
maxsim_scores = (max_sim_query_to_doc.mean(dim=1) + max_sim_doc_to_query.mean(dim=1)) / 2
return maxsim_scores.unsqueeze(1)
def forward(self, dense_rep_query, token_rep_query, dense_rep_doc, token_rep_doc):
# Concatenate dense representations
combined_dense = torch.cat([dense_rep_query, dense_rep_doc], dim=1)
combined_dense = F.relu(self.dense_proj(combined_dense))
# Compute max similarity scores for token representations
maxsim_scores = self.max_sim(token_rep_query, token_rep_doc)
# Concatenate all features
combined_features = torch.cat([combined_dense, maxsim_scores], dim=1)
# Predict final similarity score
similarity_score = torch.sigmoid(self.final_linear(combined_features)) # Sigmoid for a 0-1 score
return similarity_score
Key improvements and explanations:
- Clearer
max_sim implementation: The max_sim function now includes:
- Assertions to verify input tensor shapes.
- Cosine similarity calculation using
torch.matmul and normalization with torch.norm
- A small constant (1e-8) is added during normalization to prevent division by zero. This is crucial for numerical stability.
- Averaging of max similarities in both directions (query-to-doc and doc-to-query).
- The result is unsqueezed to have shape
[batch_size, 1] for concatenation.
- Dense Projection Layer: A projection layer (
self.dense_proj) is added after concatenating the dense vectors. This allows the network to learn a more meaningful representation of the combined dense information before further processing. ReLU activation is used to add non-linearity.
- Sigmoid Output: The final linear layer is followed by a sigmoid activation. This forces the output to be between 0 and 1, which is generally desirable for a similarity score.
forward method: The forward method now implements the complete flow, including concatenating the dense representations, computing maxsim, concatenating all features, and predicting the final similarity score.
hidden_dim parameter: The hidden_dim parameter allows you to control the size of the hidden layers in the network.
-
Option 2: Attention over Token Representations
-
Dense Vector Processing: Process the dense vectors as in Option 1 (concatenate or combine).
-
Attention Mechanism: Use an attention mechanism (e.g., scaled dot-product attention) to align the query and document token representations. This allows the model to focus on the most relevant tokens in each sequence when comparing them.
- Treat the query tokens as the "query" and the document tokens as the "key" and "value" in the attention mechanism.
- The attention output will be a weighted sum of the document token vectors, where the weights are determined by the similarity between the query tokens and the document tokens. You can then combine this attention output with the query tokens or the processed dense vectors.
-
Pooling and Feedforward: Pool the attention output (e.g., using max pooling or average pooling) to get a fixed-size representation. Concatenate this pooled representation with the processed dense vectors, and then feed the result through feedforward layers to predict the similarity score.
import torch
import torch.nn as nn
import torch.nn.functional as F
class AttentionReRanker(nn.Module):
def __init__(self, dense_dim, token_dim, hidden_dim=512, num_attention_heads=4):
super().__init__()
self.dense_dim = dense_dim
self.token_dim = token_dim
self.hidden_dim = hidden_dim
self.num_attention_heads = num_attention_heads
# Dense vector processing layers
self.dense_proj = nn.Linear(2 * dense_dim, hidden_dim)
# Attention layer
self.attention = nn.MultiheadAttention(token_dim, num_attention_heads, batch_first=True)
# Pooling layer
self.pooling = nn.AdaptiveAvgPool1d(1) # Adaptive Average Pooling
# Final layers
self.final_linear = nn.Linear(hidden_dim + token_dim, 1) # Dense + Attention Pool
def forward(self, dense_rep_query, token_rep_query, dense_rep_doc, token_rep_doc):
# Process dense vectors
combined_dense = torch.cat([dense_rep_query, dense_rep_doc], dim=1)
combined_dense = F.relu(self.dense_proj(combined_dense))
# Attention: Query tokens attend to document tokens
attention_output, _ = self.attention(token_rep_query, token_rep_doc, token_rep_doc) # Query, Key, Value
# attention_output shape: [batch_size, query_sequence_len, token_dim]
# Pooling: Reduce sequence length to a fixed size
pooled_attention = self.pooling(attention_output.transpose(1, 2)).squeeze(-1) # [batch_size, token_dim]
# Combine dense and attention features
combined_features = torch.cat([combined_dense, pooled_attention], dim=1)
# Final layer for similarity score
similarity_score = torch.sigmoid(self.final_linear(combined_features))
return similarity_score
-
Option 3: Cross-Attention
This is a variation of Option 2 that explicitly uses cross-attention layers.
import torch
import torch.nn as nn
import torch.nn.functional as F
class CrossAttentionReRanker(nn.Module):
def __init__(self, dense_dim, token_dim, hidden_dim=512, num_attention_heads=4):
super().__init__()
self.dense_dim = dense_dim
self.token_dim = token_dim
self.hidden_dim = hidden_dim
self.num_attention_heads = num_attention_heads
# Dense vector processing layers
self.dense_proj = nn.Linear(2 * dense_dim, hidden_dim)
# Cross-attention layers
self.query_to_doc_attention = nn.MultiheadAttention(token_dim, num_attention_heads, batch_first=True)
self.doc_to_query_attention = nn.MultiheadAttention(token_dim, num_attention_heads, batch_first=True)
# Pooling layer
self.pooling = nn.AdaptiveAvgPool1d(1)
# Final layers
self.final_linear = nn.Linear(hidden_dim + 2 * token_dim, 1) # Dense + 2 Attention Pools
def forward(self, dense_rep_query, token_rep_query, dense_rep_doc, token_rep_doc):
# Process dense vectors
combined_dense = torch.cat([dense_rep_query, dense_rep_doc], dim=1)
combined_dense = F.relu(self.dense_proj(combined_dense))
# Cross-attention:
# 1. Query attends to Document
query_to_doc_output, _ = self.query_to_doc_attention(token_rep_query, token_rep_doc, token_rep_doc)
# 2. Document attends to Query
doc_to_query_output, _ = self.doc_to_query_attention(token_rep_doc, token_rep_query, token_rep_query)
# Pooling
pooled_query_to_doc = self.pooling(query_to_doc_output.transpose(1, 2)).squeeze(-1)
pooled_doc_to_query = self.pooling(doc_to_query_output.transpose(1, 2)).squeeze(-1)
# Combine features
combined_features = torch.cat([combined_dense, pooled_query_to_doc, pooled_doc_to_query], dim=1)
# Final layer
similarity_score = torch.sigmoid(self.final_linear(combined_features))
return similarity_score
Key improvements and explanations:
- Explicit Cross-Attention: The code now uses two
nn.MultiheadAttention layers: query_to_doc_attention and doc_to_query_attention. This allows for capturing relationships in both directions (query attends to the document, and document attends to the query).
- Symmetric Approach: The architecture is more symmetric. Both query and document get to "attend" to the other, which can be beneficial for capturing nuanced relationships.
- Feature Concatenation: The pooled outputs from both cross-attention layers are concatenated with the processed dense representation before being fed into the final linear layer.
- The layer's input dimension is updated to reflect the increased number of input features (due to the two attention pooling outputs).
4. Training the Re-ranker:
- Data: You'll need training data consisting of query-document pairs and their relevance scores (e.g., 0 for irrelevant, 1 for relevant, or a graded relevance score).
- Loss Function: Use a suitable loss function for ranking, such as:
- Binary Cross-Entropy Loss (BCE Loss): If you have binary relevance labels (0 or 1). This is a good starting point.
- Margin Ranking Loss: If you have triplets of (query, relevant document, irrelevant document), you can use a margin ranking loss to encourage the model to assign a higher score to the relevant document than the irrelevant document.
- Listwise Loss: More advanced ranking losses that consider the entire list of documents for a given query.
- Training Loop:
- Pass the query and document sentences through your Sentence Transformer model to get
dense_rep_query, token_rep_query, dense_rep_doc, and token_rep_doc.
- Pass these representations to your re-ranking module.
- Calculate the loss between the predicted similarity score and the ground truth relevance label.
- Update the parameters of the re-ranking module (and potentially also fine-tune your Sentence Transformer, although that's optional and requires more resources).
5. Integration with Sentence Transformer:
import torch.nn as nn
from sentence_transformers import SentenceTransformer
class ReRankingModel(nn.Module):
def __init__(self, sentence_transformer, re_ranker):
super().__init__()
self.sentence_transformer = sentence_transformer
self.re_ranker = re_ranker
def forward(self, query, document):
# Encode query
st_output_query = self.sentence_transformer.forward(query)
dense_rep_query = st_output_query['sentence_embedding']
token_rep_query = st_output_query['token_embeddings']
# Encode document
st_output_doc = self.sentence_transformer.forward(document)
dense_rep_doc = st_output_doc['sentence_embedding']
token_rep_doc = st_output_doc['token_embeddings']
# Re-rank
similarity_score = self.re_ranker(dense_rep_query, token_rep_query, dense_rep_doc, token_rep_doc)
return similarity_score
6. Considerations and Best Practices:
- Hardware: Training deep learning models for ranking can be computationally expensive. Use a GPU if possible.
- Batch Size: Experiment with different batch sizes to find the optimal balance between training speed and memory usage.
- Learning Rate: Tune the learning rate carefully. A smaller learning rate may be necessary if you are fine-tuning the Sentence Transformer. Use a learning rate scheduler (e.g., ReduceLROnPlateau) to adjust the learning rate during training.
- Regularization: Use techniques like dropout, weight decay, and early stopping to prevent overfitting.
- Evaluation Metrics: Use appropriate evaluation metrics for ranking, such as:
- Mean Average Precision (MAP)
- Normalized Discounted Cumulative Gain (NDCG)
- Precision@k, Recall@k
- Experimentation: The specific architecture and hyperparameters that work best will depend on your data. Experiment with different options and carefully evaluate the results.
- Pre-training: Consider pre-training your re-ranking module on a large dataset of query-document pairs before fine-tuning it on your specific task.
- Freezing Layers: During initial training, consider freezing the weights of the Sentence Transformer. This can help to stabilize training and prevent the re-ranking module from overfitting to the Sentence Transformer's representations. After the re-ranking module has converged, you can unfreeze the Sentence Transformer and fine-tune the entire model.
- Normalization: It is good practice to normalize the token embeddings before the similarity calculation.
By following these steps and experimenting with different architectures and hyperparameters, you should be able to create a re-ranker that effectively leverages both the dense and token-level representations from your Sentence Transformer model. Remember to monitor your evaluation metrics closely and iterate on your design as needed.