LoopVectorization.jl icon indicating copy to clipboard operation
LoopVectorization.jl copied to clipboard

Nested loop UndefVarError

Open bvdmitri opened this issue 4 years ago • 3 comments

Hey, thanks for the great library!

I'm not sure if this is a bug, but the following code doesn't work for me for no obvious reason:

function logmean(samples, weights)
    logμ = zero(first(samples))
    n = length(samples)
    k = length(logμ)
    @turbo for i in 1:n
        for j in 1:k
            logμ[j] = logμ[j] + weights[i] * log(samples[i][j])
        end
    end
    return logμ
end
logmean([ [ 1.0, 1.0 ], [ 1.0, 1.0 ] ], [ 0.5, 0.5 ])
UndefVarError: i not defined

Stacktrace:
 [1] logmean(samples::Vector{Vector{Float64}}, weights::Vector{Float64})
   @ Main ./In[15]:5
 [2] top-level scope
   @ In[16]:1
 [3] eval
   @ ./boot.jl:360 [inlined]
 [4] include_string(mapexpr::typeof(REPL.softscope), mod::Module, code::String, filename::String)
   @ Base ./loading.jl:1116

The following version works like a charm:

function logmean(samples, weights)
    logμ = zero(first(samples))
    n = length(samples)
    k = length(logμ)
    for i in 1:n
        @turbo for j in 1:k
            logμ[j] = logμ[j] + weights[i] * log(samples[i][j])
        end
    end
    return logμ
end

I thought LoopVectorization.jl should be able to handle nested loops? Or are there some special requirements for that?

bvdmitri avatar Aug 23 '21 11:08 bvdmitri

It doesn't handle samples::Vector{Vector{Float64}} at the moment. It probably shouldn't be too hard to add support.

The second example works because it pulls samples[i] out of the loop, and samples[i] is a Vector{Float64}.

chriselrod avatar Aug 23 '21 11:08 chriselrod

I see, thanks for the clarifications! Its up to you then to either close this issue or to keep it for the future reference.

bvdmitri avatar Aug 23 '21 11:08 bvdmitri

I will keep it open for future reference.

chriselrod avatar Aug 23 '21 11:08 chriselrod