How can ignore_index be negative ? I may not have grasped what it is about, but shouldn’t it be an integer value between 0 and C-1 ?
numerator = output * target  is an element-wise operation and has the same size as the mask, that means if you weight it some of the terms with 0 before doing the sum, you’ll be fine as gradient w.r.t these terms will be zero. the only downside is that it actually computes everything before throwing out the ignored indices, but (at least to me) it’s much simpler to read, depends on the ratio of samples you throw out.