from pytorch_metric_learning.utils import loss_and_miner_utils as lmu
from pytorch_metric_learning.miners.base_miner import BaseMiner
from pytorch_metric_learning.distances import DotProductSimilarity
class PairDoubleMarginMiner(BaseMiner):
"""
Returns positive pairs that have distance greater than a margin and negative
pairs that have distance less than a margin
"""
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Do you think it will work for cases when I have positives from different classes and potentially large amount of false negatives?
Assistant
Excellent question. This gets to the heart of the challenges in real-world metric learning.
Let's break down your PairDoubleMarginMiner and analyze its behavior in your specific scenarios.
The short answer is:
For positives from different classes:No, it will not work as written. The miner is fundamentally driven by the labels you provide.
For a large amount of false negatives:No, and it will likely be actively harmful. It will identify these false negatives as "hard negatives" and train your model to push them apart, which is the opposite of what you want.
Here is a detailed breakdown of why.
1. Code Analysis and a Critical Bug
First, let's understand what your miner is trying to do and spot a logical issue.
Intent:
Find "hard positives": Positive pairs (same label) whose similarity is too low.
Find "hard negatives": Negative pairs (different labels) whose similarity is too high.
Default Distance: You're using DotProductSimilarity. For this distance metric:
Higher values mean more similar.
The is_inverted property is True.
The Logic: Let's trace the mine function with is_inverted=True:
Positive Mining:pos_mask = pos_pair < self.pos_margin (e.g., < 0.2). This correctly finds positive pairs that are not similar enough. These are good candidates for training.
With your defaults neg_margin=0.8 and neg_upper_margin=0.6, this becomes: (neg_pair > 0.8) & (neg_pair < 0.6).
This condition can never be true. A number cannot be simultaneously greater than 0.8 and less than 0.6.
As a result, your miner will never select any negative pairs. Your loss function will only ever see positive pairs, and the model will likely collapse, mapping everything to the same point.
How to Fix the Bug:
You likely intended to find negatives in a similarity band. The parameters are probably flipped. You want to find negatives that are more similar than but less similar than .
With this fix (neg_pair > 0.6 and neg_pair < 0.8), the miner would select "semi-hard" negatives. If you just want to mine all hard negatives above a certain threshold, you would only need one margin:
# Simpler logic to find all hard negatives
neg_mask = (
neg_pair > self.neg_margin # e.g., > 0.6
if self.distance.is_inverted
else neg_pair < self.neg_margin
)
For the rest of this analysis, I will assume you have fixed this bug and are using a sensible logic for mining hard negatives (e.g., neg_pair > some_threshold).
2. The Problem with "Positives from Different Classes"
The core of any miner in pytorch-metric-learning is this line:
a1, p, a2, n = lmu.get_all_pairs_indices(labels, ref_labels)
This function determines what constitutes a "positive" or "negative" pair based on a simple rule:
Positive Pair:labels[i] == labels[j]
Negative Pair:labels[i] != labels[j]
The miner has no concept of semantic similarity beyond what the labels tell it. If you have an image of a "Siamese cat" (label=10) and an image of a "Persian cat" (label=11), the miner will classify this as a negative pair, even if you want your model to see them as similar.
Conclusion: The miner will fail for this use case.
Solution: You must handle this at the data/labeling stage. Before feeding data to the miner, you need to create "super-classes". For example, you would map both "Siamese cat" and "Persian cat" to a single parent label, like "cat" (e.g., label=2).
# Example of label pre-processing
# original_labels = [10, 11, 25, 26] # Siamese, Persian, German Shepherd, Golden Retriever
# mapping = {10: 2, 11: 2, 25: 3, 26: 3} # Map to Cat, Dog
# new_labels = [mapping[l] for l in original_labels] # --> [2, 2, 3, 3]
# Pass new_labels to the miner and loss function.
3. The Danger of False Negatives
This is the most critical issue for your miner.
What is a false negative? In your dataset, it's a pair of samples that have different labels but should be considered positive (i.e., they are semantically very similar). Example: Two different photos of the same person, but they were accidentally given two different person IDs in the labeling process.
How does your miner see a false negative? Since their labels are different (label_A != label_B), get_all_pairs_indices will mark them as a negative pair.
What happens next? Because they are semantically similar, your model will (hopefully) produce a high similarity score for them (e.g., dot_product = 0.9).
How does the mining logic react? Your miner's goal is to find hard negatives, which are negative pairs with high similarity. The false negative pair (different labels, similarity of 0.9) is a perfect candidate for a hard negative. The miner will select it with high probability.
The Catastrophic Result: The miner passes this "hard negative" pair to the loss function (e.g., ContrastiveLoss, TripletMarginLoss). The loss function's job is to push negative pairs apart. It will generate a loss signal that trains the model to decrease the similarity between these two items.
Conclusion: Your miner will actively work against your goal. It will find the very samples that are mislabeled as negatives and train the model to think they are truly different. This will severely degrade model performance.
Recommendations and Alternatives
Fix Your Miner's Logic: First, fix the bug in the neg_mask as described above so that it can mine negatives at all.
Clean Your Labels: The best solution is always to improve data quality. If you can identify and correct the false negatives and inconsistent positive labels, do it. This is often not feasible, which is why we need robust methods.
Use a More Robust Mining Strategy: Hard negative mining is notoriously sensitive to label noise and false negatives. Consider alternatives:
Semi-Hard Negative Mining: This is a much more stable strategy. It looks for negative pairs that are further away than the positive pair but still within the margin (i.e., they are hard, but not the absolute hardest). The TripletMarginMiner in the library can be configured for this (type_of_triplets='semihard'). The hardest negatives are often the noisy ones, so avoiding them can help.
No Mining / Easy Negative Mining: Instead of a miner, you could use a loss function that considers all pairs, like NTXentLoss (from self-supervised learning), which is often more robust to noisy pairs than margin-based losses. Alternatively, just use a simple ContrastiveLoss or TripletMarginLoss without a miner. This uses all possible pairs/triplets, which can be computationally expensive but avoids the pitfalls of focusing only on the hardest (and potentially wrong) examples.
Use a Noise-Robust Loss: Some loss functions are designed to handle label noise. While not a direct feature of pytorch-metric-learning, you could implement a loss with a mechanism like a symmetric cross-entropy term or by using techniques like label smoothing on top of a classification-based metric loss (ArcFaceLoss, CosFaceLoss).
In summary, while your custom miner is a good exercise, its hard-mining nature makes it fundamentally unsuitable and even dangerous for a dataset with a significant number of false negatives. I would strongly recommend switching to label pre-processing for your multi-class positives and using a more stable mining strategy like semi-hard negative mining to mitigate the impact of false negatives.