Clamp logit_scale to prevent numerical instability#530
Open
Mr-Neutr0n wants to merge 1 commit intoopenai:mainfrom
Open
Clamp logit_scale to prevent numerical instability#530Mr-Neutr0n wants to merge 1 commit intoopenai:mainfrom
Mr-Neutr0n wants to merge 1 commit intoopenai:mainfrom
Conversation
The logit_scale parameter (initialized to ln(1/0.07) ≈ 2.66) can grow unbounded during training since there is no upper bound enforced on it. When logit_scale becomes too large, the exponentiated value overflows and produces NaN/Inf in the similarity logits, causing training to diverge. This adds torch.clamp(logit_scale, max=100) after exponentiation, consistent with the original CLIP training procedure and other reference implementations (e.g., OpenCLIP). The cap of 100 corresponds to a temperature of 0.01, which is already an extremely sharp distribution and well beyond any practical operating point.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
torch.clamp(logit_scale, max=100)after exponentiation inCLIP.forward()to prevent the learned temperature parameter from causing numerical overflow during training/fine-tuning.Problem
The
logit_scaleparameter is learned during training with no upper bound enforced. As training progresses,self.logit_scalecan grow large enough thatself.logit_scale.exp()overflows, producingInf/NaNin the cosine similarity logits. This causes the contrastive loss to becomeNaNand training to diverge entirely.This is a known failure mode when fine-tuning CLIP, and the fix is consistent with:
open_clip/model.py)Fix
One-line addition in
clip/model.py:The max value of 100 corresponds to a minimum temperature of 0.01, which produces an extremely sharp softmax distribution and is well beyond any practical operating point.
Test plan