Are you looking for this?

  
      github.com
  
  
    renebidart/adv-denoising/blob/1400e147ee517667fb9aeb67fa3b38a233c4ab3b/models/StochasticPool2d.py#L61-L78 80

# def gen_random(values):
#     if torch.sum(values) != 0:
#         idx = torch.multinomial(values, num_samples=1)
#     else:
#         idx = torch.randint(0, values.shape[0], size=(1,)).type(torch.LongTensor)
#     return values[idx]


# init_size = x.shape


# x = F.pad(x, self._padding(x), mode='reflect')
# x = x.unfold(2, self.kernel_size[0], self.stride[0]).unfold(3, self.kernel_size[1], self.stride[1])
# x = x.contiguous().view(-1, 4)


# x = torch.stack([
#          gen_random(x_i) for i, x_i in enumerate(torch.unbind(x, dim=0), 0)
#         ], dim=0)
# x = x.contiguous().view(init_size[0], init_size[1], int(init_size[2]/2), int(init_size[3]/2))
# return x