Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pytorch generator with manual seed resulting in different random numbers

Tags:

pytorch

enter image description here

I was expecting that the draws from the multinomial distribution would be reproducible too. Why am I getting this behavior and how do I fix this?

I am trying to draw from a multinomial distribution and want the draws to be reproducible.

like image 537
aram Avatar asked Sep 14 '25 09:09

aram


1 Answers

Passing generator to torch.multinomial will just tell pytorch which generator to use, it will not reset its states.

Try this

import torch
g = torch.Generator().manual_seed(1)
p = torch.rand(3, generator=g)
initial_state = g.get_state()
print(torch.multinomial(p, num_samples=10, replacement=True, generator=g))
g.set_state(initial_state)
print(torch.multinomial(p, num_samples=10, replacement=True, generator=g))
like image 100
TanjiroLL Avatar answered Sep 17 '25 18:09

TanjiroLL



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!