# Type instability possibly due to variable playing role of input and output

**URL:** <https://discourse.julialang.org/t/type-instability-possibly-due-to-variable-playing-role-of-input-and-output/110178>\
**Category:** General Usage\
**Tags:** question, tuple, code\_warntype, type-stability\
**Created:** [February 13, 2024, 10:58pm UTC](https://discourse.julialang.org/t/type-instability-possibly-due-to-variable-playing-role-of-input-and-output/110178 "2024-02-13T22:58:30Z")\
**Posts on this page:** 1\
**Showing post:** 10

<div class="post-metadata">

**Author:** ![mikmoore](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mikmoore/32/31109_2.png) [@mikmoore](https://discourse.julialang.org/u/mikmoore)\
**Post date:** [February 14, 2024, 9:31pm UTC](https://discourse.julialang.org/t/type-instability-possibly-due-to-variable-playing-role-of-input-and-output/110178/10 "2024-02-14T21:31:20Z")

</div>

For the MWE above, I would strongly consider `V = exp ∘ sin ∘ cos` (or `V = ∘(exp, sin, cos)`) if it’s just a line you’re writing and changing manually. But `∘` won’t work well for long or dynamic compositions.

For long or dynamic compositions, I’ll recommend either accepting instability (the cost of dynamic dispatch once per layer is modest compared to the calculation within a layer of decent size) or using FunctionWrappers.jl.

For example, if you define your activation functions like `f = FunctionWrapper{Float64, Tuple{Float64}}(tanh)` they will all have the common type `FunctionWrapper{Float64, Tuple{Float64}}` (notice: unrelated to `tanh`) and so your entire array will be made of identically-typed `layer{FunctionWrapper{Float64, Tuple{Float64}}` so entirely stable.

Initially, I would experiment with just accepting the instability and benchmarking to see if the cost is actually significant. You can probably mitigate a lot of the cost with [function barriers](https://docs.julialang.org/en/v1/manual/performance-tips/#kernel-functions) or the occasional type annotation, if it’s relevant. FunctionWrappers looks like it would solve your problem, but is a little involved so is not my initial recommendation.

---

_[View the full topic](https://discourse.julialang.org/t/type-instability-possibly-due-to-variable-playing-role-of-input-and-output/110178)._
