# Lux + Turing: How to not to use a global variable for state \`st\`

**URL:** <https://discourse.julialang.org/t/lux-turing-how-to-not-to-use-a-global-variable-for-state-st/110878>\
**Category:** General Usage\
**Tags:** question, turing, lux\
**Created:** [February 28, 2024, 8:34am UTC](https://discourse.julialang.org/t/lux-turing-how-to-not-to-use-a-global-variable-for-state-st/110878 "2024-02-28T08:34:22Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![schlichtanders](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/schlichtanders/32/32145_2.png) [@schlichtanders](https://discourse.julialang.org/u/schlichtanders)\
**Post date:** [February 28, 2024, 8:34am UTC](https://discourse.julialang.org/t/lux-turing-how-to-not-to-use-a-global-variable-for-state-st/110878/1 "2024-02-28T08:34:22Z")

</div>

Hi there,

Lux state handling, while lovely explicit, seems sometimes a bit difficult.  
Here the example from the [Bayesian Lux Tutorial](https://lux.csail.mit.edu/dev/tutorials/intermediate/5_BayesianNN)

```julia
# Specify the probabilistic model.
@model function bayes_nn(xs, ts)
    global st

    # Sample the parameters
    nparameters = Lux.parameterlength(nn)
    parameters ~ MvNormal(zeros(nparameters), Diagonal(abs2.(sig .* ones(nparameters))))

    # Forward NN to make predictions
    preds, st = nn(xs, vector_to_parameters(parameters, ps), st)

    # Observe each prediction.
    for i in 1:length(ts)
        ts[i] ~ Bernoulli(preds[i])
    end
end

```

How can I prevent the global variable in a way that the state update is efficiently optimized by the compiler?

EDIT: I opened a more generic Issue on Lux.jl for this question [Documentation Request: Standardize the handling of the state `st` · Issue #515 · LuxDL/Lux.jl · GitHub](https://github.com/LuxDL/Lux.jl/issues/515)

---

<div class="post-metadata">

**Author:** ![avikpal](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/avikpal/32/6550_2.png) [@avikpal](https://discourse.julialang.org/u/avikpal)\
**Post date:** [February 29, 2024, 12:06am UTC](https://discourse.julialang.org/t/lux-turing-how-to-not-to-use-a-global-variable-for-state-st/110878/2 "2024-02-29T00:06:20Z")

</div>

Use [Utilities | LuxDL Docs](https://lux.csail.mit.edu/dev/api/Lux/utilities#Lux.StatefulLuxLayer). It can handle both cases where the state type changes and the state type is fixed.

That said if your state changes type across iterations it is probably some problem in the model implementation. Most state type changes should be performed using `update_state` / `testmode` outside of main model calls.
