Angad Sandhu
Search
Browse
On this page

2.1_Numba_lab

Numba Lab

Now it's your turn!

Your challenge is to implement Fizz Buzz in CUDA Python with numba and calculate all instances of Fizz, Buzz and Fizz Buzz for the numbers between 1 and 50_000_000.

Before you begin, please turn off Google Colab's autocompletion by going to the settings gear in the top right -> Editor -> Uncheck "Automatically trigger code completions"

import numpy as np
from numba import cuda
import math

1. Create the input data array. Try using np.arange.

data = np.arange(1, 50_000_001)
data
data = cuda.to_device(data)

2. Create the output data array.

output = np.arange(1, 50_000_001)
output
output = cuda.to_device(output)

3. Calculate the number of threads and blocks.

threads = 128
blocks = math.ceil(len(data) / threads)

4. Create the kernel. Tip: Our output array must be numeric so try using the values 1, 2 and 3 to represent Fizz, Buzz and Fizz Buzz.

@cuda.jit
def fizz_buzz(input_array, output_array):
    i = cuda.grid(1)

    if input_array[i] % 3 == 0:
        if input_array[i] % 5 == 0:
            output_array[i] = 3
        else: output_array[i] = 1
    elif input_array[i] % 5 == 0: output_array[i] = 2
    else: output_array[i] = 0

5. Run our kernel.

%%time
fizz_buzz[blocks, threads](data, output)
output = output.copy_to_host()
output[:12]
CPU times: user 39.9 ms, sys: 247 ms, total: 287 ms
Wall time: 292 ms
array([0, 0, 1, 0, 2, 1, 0, 0, 1, 2, 0, 1])

Extra Credit 6. Calculate the highest instance of Fizz.

len(np.where(output == 1)[0])

# idx = 
# data[idx]
13333333

Browse the library