Sorry, to be clearer, you are flattening the 1st and 3rd dimensions together, then selecting the valid indices to keep.  Look at torch.take(), which can be applied after you flatten the array.  You’ll have to create a second array with the valid indices to use it.