# Unexpected behavior of CUDA kernel

**URL:** <https://discourse.julialang.org/t/unexpected-behavior-of-cuda-kernel/118625>\
**Category:** General Usage\
**Tags:** question, bug, cuda\
**Created:** [August 26, 2024, 2:25pm UTC](https://discourse.julialang.org/t/unexpected-behavior-of-cuda-kernel/118625 "2024-08-26T14:25:15Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![0samuraiE](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/0samuraie/32/209825_2.png) [@0samuraiE](https://discourse.julialang.org/u/0samuraiE)\
**Post date:** [August 26, 2024, 2:25pm UTC](https://discourse.julialang.org/t/unexpected-behavior-of-cuda-kernel/118625/1 "2024-08-26T14:25:15Z")

</div>

Hello all. I hit an unexpected error writing CUDA kernel.  
Somehow the variable `b` seems to be in conflict.  
When I removed `b=sum(A)`, this function worked.  
Is it a spec or a bug?

```julia
using CUDA

function main()
    function kernel(A, B)
        i = threadIdx().x
        b = B[i]
        A[i] = b
        return nothing
    end

    A = CUDA.zeros(1)
    B = CUDA.zeros(1)
    CUDA.@cuda kernel(A, B)

    b = sum(A)
end
main()

```

```julia
ERROR: GPU compilation of MethodInstance for (::var"#kernel#11")(::CuDeviceArray{Float32, 3, 1}, ::CuDeviceArray{Float32, 3, 1}) failed
KernelError: passing and using non-bitstype argument

Argument 1 to your kernel function is of type var"#kernel#11", which is not isbits:
  .b is of type Core.Box which is not isbits.
    .contents is of type Any which is not isbits.

```

---

<div class="post-metadata">

**Author:** ![mauro3](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/mauro3/32/292_2.png) [@mauro3](https://discourse.julialang.org/u/mauro3)\
**Post date:** [August 26, 2024, 2:38pm UTC](https://discourse.julialang.org/t/unexpected-behavior-of-cuda-kernel/118625/2 "2024-08-26T14:38:31Z")

</div>

Adding the `b = sum(A)` or anything `b = ...` makes the `b` inside the `kernel` a closed over variable. I think this is what CUDA does not like, if you change it to `c = sum(A)` it should work.

This illustrates this behavior a bit:

```julia
julia> function f()
         function g()
           return b
         end
         b = 1
         return g
       end
         
f (generic function with 1 method)

julia> gg = f(); gg()
1

```

---

<div class="post-metadata">

**Author:** ![0samuraiE](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/0samuraie/32/209825_2.png) [@0samuraiE](https://discourse.julialang.org/u/0samuraiE)\
**Post date:** [August 26, 2024, 2:48pm UTC](https://discourse.julialang.org/t/unexpected-behavior-of-cuda-kernel/118625/3 "2024-08-26T14:48:58Z")

</div>

Thanks. I did not know Julia can capture a variable after function definition.
