liveBook · Manning

Numba

As explained in Fast Python: High performance techniques for large datasets

Numba is a Python compiler that uses just-in-time compilation to generate optimized machine code for numerical code, with support for CPU and GPU targets.

Numba is a just-in-time compiler that converts a subset of Python into fast native code. It is often easier to try than rewriting a routine in Cython and may deliver comparable gains with less work. It can target GPUs as well as CPUs, but its generated code is not a substitute for choosing an appropriate algorithm. section 5.1

GPU work requires a change in execution model. Rather than sending a sequential loop to the device, write a kernel whose invocation handles one array element, then launch enough threads to cover the array. The CPU launches the kernel; GPU threads perform the elementwise work. section 9.1.4 section 9.2.2

Double a 1,000-element array

A `@cuda.jit` kernel can calculate its position with `cuda.grid(1)` and double that element. Launching `double[50, 20](my_array)` supplies 50 blocks of 20 threads, one thread per element. An ordinary call without the bracketed launch configuration fails. If the chosen block size produces extra threads, guard against positions at or beyond the array length before indexing it. section 9.2.2

Before relying on a GPU kernel:

  • Check that GPU drivers, the CUDA toolkit, a supported device and required libraries are available. section 9.2.1
  • Check that the launch covers every element; use bounds checks when its thread count exceeds the data size. section 9.2.2
  • Choose work with enough parallelism to justify GPU execution. Merely annotating existing sequential Python code does not exploit the device. section 9.4
numba -s

Run `numba -s` to inspect the detected CUDA hardware and libraries before debugging kernel code. section 9.2.1

How Fast Python: High performance techniques for large datasets covers it

How deep it goes
Works through kernel indexing, launch configuration and bounds checks; defers shared-state algorithms and gives no GPU benchmark here.
Examples
Uses array doubling and two-dimensional matrix indexing as kernel exercises, with a Mandelbrot generator identified for later comparison.
What it assumes
Assumes familiarity with Python arrays while introducing GPU kernels and thread distribution from a simple elementwise task.
What you can do after
Apply it via Numba to launch a bounds-checked CUDA array kernel and check GPU availability.
How it connects
Connects Numba to Cython, NumPy, CUDA, GPU kernels and thread blocks.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Fast Python: High performance techniques for large datasets. The section links point to the parts of the book it draws on.