Random in colab does not work

I am using colab.

I set the following:

seed = 1

torch.manual_seed(seed)

torch.cuda.manual_seed(seed)

torch.cuda.manual_seed_all(seed) # if you are using multi-GPU.

np.random.seed(seed) # Numpy module.

random.seed(seed) # Python random module.

torch.manual_seed(seed)

torch.backends.cudnn.benchmark = False

torch.backends.cudnn.deterministic = True

If i random the second time, it gives me different result.

tensor_rand_un = torch.rand(3,5)
print("tensor_rand_un :", tensor_rand_un)

tensor_rand_un = torch.rand(3,5)
print("tensor_rand_un :", tensor_rand_un)

Output:

tensor_rand_un : tensor([[0.7576, 0.2793, 0.4031, 0.7347, 0.0293],
        [0.7999, 0.3971, 0.7544, 0.5695, 0.4388],
        [0.6387, 0.5247, 0.6826, 0.3051, 0.4635]])
tensor_rand_un : tensor([[0.4550, 0.5725, 0.4980, 0.9371, 0.6556],
        [0.3138, 0.1980, 0.4162, 0.2843, 0.3398],
        [0.5239, 0.7981, 0.7718, 0.0112, 0.8100]])

However, if I restart random again, then it gives me the same random again.

seed = 1
torch.manual_seed(seed)
tensor_rand_un = torch.rand(3,5)
print("tensor_rand_un :", tensor_rand_un)
tensor_rand_un : tensor([[0.7576, 0.2793, 0.4031, 0.7347, 0.0293],
        [0.7999, 0.3971, 0.7544, 0.5695, 0.4388],
        [0.6387, 0.5247, 0.6826, 0.3051, 0.4635]])

Why I have random number every time and why I need to reset the random? how can I get the same random all the time in colab?

This is expected since the seed will define the sequence the pseudorandom number generator will generate. Seeding the code will not force the PRNG to return the same values for all calls.

You could either re-seed the code after each call into the PRNG or just use a constant. Keep in mind that your values are not random at all anymore since you are sampling only once and would then reuse exactly the same constant values.

1 Like