# Metal.jl weird behavior above 2^27

**URL:** https://discourse.julialang.org/t/metal-jl-weird-behavior-above-2-27/123261
**Category:** GPU
**Tags:** metaljl
**Created:** [November 29, 2024, 5:52pm UTC](https://discourse.julialang.org/t/metal-jl-weird-behavior-above-2-27/123261 "2024-11-29T17:52:12Z")
**Posts on this page:** 2
**Page:** 1

<div class="post-metadata">

### Author: ![jvsaddic](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/jvsaddic/32/213829_2.png) [@jvsaddic](https://discourse.julialang.org/u/jvsaddic)
#### Post date: [November 29, 2024, 5:52pm UTC](https://discourse.julialang.org/t/metal-jl-weird-behavior-above-2-27/123261/1 "2024-11-29T17:52:12Z")

</div>

Hi! I am new to GPU programming, and I have been experimenting with Metal.jl

As practice, I wrote this little program to estimate pi using the Monte Carlo method.

```julia
using Metal
using Random

throw_dart(a) = (2*a - 1)^2
dart_hit_circle(a) = a <= 1

function est_pi_gpu(N)
    darts = Metal.rand(N, 2)
    darts = mapreduce(throw_dart, +, darts; dims=2)
    hits = mapreduce(dart_hit_circle, +, darts)

    return 4 * hits / N
end

function est_pi_cpu(N)
    darts = Random.rand(N, 2)
    darts = mapreduce(throw_dart, +, darts; dims=2)
    hits = mapreduce(dart_hit_circle, +, darts)

    return 4 * hits / N
end

dart_throw_count = 2^27

println("GPU Attempt:")
@time println(est_pi_gpu(dart_throw_count))

println("\nCPU Attempt:")
@time println(est_pi_cpu(dart_throw_count))

```

If I set `dart_throw_count` to anything below 2^27, this works fine. In the first run I set `dart_throw_count = 2^27 - 1` and it returns a proper pi estimate. But as soon as I set `dart_throw_count = 2^27` or higher (The second run) it just returns `4` for the GPU

 ![Screenshot 2024-11-29 at 11.48.46 AM](https://global.discourse-cdn.com/julialang/original/3X/4/6/46b3c7dbdce17ef888dc576861e4b149da8e1229.png)

So only for the GPU the line `hits = mapreduce(dart_hit_circle, +, darts)` returns the length of the array when the length is \>=2^27

Does anyone have any ideas why this is happening?

---

<div class="post-metadata">

### Author: ![rveltz](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/rveltz/32/2707_2.png) [@rveltz](https://discourse.julialang.org/u/rveltz)
#### Post date: [November 29, 2024, 6:53pm UTC](https://discourse.julialang.org/t/metal-jl-weird-behavior-above-2-27/123261/2 "2024-11-29T18:53:51Z")

</div>

perhaps [Different result for personal argmax on CPU and GPU if array size is large enough · Issue #476 · JuliaGPU/Metal.jl · GitHub](https://github.com/JuliaGPU/Metal.jl/issues/476)
