User Defined Functions

This tutorial covers generic Python and Numba functions that process chunks of NDArray and/or NumPy arrays through the lazy user-defined function interface, LazyUDF. For elementwise calculations with branches or loops, Menudet kernels offer a simpler interface: write the calculation for one element without managing an output buffer.

[1]:
import time

import numba as nb
import numpy as np

import blosc2

A simple example

First, let’s create a NDArray array, a NumPy array and regular scalar, which will be the operands of our function.

[2]:
shape = (5_000, 2_000)
a = np.linspace(0, 1, np.prod(shape), dtype=np.int32).reshape(shape)
b = blosc2.arange(np.prod(shape), dtype=np.float32, shape=shape)
s = 2.1  # a regular scalar

Now, let’s define our function, which will be the executable attribute of a LazyUDF object. Internally, LazyUDF will execute the function chunkwise on the operands when requested, and will expect the function to have a signature with three parameters: 1) an inputs tuple; 2) an output buffer to be filled; and 3) the chunk offset coordinates. When the function is called by LazyUDF, the inputs tuple will contain chunks of the operands, and must fill the output buffer with the computation result (which is automatically of the correct shape and dtype due to the internal mechanics of LazyUDF). The offset is the coordinates of the chunk being filled in the output, which is often useful (but not always necessary). For example, if we were to write a function to fill an empty array with ones on the main diagonal chunk-by-chunk, some chunks may have all zeros, which one will be able to ascertain using the coordinates in the offset parameter (see the implementation of `blosc2.eye <https://www.blosc.org/python-blosc2/reference/ndarray.html#blosc2.eye>`__).

For the moment, we’ll just write a function that does something simple with the operands and writes the result to the buffer.

[3]:
def myudf(inputs_tuple, output, offset):
    x, y, s = inputs_tuple  # at this point, all are either numpy arrays or scalars
    output[:] = x**3 + np.sin(y) + s + 1

It is important to write the result to the memory location indicated by the buffer using output[:] = result, since writing output = result would merely overwrite the value of output, which is just a memory address, and leave the memory at the address untouched.

Now, to actually create a LazyUDF object (which also follows the LazyArray interface) we will use its constructor lazyudf. As arguments, we provide: the UDF we have defined; a tuple with the operands; and the dtype of the output. The latter is important since it will be used to create the output buffer. Optionally we can provide the shape of the output, but if not the shape will be inferred from the operands.

[4]:
larray = blosc2.lazyudf(myudf, (a, b, s), a.dtype)
print(f"Type: {type(larray)}")
Type: <class 'blosc2.lazyexpr.LazyUDF'>

Since the LazyUDF object implements the same LazyArray interface as LazyExpr, we may execute and get the result of the function via either of the __getitem__ (returning a NumPy array) and compute (returning a NDArray array) methods. Let’s see __getitem__ first, computing either a slice or the whole result:

[5]:
npc = larray[:10]  # compute a slice of the result
print(f"Slice - Type: {type(npc)}, shape: {npc.shape}")
npc = larray[:]  # compute the whole result
print(f"Full array - Type: {type(npc)}, shape: {npc.shape}")
Slice - Type: <class 'numpy.ndarray'>, shape: (10, 2000)
Full array - Type: <class 'numpy.ndarray'>, shape: (5000, 2000)

Now, let’s use compute for the same purpose. The advantage of using this method is that you can pass some construction parameters for the resulting NDArray like the urlpath to store the resulting array on-disk, as we saw in the previous tutorial.

[6]:
c = larray.compute(urlpath="larray.b2nd", mode="w")
print(f"Type: {type(c)}")
print(c.info)
blosc2.remove_urlpath("larray.b2nd")  # clean-up
Type: <class 'blosc2.ndarray.NDArray'>
type    : NDArray
shape   : (5000, 2000)
chunks  : (1250, 2000)
blocks  : (10, 2000)
dtype   : int32
nbytes  : 40000000 (38.15 MiB)
cbytes  : 102314 (99.92 KiB)
cratio  : 390.95x
cparams : CParams(codec=<Codec.ZSTD: 5>, codec_meta=0, clevel=5, use_dict=False, typesize=4,
        : nthreads=12, blocksize=80000, splitmode=<SplitMode.AUTO_SPLIT: 3>,
        : filters=[<Filter.NOFILTER: 0>, <Filter.NOFILTER: 0>, <Filter.NOFILTER: 0>,
        : <Filter.NOFILTER: 0>, <Filter.NOFILTER: 0>, <Filter.SHUFFLE: 1>], filters_meta=[0, 0,
        : 0, 0, 0, 0], tuner=<Tuner.STUNE: 0>)
dparams : DParams(nthreads=12)

