Automatic Differentiation with custom functions within likelihood function

You may find this discussion relevant, has a lot of nice suggestions: