# Zygote: Mutating arrays is not supported

**URL:** <https://discourse.julialang.org/t/zygote-mutating-arrays-is-not-supported/44309>\
**Category:** General Usage\
**Created:** [August 5, 2020, 6:36am UTC](https://discourse.julialang.org/t/zygote-mutating-arrays-is-not-supported/44309 "2020-08-05T06:36:19Z")\
**Posts on this page:** 4\
**Page:** 1

<div class="post-metadata">

**Author:** ![DeepQ](https://avatars.discourse-cdn.com/v4/letter/d/2bfe46/32.png) [@DeepQ](https://discourse.julialang.org/u/DeepQ)\
**Post date:** [August 5, 2020, 6:36am UTC](https://discourse.julialang.org/t/zygote-mutating-arrays-is-not-supported/44309/1 "2020-08-05T06:36:19Z")

</div>

I am trying to calculate the laplacian of a neural network using Flux library. My code is:

```julia
using Flux
using Zygote

model = Chain(Dense(2,5,sigmoid), Dense(5,1))

function laplace(x)
    a, b = size(x)
    Δ = Zygote.Buffer(zeros(b))
    deriv2 = sum(Diagonal(ones(a*b)).*Zygote.hessian(v -> sum(model(v)), x), dims=1)
    for i=1:b
        for j=1:a
            Δ[i] += deriv2[(i-1)*a+j]
        end
    end
    return copy(Δ)
end

gradient(x -> sum(laplace(x)), rand(2,5))

```

---

<div class="post-metadata">

**Author:** ![jling](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jling/32/212909_2.png) [@jling](https://discourse.julialang.org/u/jling)\
**Post date:** [August 5, 2020, 7:23am UTC](https://discourse.julialang.org/t/zygote-mutating-arrays-is-not-supported/44309/2 "2020-08-05T07:23:01Z")

</div>

it is indeed not supported

---

<div class="post-metadata">

**Author:** ![DeepQ](https://avatars.discourse-cdn.com/v4/letter/d/2bfe46/32.png) [@DeepQ](https://discourse.julialang.org/u/DeepQ)\
**Post date:** [August 5, 2020, 7:45am UTC](https://discourse.julialang.org/t/zygote-mutating-arrays-is-not-supported/44309/3 "2020-08-05T07:45:50Z")

</div>

I am using Zygote.Buffer.

---

<div class="post-metadata">

**Author:** ![jondeuce](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jondeuce/32/16378_2.png) [@jondeuce](https://discourse.julialang.org/u/jondeuce)\
**Post date:** [August 5, 2020, 3:42pm UTC](https://discourse.julialang.org/t/zygote-mutating-arrays-is-not-supported/44309/4 "2020-08-05T15:42:15Z")

</div>

I can’t see at first glance what is causing the error, but note that in any case differentiating loops like this tends to be slow in Zygote. I would drop the `Buffer` and write

```julia
Δ = vec(sum(reshape(deriv2, a, b); dims = 1))

```

Also, the expression for `deriv2` seems to be equivalent to

```julia
deriv2 = diag(Zygote.hessian(v -> sum(model(v)), x))

```

and there may be more efficient ways to compute the diagonal of the hessian with Zygote.
