Ho actually reading the error message in details:

“output 0 of SelectBackward” This means that the problematic one is actually ni_pred

You do change this inplace when you do ni_pred[:, j] = xxx.

Can you try changing ni_pred to be a list and only before the return do return torch.stack(ni_pred, 1)?
something like:
ni_pred = torch.split(iv.clone().detach(), 1, dim=1)

# replace
ni_pred[:, j]
# by
ni_pred[j]

# replace
ni_pred[:, j] = xxx
# by
ni_pred.append(xxx)