title: Is there an efficient way to create a random bit mask in Pytorch?
body: <p>I want to have a random bit mask that has some specified percent of <code>0</code>s. The function I devised is:</p>
  
  <pre><code>def create_mask(shape, rate):
      """
      The idea is, you take a random permutations of numbers. You then mod then
      mod it by the [number of entries in the bitmask] / [percent of 0s you
      want]. The number of zeros will be exactly the rate of zeros need. You
      can clamp the values for a bitmask.
      """
      mask = torch.randperm(reduce(operator.mul, shape, 1)).float().cuda()
      # Mod it by the percent to get an even dist of 0s.
      mask = torch.fmod(mask, reduce(operator.mul, shape, 1) / rate)
      # Anything not zero should be put to 1
      mask = torch.clamp(mask, 0, 1)
      return mask.view(shape)
  </code></pre>
  
  <p>To illustrate:</p>
  
  <pre><code>&gt;&gt;&gt; x = create_mask((10, 10), 10)
  &gt;&gt;&gt; x
  
      1     1     1     1     1     1     1     1     1     1
      1     1     1     1     1     1     0     1     1     1
      0     1     1     1     1     0     1     1     1     1
      0     1     1     1     1     1     1     1     1     1
      1     1     1     1     1     1     1     1     1     0
      1     1     1     1     1     1     1     1     1     1
      1     1     1     0     1     1     1     0     1     1
      0     1     1     1     1     1     1     1     1     1
      1     1     1     0     1     1     0     1     1     1
      1     1     1     1     1     1     1     1     1     1
  [torch.cuda.FloatTensor of size 10x10 (GPU 0)]
  </code></pre>
  
  <p>The main issue I have with this method is it requires the <code>rate</code> to divide the <code>shape</code>. I want a function that accepts an arbitrary decimal and gives approximately <code>rate</code> percent of 0s in the bitmask. Furthermore, I am trying to find a relatively efficient way of doing so. Hence, I would rather not move a <code>numpy</code> array from the CPU to the GPU. Is there an effiecient way of doing so that allows for a decimal <code>rate</code>?</p>