Getindex without a warning?

I need to extract a single value from a CuArray for some calculation. Is there a way to do it without getting the “scalar operations” warning?

copyto! is your friend here.

for Example

 function my_getindex(a::CuArray{T}, index) where T
     out = Array{T}(undef, 1)
     copyto!(out, 1, a, index, 1)
     out[1]
 end

Usage:

julia> arr = CuArray(1.:32);

julia> my_getindex(a, 1)
1.0

julia> my_getindex(a, 2)
2.0

julia> my_getindex(a, 33)
ERROR: BoundsError: attempt to access 32-element CuArray{Float64,1,Nothing} at index [33]
Stacktrace:
 [1] throw_boundserror(::CuArray{Float64,1,Nothing}, ::Tuple{Int64}) at ./abstractarray.jl:537
 [2] checkbounds at ./abstractarray.jl:502 [inlined]
 [3] copyto! at /home/aditya/.julia/dev/CUDA/src/array.jl:294 [inlined]
 [4] my_getindex(::CuArray{Float64,1,Nothing}, ::Int64) at ./REPL[75]:3
 [5] top-level scope at REPL[79]:1

Alternatively, you can @allowscalar foo[i].

3 Likes

Thanks, this is exactly what I need.