Fix gamma-zero focal loss NaN - #576
Conversation
|
Hi @steve5636! Thank you for your pull request and welcome to our community. Action RequiredIn order to merge any pull request (code, docs, etc.), we require contributors to sign our Contributor License Agreement, and we don't seem to have one on file for you. ProcessIn order for us to review and merge your suggested changes, please sign at https://code.facebook.com/cla. If you are contributing on behalf of someone else (eg your employer), the individual CLA may not be sufficient and your employer may need to sign the corporate CLA. Once the CLA is signed, our tooling will perform checks and validations. Afterwards, the pull request will be tagged with If you have received this in error or have any questions, please contact us at cla@meta.com. Thanks! |
|
Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Meta Open Source project. Thanks! |
Fixes #575
Summary
This PR fixes two related numerical issues around the SAM3 presence loss path:
sigmoid_focal_loss(..., gamma=0)away from the reduced Triton focal kernel and through the existing PyTorch fallback pathclamp(...)For
gamma=0, sigmoid focal loss is equivalent to alpha-weighted BCE. The reduced Triton backward currently computes(1 - p_t) ** (gamma - 1), which becomes0 ** -1 = inffor saturated correct predictions, and later produces0 * inf = NaN.Verification
python -m py_compile sam3/train/loss/loss_fns.py sam3/model/decoder.pysigmoid_focal_loss(x=[[18.0]], y=[[1.0]], alpha=0.5, gamma=0.0)now returns a finite gradient ([[0.0]]).I also verified this locally on a SAM3 fine-tuning run where the original issue first appeared as a NaN gradient in
SigmoidFocalLossReducedBackward; after the fix, the epoch-6 canary reached the final dataloader step with finite loss and outputs.