Previous topic

Next topic

This Page

Quick search

Numba is a compiler for Python bytecode with optional type-specialization.

Suppose you enter a function like this into the standard Python interpreter
(henceforward referred to as “CPython”):

defadd(a,b):returna+b

The interpreter will immediately parse the function and convert it into a
bytecode representation that describes how the CPython interpreter should
execute the function at a low level. For the example above, it looks
something like this:

CPython uses a stack-based interpreter (much like an HP calculator), so the
code first pushes two local variables onto the stack. The BINARY_ADD
opcode pops the top two arguments off the stack and makes a Python C API
function call that is equivalent to calling a.__add__(b). The result is
then pushed onto the top of the interpreter stack. Finally, the
RETURN_VALUE opcode returns value on the top of the stack as the result of
the function call.

Numba can take this bytecode and compile it to machine code that performs the
same operations as the CPython interpreter, treating a and b as
generic Python objects. The full semantics of Python are preserved, and the
compiled function can be used with any kind of objects that have the add
operator defined. When a Numba function is compiled this way, we say that it
has been compiled in object mode, because the code still manipulates
Python objects.

Numba code compiled in object mode is not much faster than executing the
original Python function in the CPython interpreter. However, if we
specialize the function to only run with certain data types, Numba can
generate much shorter and more efficient code that manipulates the data
natively without any calls into the Python C API. When code has been compiled
for specific data types so that the function body no longer relies on the
Python runtime, we say the function has been compiled in nopython mode.
Numeric code compiled in nopython mode can be hundreds of times faster
than the original Python.

Like many compilers, Numba can be conceptually divided into a
frontend and a backend.

The Numba frontend comprises the stages which analyze the Python bytecode,
translate it to Numba IR and perform various transformations and
analysis steps on the IR. One of the key steps is type inference.
The frontend must succeed in typing all variables unambiguously in order
for the backend to generate code in nopython mode, because the
backend uses type information to match appropriate code generators with
the values they operate on.

The Numba backend walks the Numba IR resulting from the frontend analyses
and exploits the type information deduced by the type inference phase to
produce the right LLVM code for each encountered operation. After LLVM
code is produced, the LLVM library is asked to optimize it and generate
native processor code for the final, native function.

There are other pieces besides the compiler frontend and backend, such
as the caching machinery for JIT functions. Those pieces are not considered
in this document.

Numba is quite flexible, allowing it to generate code for different hardware
architectures like CPUs and GPUs. In order to support these different
applications, Numba uses a typing context and a target context.

A typing context is used in the compiler frontend to perform type inference
on operations and values in the function. Similar typing contexts could be
used for many architectures because for nearly all cases, typing inference
is hardware-independent. However, Numba currently has a different typing
context for each target.

A target context is used to generate the specific instruction sequence
required to operate on the Numba types identified during type inference.
Target contexts are architecture-specific and are flexible in defining
the execution model and available Python APIs. For example, Numba has a “cpu”
and a “cuda” context for those two kinds of architecture, and a “parallel”
context which produces multithreaded CPU code.

At the start of compilation, the function bytecode is passed to an instance of
the Numba interpreter (numba.interpreter). The interpreter object
analyzes the bytecode to find the control flow graph (numba.controlflow).
The control flow graph describes the ways that execution can move from one
block to the next inside the function as a result of loops and branches.

The data flow analysis (numba.dataflow) takes the control flow graph and
traces how values get pushed and popped off the Python interpreter stack for
different code paths. This is important to understand the lifetimes of
variables on the stack, which are needed in Stage 2.

If you set the environment variable NUMBA_DUMP_CFG to 1, Numba will dump
the results of the control flow graph analysis to the screen. Our add()
example is pretty boring, since there is only one statement block:

Once the control flow and data analyses are complete, the Numba interpreter
can step through the bytecode and translate it into an Numba-internal
intermediate representation. This translation process changes the function
from a stack machine representation (used by the Python interpreter) to a
register machine representation (used by LLVM).

Although the IR is stored in memory as a tree of objects, it can be serialized
to a string for debugging. If you set the environment variable
NUMBA_DUMP_IR equal to 1, the Numba IR will be dumped to the screen. For
the add() function described above, the Numba IR looks like:

The del instructions are produced by Live Variable Analysis.
Those instructions ensure references are not leaked.
In nopython mode, some objects are tracked by the numba runtime and
some are not. For tracked objects, a dereference operation is emitted;
otherwise, the instruction is an no-op.
In object mode each variable contains an owned reference to a PyObject.

Now that the function has been translated into the Numba IR, macro expansion can
be performed. Macro expansion converts specific attributes that are known to
Numba into IR nodes representing function calls. This is initiated in the
numba.compiler.translate_stage function, and is implemented in
numba.macro.