Saving to disk

Generic Python UDF recipes cannot be saved. To keep their results, materialize the values into an on-disk array with compute(urlpath=...), then reopen that array normally. To save a lazy calculation instead of its values, use Menudet with persistent array operands.

[7]:
c = larray.compute(urlpath="udf-values.b2nd", mode="w")
c2 = blosc2.open("udf-values.b2nd")
print(c2.info)
np.testing.assert_array_equal(c2[:], npc)
print(f"Result shape: {c2.shape}")
type    : NDArray
shape   : (5000, 2000)
chunks  : (1250, 2000)
blocks  : (10, 2000)
dtype   : int32
nbytes  : 40000000 (38.15 MiB)
cbytes  : 102314 (99.92 KiB)
cratio  : 390.95x
cparams : CParams(codec=<Codec.ZSTD: 5>, codec_meta=0, clevel=5, use_dict=False, typesize=4,
        : nthreads=12, blocksize=80000, splitmode=<SplitMode.AUTO_SPLIT: 3>,
        : filters=[<Filter.NOFILTER: 0>, <Filter.NOFILTER: 0>, <Filter.NOFILTER: 0>,
        : <Filter.NOFILTER: 0>, <Filter.NOFILTER: 0>, <Filter.SHUFFLE: 1>], filters_meta=[0, 0,
        : 0, 0, 0, 0], tuner=<Tuner.STUNE: 0>)
dparams : DParams(nthreads=12)

Result shape: (5000, 2000)

BONUS: Using Numba

Numba is a Just-In-Time (JIT) compiler that translates a subset of Python and NumPy code into fast machine code. It is particularly useful for numerical computations and can significantly speed up the execution of functions that are computationally intensive. Python-Blosc2 can also interface with Numba, via UDFs. It’s as simple as decorating the same function as before with a Numba jit decorator.

[8]:
@nb.jit(nopython=True, parallel=True)
def myudf_numba(inputs_tuple, output, offset):
    x, y, s = inputs_tuple
    output[:] = x**3 + np.sin(y) + s + 1


larray_nb = blosc2.lazyudf(myudf_numba, (a, b, s), a.dtype)

We then use the lazyudf constructor as before. Compare the first evaluation here, which includes Numba compilation, and the best of three warmed evaluations. The Python version uses vectorized NumPy operations rather than a Python loop over individual elements, and it has already been evaluated above.

[9]:
t1 = time.perf_counter()
npc_nb = larray_nb[:]  # numba version
t_nb = time.perf_counter() - t1

t1 = time.perf_counter()
npc = larray[:]  # pure python version
t_ = time.perf_counter() - t1
np.testing.assert_array_equal(npc_nb, npc)


def best_time(lazy, repeats=3):
    best = float("inf")
    for _ in range(repeats):
        start = time.perf_counter()
        lazy[:]
        best = min(best, time.perf_counter() - start)
    return best


best_nb = best_time(larray_nb)
best_python = best_time(larray)
print(f"First evaluation here - Numba: {t_nb:.3f} s, Python/NumPy: {t_:.3f} s")
print(f"Best of 3 warmed evaluations - Numba: {best_nb:.3f} s, Python/NumPy: {best_python:.3f} s")
print(f"First evaluation Numba / Python/NumPy: {t_nb / t_:.2f}x")
print(f"Warmed Numba / Python/NumPy: {best_nb / best_python:.2f}x")
First evaluation here - Numba: 1.211 s, Python/NumPy: 0.054 s
Best of 3 warmed evaluations - Numba: 0.017 s, Python/NumPy: 0.046 s
First evaluation Numba / Python/NumPy: 22.60x
Warmed Numba / Python/NumPy: 0.37x

Interpreting these results

The saved results were measured on a Mac mini with an Apple M4 Pro and 24 GB RAM, running macOS. Relative performance is specific to this machine, workload and run. Both UDFs produce identical results.

  • First evaluation here: Numba takes about 23x as long as the already-warmed Python/NumPy UDF, because this call also compiles the Numba function. This is not a comparison of two cold starts.

  • Steady-state: Once compiled, the Numba UDF is about 2.7x faster than the Python/NumPy UDF, comparing the best of three warmed evaluations.

For a one-off calculation, compilation can dominate; repeated evaluations can amortize that cost. Try changing the array size or calculation to see how the tradeoff changes.

Now that we’re finished, let’s delete the file we wrote to disk to clean up our directory.

[10]:
blosc2.remove_urlpath("udf-values.b2nd")

Summary

We have seen how to build new LazyUDFobjects based on bespoke User Defined Functions (UDFs) to perform computations of arbitrary complexity lazily. We have also demonstrated that integrating Numba in UDF is pretty easy.