Pytorch-metric-learning

Latest version: v2.7.0

Safety actively analyzes 681866 Python packages for vulnerabilities to keep your Python projects secure.

Scan your dependencies

Page 8 of 9

0.9.90

********** Summary **********
The main update is the new distances module, which adds an extra level of modularity to loss functions. It is a pretty big design change, which is why so many arguments have become obsolete. See [the documentation](https://kevinmusgrave.github.io/pytorch-metric-learning/distances/) for a description of the new module.

Other updates include support for half-precision, new regularizers and mixins, improved documentation, and default values for most initialization parameters.


********** Breaking Changes **********

Dependencies
This library now requires PyTorch >= 1.6.0. Previously there was no explicit version requirement.

Losses and Miners
All loss functions
normalize_embeddings has been removed
- If you never used this argument, nothing needs to be done.
- normalize_embeddings = True: just remove the argument.
- normalize_embeddings = False: remove the argument and instead pass it into a distance object. For example:
python
from pytorch_metric_learning.distances import LpDistance
loss_func = TripletMarginLoss(distance=LpDistance(normalize_embeddings=False))


ContrastiveLoss, GenericPairLoss, BatchHardMiner, HDCMiner, PairMarginMiner
use_similarity has been removed
- If you never used this argument, nothing needs to be done.
- use_similarity = True: remove the argument and:
python
if you had set normalize_embeddings = False
from pytorch_metric_learning.distances import DotProductSimilarity
loss_func = ContrastiveLoss(distance=DotProductSimilarity(normalize_embeddings=False))

otherwise
from pytorch_metric_learning.distances import CosineSimilarity
loss_func = ContrastiveLoss(distance=CosineSimilarity())


squared_distances has been removed
- If you never used this argument, nothing needs to be done.
- squared_distances = True: remove the argument and instead pass power=2 into a distance object. For example:
python
from pytorch_metric_learning.distances import LpDistance
loss_func = ContrastiveLoss(distance=LpDistance(power=2))

- squared_distances = False: just remove the argument.

ContrastiveLoss, TripletMarginLoss
power has been removed
- If you never used this argument, nothing needs to be done.
- power = 1: just remove the argument
- power = X, where X != 1: remove the argument and instead pass it into a distance object. For example:
python
from pytorch_metric_learning.distances import LpDistance
loss_func = TripletMarginLoss(distance=LpDistance(power=2))


TripletMarginLoss
distance_norm has been removed
- If you never used this argument, nothing needs to be done.
- distance_norm = 2: just remove the argument
- distance_norm = X, where X != 2: remove the argument and instead pass it as p into a distance object. For example:
python
from pytorch_metric_learning.distances import LpDistance
loss_func = TripletMarginLoss(distance=LpDistance(p=1))


NPairsLoss
l2_reg_weight has been removed
- If you never used this argument, nothing needs to be done.
- l2_reg_weight = 0: just remove the argument
- l2_reg_weight = X, where X > 0: remove the argument and instead pass in an LpRegularizer and weight:
python
from pytorch_metric_learning.regularizers import LpRegularizer
loss_func = NPairsLoss(embedding_regularizer=LpRegularizer(), embedding_reg_weight=0.123)


SignalToNoiseRatioContrastiveLoss
regularizer_weight has been removed
- If you never used this argument, nothing needs to be done.
- regularizer_weight = 0: just remove the argument
- regularizer_weight = X, where X > 0: remove the argument and instead pass in a ZeroMeanRegularizer and weight:
python
from pytorch_metric_learning.regularizers import LpRegularizer
loss_func = SignalToNoiseRatioContrastiveLoss(embedding_regularizer=ZeroMeanRegularizer(), embedding_reg_weight=0.123)


SoftTripleLoss
reg_weight has been removed
- If you never used this argument, do the following to obtain the same default behavior:
python
from pytorch_metric_learning.regularizers import SparseCentersRegularizer
weight_regularizer = SparseCentersRegularizer(num_classes, centers_per_class)
SoftTripleLoss(..., weight_regularizer=weight_regularizer, weight_reg_weight=0.2)

- reg_weight = X: remove the argument, and use the SparseCenterRegularizer as shown above.

WeightRegularizerMixin and all classification loss functions
- If you never specified regularizer or reg_weight, nothing needs to be done.
- regularizer = X: replace with weight_regularizer = X
- reg_weight = X: replace with weight_reg_weight = X

Classification losses
- For all losses and miners, default values have been set for as many arguments as possible. This has caused a change in ordering in positional arguments for several of the classification losses. The typical form is now:
python
loss_func = SomeClassificatinLoss(num_classes, embedding_loss, <keyword arguments>)

See the documentation for specifics

Reducers
ThresholdReducer
threshold has been replaced by low and high
- Replace threshold = X with low = X

Regularizers
All regularizers
normalize_weights has been removed
- If you never used this argument, nothing needs to be done.
- normalize_weights = True: just remove the argument.
- normalize_weights = False: remove the argument and instead pass normalize_embeddings = False into a distance object. For example:
python
from pytorch_metric_learning.distances import DotProductSimilarity
loss_func = RegularFaceRegularizer(distance=DotProductSimilarity(normalize_embeddings=False))


Inference

MatchFinder
mode has been removed
- Replace mode="sim" with either distance=CosineSimilarity() or distance=DotProductSimilarity()
- Replace mode="dist" with distance=LpDistance()
- Replace mode="squared_dist" with distance=LpDistance(power=2)



********** New Features **********
Distances
Distances bring an additional level of modularity to building loss functions. Here's an example of how they work.

Consider the TripletMarginLoss in its default form:
python
from pytorch_metric_learning.losses import TripletMarginLoss
loss_func = TripletMarginLoss(margin=0.2)

This loss function attempts to minimize [d<sub>ap</sub> - d<sub>an</sub> + margin]<sub>+</sub>.

In other words, it tries to make the anchor-positive distances (d<sub>ap</sub>) smaller than the anchor-negative distances (d<sub>an</sub>).

Typically, d<sub>ap</sub> and d<sub>an</sub> represent Euclidean or L2 distances. But what if we want to use a squared L2 distance, or an unnormalized L1 distance, or completely different distance measure like signal-to-noise ratio? With the distances module, you can try out these ideas easily:
python
TripletMarginLoss with squared L2 distance
from pytorch_metric_learning.distances import LpDistance
loss_func = TripletMarginLoss(margin=0.2, distance=LpDistance(power=2))

TripletMarginLoss with unnormalized L1 distance
loss_func = TripletMarginLoss(margin=0.2, distance=LpDistance(normalize_embeddings=False, p=1))

TripletMarginLoss with signal-to-noise ratio
from pytorch_metric_learning.distances import SNRDistance
loss_func = TripletMarginLoss(margin=0.2, distance=SNRDistance())


You can also use similarity measures rather than distances, and the loss function will make the necessary adjustments:
python
TripletMarginLoss with cosine similarity
from pytorch_metric_learning.distances import CosineSimilarity
loss_func = TripletMarginLoss(margin=0.2, distance=CosineSimilarity())

With a similarity measure, the TripletMarginLoss internally swaps the anchor-positive and anchor-negative terms: [s<sub>an</sub> - s<sub>ap</sub> + margin]<sub>+</sub>. In other words, it will try to make the anchor-negative similarities smaller than the anchor-positive similarities.

All **losses, miners, and regularizers** accept a distance argument. So you can try out the MultiSimilarityMiner using SNRDistance, or the NTXentLoss using LpDistance(p=1) and so on. Note that some losses/miners/regularizers have restrictions on the type of distances they can accept. For example, some classification losses only allow CosineSimilarity or DotProductSimilarity as their distance measure between embeddings and weights. To view restrictions for specific loss functions, see [the documentation](https://kevinmusgrave.github.io/pytorch-metric-learning/losses/)

There are four distances implemented (LpDistance, SNRDistance, CosineSimilarity, DotProductSimilarity), but of course you can extend the BaseDistance class and write a custom distance measure if you want. See [the documentation](https://kevinmusgrave.github.io/pytorch-metric-learning/distances/) for more.

EmbeddingRegularizerMixin
All loss functions now extend EmbeddingRegularizerMixin, which means you can optionally pass in (to any loss function) an embedding regularizer and its weight. The embedding regularizer will compute some loss based on the embeddings alone, ignoring labels and tuples. For example:
python
from pytorch_metric_learning.regularizers import LpRegularizer
loss_func = MultiSimilarityLoss(embedding_regularizer=LpRegularizer(), embedding_reg_weight=0.123)


WeightRegularizerMixin is now a subclass of WeightMixin
As in previous versions, classification losses extend WeightRegularizerMixin, which which means you can optionally pass in a weight matrix regularizer. Now that WeightRegularizerMixin extends WeightMixin, you can also specify the weight initialization function [in object form](https://kevinmusgrave.github.io/pytorch-metric-learning/common_functions/#torchinitwrapper):
python
from ..utils import common_functions as c_f
import torch

use kaiming_uniform, with a=1 and mode='fan_out'
weight_init_func = c_f.TorchInitWrapper(torch.nn.kaiming_uniform_, a=1, mode='fan_out')
loss_func = SomeClassificationLoss(..., weight_init_func=weight_init_func)


New Regularizers
For increased modularity, the regularizers hard-coded in several loss functions were separated into their own classes. The new regularizers are:
- LpRegularizer
- SparseCentersRegularizer
- ZeroMeanRegularizer

Support for half-precision
In previous versions, various functions would break in half-precision (float16) mode. Now all distances, losses, miners, regularizers, and reducers work with half-precision, float32, and double (float64).

New collect_stats argument
All distances, losses, miners, regularizers, and reducers now have a collect_stats argument, which is True by default. This means that various statistics are collected in each forward pass, and these statistics can be useful to look at during experiments. However, if you don't care about collecting stats, you can set collect_stats=False, and the stat computations will be skipped.

Other updates

- You no longer have to explicitly call .to(device) on classification losses, because their weight matrices will be moved to the correct device during the forward pass if necessary. See issue https://github.com/KevinMusgrave/pytorch-metric-learning/issues/139

- Reasonable default values have been set for all losses and miners, to make these classes easier to try out. In addition, equations have been added to many of the class descriptions in the documentation. See issue https://github.com/KevinMusgrave/pytorch-metric-learning/issues/140

- Calls to torch.nonzero have been replaced by torch.where.

- The documentation for ArcFaceLoss and CosFaceLoss have been fixed to reflect the actual usage. (The documentation previously indicated that some arguments are positional, when they are actually keyword arguments.)

- The tensorboard_folder argument for utils.logging_presets.get_record_keeper is now optional. If you don't specify it, then there will be no tensorboard logs, which can be useful if speed is a concern.

- The loss dictionary in BaseTrainer is now cleared at the end of each epoch, to free up GPU memory. See issue https://github.com/KevinMusgrave/pytorch-metric-learning/issues/171

0.9.89

CrossBatchMemory
- Fixed bug where CrossBatchMemory would use self-comparisons as positive pairs. This was uniquely a CrossBatchMemory problem because of the nature of adding each current batch to the queue.
- Fixed bug where DistanceWeightedMiner would not work with CrossBatchMemory due to missing ref_label
- Changed 3rd keyword argument of forward() from input_indices_tuple to indices_tuple to be consistent with all other losses.

AccuracyCalculator
- Fixed bug in AccuracyCalculator where it would return NaN if the reference set contained none of query set labels. Now it will log a warning and return 0.

BaseTester
- Fixed bug where "compared_to_training_set" mode of BaseTester fails due to list(None) bug.

InferenceModel
- New get_nearest_neighbors function will return nearest neighbors of a query. By btseytlin

Loss and miner utils
- Switched to fill_diagonal_ in the get_all_pairs_indices and get_all_triplets_indices code, instead of creating torch.eye.

0.9.88

Bug fix
Removed the circular import which caused an ImportError when the reducers module was imported before anything else. See 125

0.9.87

v0.9.87 comes with some major changes that may cause your existing code to break.

**BREAKING CHANGES**
Losses
- The avg_non_zero_only init argument has been removed from ContrastiveLoss, TripletMarginLoss, and SignalToNoiseRatioContrastiveLoss. Here's how to translate from old to new code:
- avg_non_zero_only=True: Just remove this input parameter. Nothing else needs to be done as this is the default behavior.
- avg_non_zero_only=False: Remove this input parameter and replace it with reducer=reducers.MeanReducer(). You'll need to add this to your imports: from pytorch_metric_learning import reducers
- learnable_param_names and num_class_per_param has been removed from BaseMetricLossFunction due to lack of use.
- MarginLoss is the only built-in loss function that is affected by this. Here's how to translate from old to new code:
- learnable_param_names=["beta"]: Remove this input parameter and instead pass in learn_beta=True.
- num_class_per_param=N: Remove this input parameter and instead pass in num_classes=N.

AccuracyCalculator
- The average_per_class init argument is now avg_of_avgs. The new name better reflects the functionality.
- The old way to import was: from pytorch_metric_learning.utils import AccuracyCalculator. This will no longer work. The new way is: from pytorch_metric_learning.utils.accuracy_calculator import AccuracyCalculator. The reason for this change is to avoid an unnecessary import of the Faiss library, especially when this library is used in other packages.


**New feature: Reducers**
Reducers specify how to go from many loss values to a single loss value. For example, the ContrastiveLoss computes a loss for every positive and negative pair in a batch. A reducer will take all these per-pair losses, and reduce them to a single value. Here's where reducers fit in this library's flow of filters and computations:

Your Data --> Sampler --> Miner --> Loss --> Reducer --> Final loss value

Reducers are passed into loss functions like this:
python
from pytorch_metric_learning import losses, reducers
reducer = reducers.SomeReducer()
loss_func = losses.SomeLoss(reducer=reducer)
loss = loss_func(embeddings, labels) in your training for-loop

Internally, the loss function creates a dictionary that contains the losses and other information. The reducer takes this dictionary, performs the reduction, and returns a single value on which .backward() can be called. Most reducers are written such that they can be passed into any loss function.

See [the documentation](https://kevinmusgrave.github.io/pytorch-metric-learning/reducers/) for details.


**Other updates**
Utils
Inference
- InferenceModel has been added to the library. It is a model wrapper that makes it convenient to find matching pairs within a batch, or from a set of pairs. Take a look at [this notebook](https://colab.research.google.com/github/KevinMusgrave/pytorch-metric-learning/blob/master/examples/notebooks/Inference.ipynb) to see example usage.

AccuracyCalculator
- The k value for k-nearest neighbors can optionally be specified as an init argument.
- k-nn based metrics now receive knn distances in their kwargs. See 118 by marijnl

Other stuff
Unit tests were added for almost all losses, miners, regularizers, and reducers.

**Bug fixes**
Trainers
- Fixed a labels related bug in TwoStreamMetricLoss. See 112 by marijnl

Loss and miner utils
- Fixed bug where convert_to_triplets could encounter a RuntimeError. See 95

0.9.86

**Losses + miners**
- Added assertions to make sure the number of input embeddings is equal to the number of input labels.
- MarginLoss
- Fixed bug where loss explodes if self.nu > 0 and number of active pairs is 0. See https://github.com/KevinMusgrave/pytorch-metric-learning/issues/98#issue-618347291


**Trainers**
- Added freeze_these to the init arguments of BaseTrainer. This optional argument takes a list or tuple of strings as input. The strings must correspond to the names of models or loss functions, and these models/losses will have their parameters frozen during training. Their corresponding optimizers will also not be stepped.
- Fixed indices shifting bug in the TwoStreamMetricLoss trainer. By marijnl

**Testers**
- BaseTester
- Pass in epoch to visualizer_hook
- Added eval option to get_all_embeddings. By default it is True, and will set the input trunk and embedder to eval() mode.

**Utils**
- HookContainer
- Allow training to resume from best model, rather than just the latest model.
- **The best models are now saved as <model_name>_best<epoch>.pth rather than <model_name>_best.pth.** To easily get the new suffix for loading the best model you can do:
python
from pytorch_metric_learning.utils import common_functions as c_f
_, best_model_suffix = c_f.latest_version(your_model_folder, best=True)
best_trunk = "trunk_{}.pth".format(best_model_suffix)
best_embedder = "embedder_{}.pth".format(best_model_suffix)

0.9.85

**Trainers**
- Added [TwoStreamMetricLoss](https://kevinmusgrave.github.io/pytorch-metric-learning/trainers/#twostreammetricloss). By marijnl.
- All BaseTrainer child classes now accept *args and pass it to BaseTrainer, so that you can use positional arguments when you init those child classes, rather than just keyword arguments.
- Fixed a key verification bug in CascadedEmbeddings that made it impossible to pass in an optimizer for the metric loss.

**Testers**
- Added [GlobalTwoStreamEmbeddingSpaceTester](https://kevinmusgrave.github.io/pytorch-metric-learning/testers/#globaltwostreamembeddingspacetester). By marijnl
- BaseTester
- The input visualizer should now implement the fit_transform method, rather than fit and transform separately.
- Fixed various bugs related to label_hierarchy_level
- WithSameParentLabelTester
- Fixed bugs that were causing this tester to encounter a runtime error.

**Utils**
- HookContainer
- Added methods for retrieving loss and accuracy history.
- Fixed bug where the value for best_epoch could be None.
- AccuracyCalculator
- Got rid of bug that returned NaN when dealing with classes containing only one sample.
- Added average_per_class option, which computes the average accuracy per class, and then returns the average of those averages. This can be useful when evaluating datasets with unbalanced classes.

**Other stuff**
- Added the with-hooks and with-hooks-cpu pip install options. The following will install record-keeper, faiss-gpu, and tensorboard, in addition to pytorch-metric-learning

pip install pytorch-metric-learning[with-hooks]

If you don't have a GPU you can do:

pip install pytorch-metric-learning[with-hooks-cpu]

- Added more tests for AccuracyCalculator

Page 8 of 9

© 2024 Safety CLI Cybersecurity Inc. All Rights Reserved.