Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix type inference of eltype(vi, spl) (Turing#2151) #568

Merged
merged 7 commits into from
Jan 24, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 8 additions & 1 deletion src/abstract_varinfo.jl
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,14 @@ Determine the default `eltype` of the values returned by `vi[spl]`.
This method is considered legacy, and is likely to be deprecated in the future.
"""
function Base.eltype(vi::AbstractVarInfo, spl::Union{AbstractSampler,SampleFromPrior})
return eltype(Core.Compiler.return_type(getindex, Tuple{typeof(vi),typeof(spl)}))
T = Base.promote_op(getindex, typeof(vi), typeof(spl))
if T === Union{}
# In this case `getindex(vi, spl)` errors
# Let us throw a more descriptive error message
# Ref https://github.com/TuringLang/Turing.jl/issues/2151
return eltype(vi[spl])
end
return eltype(T)
end

# TODO: Should relax constraints on `vns` to be `AbstractVector{<:Any}` and just try to convert
Expand Down
2 changes: 1 addition & 1 deletion src/varinfo.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1444,7 +1444,7 @@ function getindex(vi::TypedVarInfo, spl::Sampler)
# Gets the ranges as a NamedTuple
ranges = _getranges(vi, spl)
# Calling getfield(ranges, f) gives all the indices in `vals` of the `vn`s with symbol `f` sampled by `spl` in `vi`
return vcat(_getindex(vi.metadata, ranges)...)
return reduce(vcat, _getindex(vi.metadata, ranges))
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This fixes the ReverseDiff issue but probably reduces performance in cases where vcat with multiple arguments is implemented in an optimized way.

end
# Recursively builds a tuple of the `vals` of all the symbols
@generated function _getindex(metadata, ranges::NamedTuple{names}) where {names}
Expand Down
Loading