def masked_softmax(X, mask=None):
"""Softmax over the last axis with zero weight where mask is False."""
if mask is None:
return F.softmax(X, dim=-1)
# Most negative finite value: zero weight at any precision, no NaN
X = X.masked_fill(~mask, torch.finfo(X.dtype).min)
weights = F.softmax(X, dim=-1)
# A query without any valid key gets zero weights, not a uniform row
return torch.where(mask.any(-1, keepdim=True), weights, 0.0)