This code should work:
kh, kw = 2, 2
dh, dw = 2, 2
input = torch.randint(10, (1, 2, 4, 4))
input_windows = input.unfold(2, kh, dh).unfold(3, kw, dw)
input_windows = input_windows.contiguous().view(*input_windows.size()[:-2], -1)
input_windows_sorted = input_windows.sort(descending=True)[0]
input_windows_sorted = input_windows_sorted.view(*input.size())
input_windows_sorted = input_windows_sorted.transpose(2, 3)
input_windows_sorted = input_windows_sorted.unfold(3, kh, kw)

Let me know, if that works for you.