# Using the DiffResult API

**URL:** <https://discourse.julialang.org/t/using-the-diffresult-api/5456>\
**Category:** Numerics\
**Tags:** question\
**Created:** [August 18, 2017, 7:18pm UTC](https://discourse.julialang.org/t/using-the-diffresult-api/5456 "2017-08-18T19:18:12Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Tamas\_Papp](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/tamas_papp/32/25949_2.png) [@Tamas\_Papp](https://discourse.julialang.org/u/Tamas_Papp)\
**Post date:** [August 18, 2017, 7:18pm UTC](https://discourse.julialang.org/t/using-the-diffresult-api/5456/1 "2017-08-18T19:18:12Z")

</div>

We are wrapping up the API for a GSOC project and I need some help about how to best integrate this into the existing Julia ecosystem.

From a theoretical point of view, the API needs a simple function `ℓ:ℝⁿ→ℝ` (log posterior), its gradient `∇ℓ:ℝⁿ→ℝⁿ`, and a starting point `θ`. For the first two, the user currently supplies a model object `model`, which, among other things (bookkeeping), mostly supports `logdensity(model, θ)` and `loggradient(model, θ)`. But since both the gradient and the density are frequently needed together, this is wasteful, and something like the [DiffResult](http://www.juliadiff.org/DiffBase.jl/latest/diffresult_api.html) API could be a good choice. Important: _type stability_ is crucial.

For the actual algorithm, possibly `ForwardDiff.jl` or `ReverseDiff.jl` may be used, or some other option (eg manual calculation of derivatives for some simple models). I don’t want the API to commit to either. This should be up to the user.

What I thought about: have an interface which supports

```julia
gradient!(result::DiffBase.DiffResult, model, θ)

```

for `model` and `θ`. When defining this method, the user picks the implementation (forward or reverse AD, or manual calculation). Choices and parameters specific to this could be shoved into `model` (eg `ForwardDiff.GradientConfig`). The interface calls `gradient!`, then queries `result` for `value` and `gradient`.

Problem: all methods would need to pass around `result` in addition to `model` all the way down. Possible solution: wrap `result` and `model` in a single object together, but this looks inelegant.

It is possible that I am not grasping the related APIs well. Any advice would be appreciated.

---

<div class="post-metadata">

**Author:** ![antoine-levitt](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/antoine-levitt/32/4008_2.png) [@antoine-levitt](https://discourse.julialang.org/u/antoine-levitt)\
**Post date:** [August 18, 2017, 8:04pm UTC](https://discourse.julialang.org/t/using-the-diffresult-api/5456/2 "2017-08-18T20:04:05Z")

</div>

Maybe the API for optimizers can help? E.g. OnceDifferentiable in [https://github.com/JuliaNLSolvers/NLSolversBase.jl](https://github.com/JuliaNLSolvers/NLSolversBase.jl)
