[Bug] GradCache replay downcasts FP64 embeddings to FP32 in the surrogate dot product
Summary
In the GradCache backward replay, the surrogate is always computed in FP32 (gradcache.py#L316-L318):
# Under autocast the cached gradients are reduced-precision while this re-embedding
# (inside backward, outside autocast) is fp32, so compute the surrogate in fp32.
surrogate = torch.dot(reps_mb.flatten().float(), grad_mb.flatten().float()) * grad_outputThe comment explains why FP32 is needed under autocast, and that part makes sense. But .float() also downcasts when the model and the cached gradients are FP64, so in double precision the cached losses no longer match their non-cached counterparts to FP64 accuracy.
Environment
Tested at cad21198 with PyTorch 2.13.0+cu130 on 2× RTX 5090. The same line is unchanged on current main (4a3b5cd6), but I haven't rerun the numbers there.
Steps to reproduce
I called CachedMultipleNegativesRankingLoss (scale=20, cos_sim, gather_across_devices=True) on a tiny FP64 encoder module with dropout 0, on two ranks with eight query/document pairs, followed by one SGD step. To use a plain nn.Module as the encoder, I created the loss with __new__ to skip the SentenceTransformer type check in the constructor. I compared mini-batch sizes 2 and 4 with the same loss computed directly in FP64 without caching.
| Cached vs. direct FP64 | Max abs difference (gradient and SGD update) |
|---|---|
| Current code (both mini-batch sizes) | 1.15692e-7 |
| Keeping FP64 in the surrogate (mini-batch 2 / 4) | 2.6645e-15 / 3.5527e-15 |
The relative L2 difference before the change is 1.64960e-8. Note that the two mini-batch sizes agree with each other before the change, so comparing mini-batch sizes alone doesn't reveal this.
This was not a full SentenceTransformer training run.
Expected behavior
With an FP64 model, the cached losses should match the non-cached result to FP64 precision, while the FP32 upcast under autocast stays as it is.
Proposed fix
Keep at least FP32, but don't go below the inputs' precision:
surrogate_dtype = torch.promote_types(reps_mb.dtype, grad_mb.dtype)
if surrogate_dtype in (torch.float16, torch.bfloat16):
surrogate_dtype = torch.float32
surrogate = torch.dot(
reps_mb.flatten().to(surrogate_dtype), grad_mb.flatten().to(surrogate_dtype)
) * grad_outputFP16/BF16 (including the autocast case, where reps_mb is FP32 and grad_mb is reduced precision) still use FP32, FP32 stays FP32, and FP64 stays FP64.
I realize FP64 training with sentence-transformers is uncommon, so this is low priority; it came up while checking the cached losses against a direct computation.
Source: huggingface/sentence-transformers