Examples of attributes that are macro-expanded include the CUDA instrinsics for
grid, block and thread dimensions and indices. For example, the assignment to
tx in the following function:

Before running type inference, it may be desired to run certain
transformations on the Numba IR. One such example is to detect raise
statements which have an implicitly constant argument, so as to
support them in nopython mode. Let’s say you compile the
following function with Numba:

deff(x):ifx==0:raiseValueError("x cannot be zero")

If you set the NUMBA_DUMP_IR environment variable to 1,
you’ll see the IR being rewritten before the type inference phase:

Now that the Numba IR has been generated and macro-expanded, type analysis
can be performed. The types of the function arguments can be taken either
from the explicit function signature given in the @jit decorator
(such as @jit('float64(float64,float64)')), or they can be taken from
the types of the actual function arguments if compilation is happening
when the function is first called.

The type inference engine is found in numba.typeinfer. Its job is to
assign a type to every intermediate variable in the Numba IR. The result of
this pass can be seen by setting the NUMBA_DUMP_ANNOTATION
environment variable to 1:

If type inference fails to find a consistent type assignment for all the
intermediate variables, it will label every variable as type pyobject and
fall back to object mode. Type inference can fail when unsupported Python
types, language features, or functions are used in the function body.

This pass’s purpose is to perform any high-level optimizations that still
require, or could at least benefit from, Numba IR type information.

One example of a problem domain that isn’t as easily optimized once
lowered is the domain of multidimensional array operations. When
Numba lowers an array operation, Numba treats the operation like a
full ufunc kernel. During lowering a single array operation, Numba
generates an inline broadcasting loop that creates a new result array.
Then Numba generates an application loop that applies the operator
over the array inputs. Recognizing and rewriting these loops once
they are lowered into LLVM is hard, if not impossible.

An example pair of optimizations in the domain of array operators is
loop fusion and shortcut deforestation. When the optimizer
recognizes that the output of one array operator is being fed into
another array operator, and only to that array operator, it can fuse
the two loops into a single loop. The optimizer can further eliminate
the temporary array allocated for the initial operation by directly
feeding the result of the first operation into the second, skipping
the store and load to the intermediate array. This elimination is
known as shortcut deforestation. Numba currently uses the rewrite
pass to implement these array optimizations. For more information,
please consult the “Case study: Array Expressions” subsection,
later in this document.

One can see the result of rewriting by setting the
NUMBA_DUMP_IR environment variable to a non-zero value (such
as 1). The following example shows the output of the rewrite pass as
it recognizes an array expression consisting of a multiply and add,
and outputs a fused kernel as a special operator, arrayexpr():

If type inference succeeds in finding a Numba type for every intermediate
variable, then Numba can (potentially) generate specialized native code. This
process is called lowering. The Numba IR tree is translated into
LLVM IR by using helper classes from llvmlite.
The machine-generated LLVM IR can seem unnecessarily verbose, but the LLVM
toolchain is able to optimize it quite easily into compact, efficient code.

The basic lowering algorithm is generic, but the specifics of how particular
Numba IR nodes are translated to LLVM instructions is handled by the
target context selected for compilation. The default target context is
the “cpu” context, defined in numba.targets.cpu.

The LLVM IR can be displayed by setting the NUMBA_DUMP_LLVM environment
variable to 1. For the “cpu” context, our add() example would look like:

If type inference fails to find Numba types for all values inside a function,
the function will be compiled in object mode. The generated LLVM will be
significantly longer, as the compiled code will need to make calls to the
Python C API to perform basically all
operations. The optimized LLVM for our example add() function is:

The careful reader might notice several unnecessary calls to Py_IncRef
and Py_DecRef in the generated code. Currently Numba isn’t able to
optimize those away.

Object mode compilation will also attempt to identify loops which can be
extracted and statically-typed for “nopython” compilation. This process is
called loop-lifting, and results in the creation of a hidden nopython mode
function just containing the loop which is then called from the original
function. Loop-lifting helps improve the performance of functions that
need to access uncompilable code (such as I/O or plotting code) but still
contain a time-intensive section of compilable code.

In both object mode and nopython mode, the generated LLVM IR
is compiled by the LLVM JIT compiler and the machine code is loaded into
memory. A Python wrapper is also created (defined in
numba.dispatcher.Dispatcher) which can do the dynamic dispatch to the
correct version of the compiled function if multiple type specializations
were generated (for example, for both float32 and float64 versions
of the same function).

The machine assembly code generated by LLVM can be dumped to the screen by
setting the NUMBA_DUMP_ASSEMBLY environment variable to 1: