T = torch.randn(3,4,5,6,7,8)
all_but_last_two_dims = T.size()[:-2]
U = T.view(*all_but_last_two_dims, -1)

I don’t think this is the most ideal solution especially if you want to flatten dimensions in the middle of a tensor but for your use case this should work.