# Not using PreallocationTools.jl correctly

**URL:** https://discourse.julialang.org/t/not-using-preallocationtools-jl-correctly/123609
**Category:** Performance
**Tags:** question, forwarddiff, autodiff, preallocation
**Created:** [December 9, 2024, 9:14am UTC](https://discourse.julialang.org/t/not-using-preallocationtools-jl-correctly/123609 "2024-12-09T09:14:33Z")
**Posts on this page:** 1
**Showing post:** 8

<div class="post-metadata">

### Author: ![Nikos\_Gianniotis](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/nikos_gianniotis/32/11487_2.png) [@Nikos\_Gianniotis](https://discourse.julialang.org/u/Nikos_Gianniotis)
#### Post date: [December 9, 2024, 1:09pm UTC](https://discourse.julialang.org/t/not-using-preallocationtools-jl-correctly/123609/8 "2024-12-09T13:09:35Z")

</div>

I somehow managed to solve this, though I don’t understand exactly why this solution works. Basically, it has to do with the chunking in ForwardDiff.jl.

(This reply, [How to make this function compatible with ForwardDiff? - #9 by ChrisRackauckas](https://discourse.julialang.org/t/how-to-make-this-function-compatible-with-forwarddiff/67415/9) pointed me to the solution).

Staying with the code I posted above, the following does the trick:

```julia
aux(x) = logl!(C,x)
cfg1 = ForwardDiff.GradientConfig(aux, W, ForwardDiff.Chunk{1}())
# The call below is now fast and allocates far less
ForwardDiff.gradient(aux, W, cfg1) 

```

However: even if the above works, I am not sure why it does. Hence, to anyone that has the same problem and is reading this, I am not sure whether this is a good solution. Perhaps more knowledgeable people can offer a comment.

Also: letting ForwardDiff.jl decide on its own about the chunking, works even better:

```julia
cfg1 = ForwardDiff.GradientConfig(aux, W, ForwardDiff.Chunk{1}());
@btime ForwardDiff.gradient(aux, W, cfg1)
  10.771 μs (161 allocations: 39.89 KiB)

# VS

cfg = ForwardDiff.GradientConfig(aux, W);
@btime ForwardDiff.gradient(aux, W, cfg)
  2.956 μs (21 allocations: 18.17 KiB)

```

Obviously, it doesn’t beat the Enzyme solution above.

---

_[View the full topic](https://discourse.julialang.org/t/not-using-preallocationtools-jl-correctly/123609)._
