lightly-ai / lightly-ai/lightly

Add configurable normalization epsilon for NTXentLoss

Open
#1,259 1 comment 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

enhancement
Dominant language
Python
Stars
3.8k
Forks
367
Avg merge
3d 22h
Merged PRs (30d)
5

Description

When training with half-precision I noticed that normalization in NTXentLoss can give NaN values.

in forward method, there is a code:

        # normalize the output to length 1
        out0 = nn.functional.normalize(out0, dim=1)
        out1 = nn.functional.normalize(out1, dim=1)

It uses torch.nn.functional.normalize function with default 1e-12 epsilon, what gives 0 for half precision. As a result we have division by zero and NaN in output.

The way to solve it is to add optional normalization epsilon parameter in NTXentLoss initializer and use it when calling torch.nn.functional.normalize function.

Please let me know if there is any mistake in my understanding.
If it's okay for you, I can propose a pull request.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start by locating NTXentLoss and its forward method, then inspect the existing torch.nn.functional.normalize calls and related tests. Reproduce the half-precision NaN behavior if possible, and verify that a configurable epsilon is used for both normalizations while preserving the current default behavior.

Written by the indexing model from the issue text.

Assessment

Tech stack
python, pytorch
Domain
machine-learning
Issue type
Bug
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Clearly specified
Newbie friendliness
52/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.