# A gradient block?

**URL:** <https://discourse.mc-stan.org/t/a-gradient-block/3782>\
**Category:** General\
**Created:** [April 5, 2018, 2:27am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782 "2018-04-05T02:27:14Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![James\_Savage](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/james_savage/32/26_2.png) [@James\_Savage](https://discourse.mc-stan.org/u/James_Savage)\
**Post date:** [April 5, 2018, 2:27am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/1 "2018-04-05T02:27:14Z")

</div>

Some of the models I fit quite regularly have fairly straightforward analytical gradients but are very expensive to evaluate via autodiff. I know it’s in theory possible to hack together my own version of Stan with these analytical gradients defined on the back end, but I’d probably mess that up. Something like this would be extremely handy:

```
data {
  ...
}
parameters {
  real par1;
  real par2;
}
gradients {
  par1 = some expression;
  // gradient wrt par2 to be left to autodiff
}
model {
  ...
}

```

This isn’t much of a question, but would something like this be possible in theory?

---

<div class="post-metadata">

**Author:** ![aaronjg](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/aaronjg/32/3768_2.png) [@aaronjg](https://discourse.mc-stan.org/u/aaronjg)\
**Post date:** [April 5, 2018, 2:50am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/2 "2018-04-05T02:50:40Z")

</div>

Can you wrap it into its own function and then code the gradients by hand? You don’t need to recompile Stan to do this:  
[https://cran.r-project.org/web/packages/rstan/vignettes/external.html](https://cran.r-project.org/web/packages/rstan/vignettes/external.html)

I’ve done this for some parts of a model that have easy analytical gradients and are evaluated in the inner loop of the likelihood function.

---

<div class="post-metadata">

**Author:** ![andre.pfeuffer](https://avatars.discourse-cdn.com/v4/letter/a/e480ec/32.png) [@andre.pfeuffer](https://discourse.mc-stan.org/u/andre.pfeuffer)\
**Post date:** [April 5, 2018, 3:13am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/3 "2018-04-05T03:13:00Z")

</div>

Can you provide an example?  
I would be nice to have an example prototype about how to extend Stan in C++.

---

<div class="post-metadata">

**Author:** ![aaronjg](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/aaronjg/32/3768_2.png) [@aaronjg](https://discourse.mc-stan.org/u/aaronjg)\
**Post date:** [April 5, 2018, 3:27am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/4 "2018-04-05T03:27:14Z")

</div>

Sure.

I needed to calculate \frac x {1 - x} or \exp(\mbox{logit}(x)) in a hot path, but could not find it in the Stan math library. It has derivative \frac 1 {(1-x)^2}

So I added this code to a separate .hpp

and included it as described in the tutorial.

```
inline double exp_logit(double u) {
  return u / (1 - u);
}

inline var exp_logit(const var& u) {
  const double uv = u.val();
  const double m_u = (1-uv);
  const double m_u_sq = m_u * m_u;
  
  
  return var(new precomp_v_vari(exp_logit(u.val()),
                                u.vi_,
                                1 / m_u_sq));
}
struct exp_logit_fun {
  template <typename T>
  static inline T fun(const T& x) {
    return exp_logit(x);
  }
};

template <typename T>
inline typename apply_scalar_unary<exp_logit_fun, T>::return_t
exp_logit(const T& x) {
  return apply_scalar_unary<exp_logit_fun, T>::apply(x);
}

template <typename T0__>
Eigen::Matrix<typename boost::math::tools::promote_args<T0__>::type, 
Eigen::Dynamic,1>
exp_logit(const Eigen::Matrix<T0__, Eigen::Dynamic,1>& x, std::ostream* 
pstream__) {
 return exp_logit(x);
}

struct exp_logit_functor__ {
template <typename T0__>
    Eigen::Matrix<typename boost::math::tools::promote_args<T0__>::type, 
Eigen::Dynamic,1>
  operator()(const Eigen::Matrix<T0__, Eigen::Dynamic,1>& x, std::ostream* 
pstream__) const {
return exp_logit(x, pstream__);
}
};

```

This is pretty much all the Stan C++ code I’ve ever written, so by no means take this to be best practices!

---

<div class="post-metadata">

**Author:** ![avehtari](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/avehtari/32/5935_2.png) [@avehtari](https://discourse.mc-stan.org/u/avehtari)\
**Post date:** [April 5, 2018, 3:42pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/5 "2018-04-05T15:42:57Z")

</div>

User defined gradients are in Stan Road Map [https://github.com/stan-dev/stan/wiki/Stan-Road-Map](https://github.com/stan-dev/stan/wiki/Stan-Road-Map),  
but while waiting for them, what @aaronjg did doesn’t seem that complicated (given that the process of including additional .hpp is not too complicated for you)

---

<div class="post-metadata">

**Author:** ![sakrejda](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/sakrejda/32/845_2.png) [@sakrejda](https://discourse.mc-stan.org/u/sakrejda)\
**Post date:** [April 5, 2018, 3:57pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/6 "2018-04-05T15:57:02Z")

</div>

I’d trust 0% of users to keep the gradients block properly updated as they evolve their model but I can see the attraction.

---

<div class="post-metadata">

**Author:** ![andre.pfeuffer](https://avatars.discourse-cdn.com/v4/letter/a/e480ec/32.png) [@andre.pfeuffer](https://discourse.mc-stan.org/u/andre.pfeuffer)\
**Post date:** [April 5, 2018, 4:24pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/7 "2018-04-05T16:24:42Z")

</div>

> [@sakrejda](#):
>
> I’d trust 0% of users to keep the gradients block properly updated as they evolve their model but I can see the attraction.

User’s autodiff could be cross-checked by Stan’s version at initial phase.

---

<div class="post-metadata">

**Author:** ![avehtari](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/avehtari/32/5935_2.png) [@avehtari](https://discourse.mc-stan.org/u/avehtari)\
**Post date:** [April 5, 2018, 5:33pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/8 "2018-04-05T17:33:50Z")

</div>

> [@andre.pfeuffer](#):
>
> User’s autodiff could be cross-checked by Stan’s version at initial phase.

And for random draws after sampling stops. This is also in the plan.

---

<div class="post-metadata">

**Author:** ![Bob\_Carpenter](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/bob_carpenter/32/9230_2.png) [@Bob\_Carpenter](https://discourse.mc-stan.org/u/Bob_Carpenter)\
**Post date:** [April 13, 2018, 8:02pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/9 "2018-04-13T20:02:29Z")

</div>

> [@sakrejda](#):
>
> I’d trust 0% of users to keep the gradients block properly updated

We have to trust our users. There’s so many ways to screw up a Stan program that we can’t really provide much protection.

I’d trust a fair bit more than 0% because some users are careful with software and test as they go.

And as others have noted, we wouldn’t do this without finite diff or autodiff tests.

What we’re likely to add is a way to define a function with gradients, not just define gradients w.r.t. the log density for parameters.

Then users will only define gradients w.r.t. constrained parameters, so we’ll need to chain the transforms and Jacobians for any constrained parameters.

---

<div class="post-metadata">

**Author:** ![James\_Savage](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/james_savage/32/26_2.png) [@James\_Savage](https://discourse.mc-stan.org/u/James_Savage)\
**Post date:** [April 14, 2018, 9:52pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/10 "2018-04-14T21:52:27Z")

</div>

@Bob_Carpenter That sounds even better than a gradients block. Exciting!

---

<div class="post-metadata">

**Author:** ![bnicenboim](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/bnicenboim/32/21197_2.png) [@bnicenboim](https://discourse.mc-stan.org/u/bnicenboim)\
**Post date:** [February 17, 2021, 7:30pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/11 "2021-02-17T19:30:21Z")

</div>

> [@Bob\_Carpenter](#):
>
> What we’re likely to add is a way to define a function with gradients, not just define gradients w.r.t. the log density for parameters.
> 
> Then users will only define gradients w.r.t. constrained parameters, so we’ll need to chain the transforms and Jacobians for any constrained parameters.

Hi Bob,  
I just found this from almost three years ago. Will this still happen? (soon? eventually?)

---

<div class="post-metadata">

**Author:** ![bbbales2](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/bbbales2/32/77_2.png) [@bbbales2](https://discourse.mc-stan.org/u/bbbales2)\
**Post date:** [February 17, 2021, 7:47pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/12 "2021-02-17T19:47:29Z")

</div>

It’s something we talk about and this idea is reasonably popular but there’s no work on it as of yet :D.

---

<div class="post-metadata">

**Author:** ![bnicenboim](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/bnicenboim/32/21197_2.png) [@bnicenboim](https://discourse.mc-stan.org/u/bnicenboim)\
**Post date:** [February 17, 2021, 8:05pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/13 "2021-02-17T20:05:27Z")

</div>

I really look forward to be able to define something like a \_grad function for my custom \_lpdf/lpmf function. And not have to deal with c++.  
Is there an open issue about this that I can track?  
I can’t code something like this, but I volunteer to help with the testing and documentation :)

---

<div class="post-metadata">

**Author:** ![bbbales2](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/bbbales2/32/77_2.png) [@bbbales2](https://discourse.mc-stan.org/u/bbbales2)\
**Post date:** [February 19, 2021, 2:02pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/14 "2021-02-19T14:02:57Z")

</div>

> [@bnicenboim](#):
>
> Is there an open issue about this that I can track?

I don’t think there is, but if you ever get curious about the status just ask again. Hopefully it’ll be a yes in the future sometime :P

---

<div class="post-metadata">

**Author:** ![Johannes\_Hendriks](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/johannes_hendriks/32/12365_2.png) [@Johannes\_Hendriks](https://discourse.mc-stan.org/u/Johannes_Hendriks)\
**Post date:** [August 4, 2021, 2:23am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/15 "2021-08-04T02:23:47Z")

</div>

Hey, is there a way to include external c++ code using the new pystan 3 interface?

---

<div class="post-metadata">

**Author:** ![ahartikainen](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/ahartikainen/32/321_2.png) [@ahartikainen](https://discourse.mc-stan.org/u/ahartikainen)\
**Post date:** [August 4, 2021, 5:37am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/16 "2021-08-04T05:37:06Z")

</div>

Currently, no.

---

<div class="post-metadata">

**Author:** ![Johannes\_Hendriks](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/johannes_hendriks/32/12365_2.png) [@Johannes\_Hendriks](https://discourse.mc-stan.org/u/Johannes_Hendriks)\
**Post date:** [August 4, 2021, 10:45pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/17 "2021-08-04T22:45:30Z")

</div>

Is there a plan to add support for this?

---

<div class="post-metadata">

**Author:** ![ahartikainen](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/ahartikainen/32/321_2.png) [@ahartikainen](https://discourse.mc-stan.org/u/ahartikainen)\
**Post date:** [August 5, 2021, 4:50am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/18 "2021-08-05T04:50:21Z")

</div>

I don’t think Stan has any ‘official’ way to do this, so answer is probably no.

Cc @ariddell @bbbales2

---

<div class="post-metadata">

**Author:** ![bbbales2](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/bbbales2/32/77_2.png) [@bbbales2](https://discourse.mc-stan.org/u/bbbales2)\
**Post date:** [August 6, 2021, 10:49pm UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/19 "2021-08-06T22:49:42Z")

</div>

Yeah I don’t know any way to do this other than the rstan stuff above or modifying sources and rebuilding manually.

---

<div class="post-metadata">

**Author:** ![Johannes\_Hendriks](https://yyz2.discourse-cdn.com/flex030/user_avatar/discourse.mc-stan.org/johannes_hendriks/32/12365_2.png) [@Johannes\_Hendriks](https://discourse.mc-stan.org/u/Johannes_Hendriks)\
**Post date:** [August 11, 2021, 1:14am UTC](https://discourse.mc-stan.org/t/a-gradient-block/3782/20 "2021-08-11T01:14:23Z")

</div>

The research project I am working on will require custom gradients. Is there a guide or some instructions on how to modify source and recompile for use with PyStan 3? Thanks in advance for any answers
