How to generate all possible combinations of 0-1 matrix in Cuda?

Hi, I have search for it and found below solution to generate all KxN possible combination of tensors with different arrangement of zeros and ones:

import itertools, torch
K, N = 2, 2
combinations = [torch.reshape(torch.tensor(i), (K, N)) for i in itertools.product([0, 1], repeat = K*N)]

then I can get this:

However, if I want to have bigger tensor combinations (e.g., with K, N = 5, 5), this process takes so much time. Can I please ask for a faster solution that it use GPU or Cuda for finding?

Hi Majid!

Here is a loop-free approach that uses pytorch tensor operations:

>>> import torch
>>> torch.__version__
'1.12.0'
>>> K = 2
>>> N = 2
>>> (torch.bitwise_and (torch.arange (2**(K*N), device = 'cuda').unsqueeze (-1), 2**torch.arange (K*N, device = 'cuda')) > 0).long().reshape (2**(K*N), K, N)
tensor([[[0, 0],
         [0, 0]],

        [[1, 0],
         [0, 0]],

        [[0, 1],
         [0, 0]],

        [[1, 1],
         [0, 0]],

        [[0, 0],
         [1, 0]],

        [[1, 0],
         [1, 0]],

        [[0, 1],
         [1, 0]],

        [[1, 1],
         [1, 0]],

        [[0, 0],
         [0, 1]],

        [[1, 0],
         [0, 1]],

        [[0, 1],
         [0, 1]],

        [[1, 1],
         [0, 1]],

        [[0, 0],
         [1, 1]],

        [[1, 0],
         [1, 1]],

        [[0, 1],
         [1, 1]],

        [[1, 1],
         [1, 1]]], device='cuda:0')

Note that for even small values of K and N there will be a lot of such
tensors. For your example of K = N = 5 your final result will consist
of about 800 million elements.

I don’t know of a pytorch function that will give you “all possible combinations”
of some arbitrary sets of values. For your “0-1” example, we may obtain the
desired result from the binary representations of the integers up to 2**(K*N).

Best.

K. Frank

1 Like