[BUG] Triton softmax(input, mask) returns NaN when the mask removes the row maximum
Describe the bug
Summary. The exported Triton softmax(input, mask) subtracts the row maximum before adding the mask. If the mask suppresses that maximum and every remaining logit is far below it (200 below in the example), every FP32 exponential can underflow to zero, and the whole row becomes NaN although the masked logits are finite. We propose keeping the initial shift, adding the mask, then subtracting the maximum of the masked row.
Suggested fix
--- a/deepspeed/ops/transformer/inference/triton/softmax.py
+++ b/deepspeed/ops/transformer/inference/triton/softmax.py
@@ -40,6 +40,7 @@
mask = tl.load(mask_ptrs, mask=col_offsets < n_cols, other=0).to(tl.float32)
row_minus_max = row - tl.max(row, axis=0)
row_minus_max = row_minus_max + mask
+ row_minus_max = row_minus_max - tl.max(row_minus_max, axis=0)
numerator = tl.exp(row_minus_max)
denominator = tl.sum(numerator, axis=0)
softmax_output = numerator / denominator
Moving the mask before the first maximum is not enough: for FP32 input [[-16777216, -16777216]] with mask [[-1, 0]] it returns [0.5, 0.5] instead of about [0.2689, 0.7311]. With the patch above, all 19 test cases match an FP64 reference on an A100: the 16 original FP16 and FP32 cases (eight of them ordinary controls), the large-value case above, and fully masked finite rows. Performance was not measured.
Scope
This affects direct callers of the exported softmax. DeepSpeed's own TritonSelfAttention uses its flash kernel on compute capability 8.0 and above, which adds the mask before taking the maximum; by the source, it reaches this softmax only on the non-flash, non-triangular path on older GPUs, which we did not run.
To Reproduce
import torch
from deepspeed.ops.transformer.inference.triton import softmax
x = torch.tensor([[0., -200.]], device="cuda", dtype=torch.float32)
mask = torch.tensor([[-1000., 0.]], device="cuda", dtype=torch.float32)
print(softmax(x, mask))
Expected behavior
Expected tensor([[0., 1.]], device='cuda:0'); actual tensor([[nan, nan]], device='cuda:0'). The same input in FP16 also fails, and so do -inf masks and a width-32 row with 31 kept keys.
System info
DeepSpeed c6af3faf29101ccd7efba77df4b0768058ff1f4a; PyTorch 2.9.1+cu128; Triton 3.8.0, using CUDA 12.9 ptxas V12.9.86 (TRITON_PTXAS_PATH); NVIDIA A100-SXM4-80GB. We called the exported module's wrapper from the DeepSpeed source tree without initializing the full package.