# Gradient of latent space variable in Turing?

**URL:** <https://discourse.julialang.org/t/gradient-of-latent-space-variable-in-turing/60941>\
**Category:** General Usage\
**Created:** [May 11, 2021, 9:08am UTC](https://discourse.julialang.org/t/gradient-of-latent-space-variable-in-turing/60941 "2021-05-11T09:08:42Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![marius311](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/marius311/32/3953_2.png) [@marius311](https://discourse.julialang.org/u/marius311)\
**Post date:** [May 11, 2021, 9:08am UTC](https://discourse.julialang.org/t/gradient-of-latent-space-variable-in-turing/60941/1 "2021-05-11T09:08:42Z")

</div>

I just started playing with Turing so this is probably a stupid question, is there an easy way (say for the purposes of inspecting my model) to get a posterior gradient of a latent space variable at fixed data? Here’s my attempt, which doesn’t seem to work with either Zygote or ForwardDiff:

```julia
@model function MyModel(x)
    σ ~ Uniform(0, 1)
    x ~ Normal(0, σ^2)
    return x
end

model = MyModel(missing)

Zygote.gradient(σ -> logprob"x=1 | model=model, σ=σ", 1)
ForwardDiff.derivative(σ -> logprob"x=1 | model=model, σ=σ", 1)

```

Both last two lines error (I’m guessing this is not the right way to do this.)

---

<div class="post-metadata">

**Author:** ![mohamed82008](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mohamed82008/32/18171_2.png) [@mohamed82008](https://discourse.julialang.org/u/mohamed82008)\
**Post date:** [May 12, 2021, 7:10am UTC](https://discourse.julialang.org/t/gradient-of-latent-space-variable-in-turing/60941/2 "2021-05-12T07:10:58Z")

</div>

The code generated by the `logprob` macro is not AD friendly. Try the function:

```julia
Turing.gradient_logp(Turing.ZygoteAD(), θ, Turing.VarInfo(model), model)

```

but you need to define the model using `MyModel(x)` and `θ` should be the vector of random variables in order of appearance in the model. In this case, it is just `[σ]`.
