Pluto.jl icon indicating copy to clipboard operation
Pluto.jl copied to clipboard

`Random.seed!` not reproducible

Open jbrea opened this issue 2 years ago • 2 comments

22 09 20T09:22:18 I expected the two random numbers to be the same, similarly as to what we see in the repl when we run

julia> using Random

julia> Random.seed!(123)
TaskLocalRNG()

julia> rand()
0.521213795535383

julia> Random.seed!(123)
TaskLocalRNG()

julia> rand()
0.521213795535383

notebook.tar.gz

jbrea avatar Sep 20 '22 07:09 jbrea

ps. This happens on Julia 1.7 and 1.8. On Julia 1.6 Pluto behaves like the REPL.

jbrea avatar Sep 20 '22 09:09 jbrea

The difference with 1.6 is caused by this change: https://github.com/JuliaLang/julia/pull/40546. Each eval is made in a different task in Pluto, thus the RNG is not inherited.

Pangoraw avatar Sep 20 '22 17:09 Pangoraw

@Pangoraw thanks! Does that mean that this is the intended result? Should/could we change it?

fonsp avatar Sep 21 '22 16:09 fonsp

I would say that this is intentional, and the way to get reproducible RNG across cells is to create an RNG object and pass it to other cells. @Pangoraw WDYT?

fonsp avatar Oct 17 '22 12:10 fonsp

With the task based rng passing it explicitely does not work since the task local state is not preserved across cells:

rng = Random.seed!(42)

randn(rng, 10)

One workaround for reproducible randomness is to use the previous Random.MersenneTwister generator:

rng = Random.MersenneTwister(42)

randn(rng, 10)

To fix inside pluto, we need to use a persistent task with an loop to execute cells like in IJulia for example: https://github.com/JuliaLang/IJulia.jl/blob/2748004d9a7ad520a31397566885970072a6fd05/src/eventloop.jl#L4

Pangoraw avatar Nov 13 '22 12:11 Pangoraw