numbox.core.proxy
Overview
When one numba function calls another, numba links a copy of the callee’s compiled code into the caller. For a few small functions, the cost of these copies is negligible. For a function that many jitted callers share, each caller’s compiled code embeds its own copy of the callee, and each cached caller stores that copy on disk.
proxy() separates the caller from the callee. The decorated function, called the proxied
function below, is compiled when its module is imported, for the signature passed to the decorator. A caller’s compiled
code holds a declaration of the compiled function and a call to it, not a copy. The compiled function therefore exists
in one place. The module-level constant form described in Holding the function as a module-level constant is the
exception: it embeds a copy.
The drawback is that LLVM cannot inline the call. The decorator is therefore suited to functions whose work takes longer than the call itself. numbox uses it mainly for its bindings: a binding is a proxied function that wraps one C function, such as the bindings to libc and to SQLite in numbox.core.bindings. Any function that many cached callers share is a candidate.
Using the decorator
Decorate the function with its signature. The signature is required, because the body is compiled at import time,
before any call could supply argument types. Where the function may start explains the length of the module docstring
below. The following example is saved as mymodule.py:
"""A module with a proxied function and a cached caller.
The @proxy line must be on line 8 of the file or later; this docstring makes the room.
"""
from numba import float64, njit
from numbox.core.proxy.proxy import proxy
@proxy(float64(float64), jit_options={"cache": True})
def scale(x):
return 2.0 * x
@njit(cache=True)
def total(xs):
acc = 0.0
for x in xs:
acc += scale(x)
return acc
After the decoration, the name scale refers to a numba dispatcher for a small wrapper that numbox generates around
the compiled body. The wrapper is named __scale, so expect that name, not scale, in numba’s messages. Python
code calls scale as before. Jitted code such as total calls the body by a name that numbox registers in every
process, the alias that Caching describes. When total is cached, its cache entry holds that name instead of a
copy of the body’s code. A call succeeds when numba can convert the argument to the signature’s type, such as an int
for a float64. A call from Python with any other type raises numba’s TypeError: No matching definition for
argument type(s); from jitted code, such a call fails to compile, and numba reports a failed cast to the signature’s
type.
The body is cached only on request. The second argument, jit_options, is passed to njit for the body and for
the generated wrapper. Pass {"cache": True} as above, or pass numbox.core.configurations.jit_options, the
setting numbox’s own bindings use. That setting enables caching unless the NUMBOX_JIT_OPTIONS environment variable
disables it. It also disables caching when numba can write no cache for numbox’s own files, and your function is then
not cached either (numbox.core.configurations). Under NUMBA_OPT=0, a debugging setting, numba does not cache
a caller of a proxied function and warns that the caller uses dynamic globals; the caller then compiles on every run.
Where the function may start
The function’s first decorator line must be on line 8 of its file or later. That line is the @proxy line, or the
topmost decorator when others are stacked above it, because Python records the line of a decorated function as the line
of its first decorator. numbox compiles the generated wrapper as though it were defined at that line of your file, so
that numba caches the wrapper with your module and detects your edits. The wrapper’s own source has seven lines of
helper code above its decorator. That decorator therefore cannot be above line 8. A function nearer the top is refused
at import with a ValueError that says where to move it. In the example, the module docstring moves the @proxy
line to line 8 or later.
Other decorators may be stacked above @proxy. A decorator between @proxy and def runs first, so numba
compiles whatever that decorator returns in place of your function. Put a decorator there only if it returns the
function unchanged.
A proxied function cannot take *args or **kwargs. Such a function fails at import.
Default arguments
For a function with default arguments, pass @proxy a list of signatures. The first is the main signature. Each
further signature describes a call that omits trailing defaulted parameters. In such a signature, each omitted parameter
appears as numba’s Omitted type, constructed with the default value:
"""A proxied function with a default argument.
The @proxy line must be on line 8 of the file or later; this docstring makes the room.
"""
from numba import float64, njit
from numba.types import Omitted
from numbox.core.proxy.proxy import proxy
@proxy([float64(float64, float64), float64(float64, Omitted(1.3))])
def shift(x, y=1.3):
return x + y
@njit
def use(x):
return shift(x) + shift(x, 2.0) # 2.3 + 3.0 for x = 1.0
Exceptions
If the body raises an exception, a call to scale, from Python or from jitted code, does not propagate it. The call
reaches the body through its C entry point, of the kind that @cfunc builds. That entry point cannot propagate a
Python exception to its caller. Python prints the exception to stderr below a line that begins
Exception ignored in:. The call returns a zero of the signature’s return type. If the body can raise, pass the
function as a value, as the next section shows, or report failure through the return value.
Passing the function as a value
Jitted code that takes a function as an argument needs a function value, not a dispatcher. The dispatcher’s attribute
.as_func is such a value for the main signature: a first-class function value. When you pass .as_func, an exception
raised in the body propagates. The receiving function also remains cacheable. The following example is saved in a second
file, callers.py:
from numba import njit
from mymodule import scale
@njit(cache=True)
def apply(f, x):
return f(x)
apply(scale.as_func, 3.0)
Read .as_func in Python and pass the value to the jitted function as an argument. Jitted code cannot read an
attribute of a dispatcher, and scale.as_func inside a jitted function fails to compile. The value has only the main
signature, so a call through it must pass every parameter: shift.as_func takes two arguments, and the default for
y applies only to calls of shift itself.
An exception raised inside the body propagates out of a call made through .as_func. To keep that propagation, let
numba infer the type of the parameter that receives the value, as apply does. The value then keeps its own type,
which numba prints as DeriveFunctionType[float64(float64)], and the exception propagates.
If the parameter is declared as a plain numba function type instead, numba converts the value to a plain function
value when Python code passes it to the jitted function. The jitted function calls the body through its C entry point.
An exception is then discarded, as it is for a call to the dispatcher. Such a declaration is
@njit(float64(FunctionType(float64(float64)), float64)), with FunctionType from numba.types.
Do not pass the dispatcher itself, as in apply(scale, 3.0). numba derives the type of that parameter from the
dispatcher object. The type’s name includes the memory address of the function that the dispatcher wraps, an address
that differs in every process. A cached apply then recompiles on every run and adds a cache entry each time.
.as_func has the same type in every process, so apply compiles once and loads from the cache after that.
Below numba 0.68.0, a tuple that mixes .as_func with a function value of another type, such as a @cfunc, an
@njit function compiled for a signature, numba’s own CompileResultWAP or an .as_func of another signature,
can fail with an AssertionError that has no message. numba 0.68.0 accepts such a tuple. A lazily compiled @njit
function that takes as many arguments as an .as_func cannot share a tuple with it on any numba version: the call
raises a TypeError. The work page lists this limit alongside related ones.
For reference, the value’s class is DeriveWAP and its numba type is
DeriveFunctionType.
Optional C symbols
A binding to a C library can name a symbol that older versions of the library lack.
proxy_if_available() takes the loaded library and first checks it for an attribute with
the decorated function’s name. The function must therefore be named after the C symbol. The following example is saved
as mybindings.py:
"""A binding to a C symbol that may be absent.
The decorator line must be on line 8 of the file or later; this docstring makes the room.
"""
from numba import float64
from numba.types import ExternalFunction
from numbox.core.bindings.utils import load_lib
from numbox.core.proxy.proxy import proxy_if_available
lib = load_lib("m")
_cos = ExternalFunction("cos", float64(float64))
@proxy_if_available(lib, float64(float64))
def cos(x):
return _cos(x)
load_lib() opens the library in global symbol mode, so that compiled code can resolve
its symbols; a ctypes.CDLL opened without that mode is not visible to the compiled code. The body calls the C
function through numba’s ExternalFunction, which names the symbol and its C signature. numbox’s own bindings call a
private helper instead, _call_lib_func, which serves only the symbols in numbox’s table
numbox.core.bindings.signatures. Every libm has cos, so proxy_if_available never returns a stub in this
example. The example uses cos in place of a symbol such as sqlite3_changes64, which SQLite added in
version 3.37. numbox guards that symbol in the same way.
If the symbol is present, the result is an ordinary proxied function. If it is absent, the result is a stub: a Python
call raises NotImplementedError, and a jitted caller fails to compile with a TypingError that names the binding
and says that its C symbol is missing. The stub has no .as_func, so code that passes the function as a value checks
for it first:
from callers import apply
from mybindings import cos
if hasattr(cos, "as_func"):
apply(cos.as_func, 0.0)
Caching
After a caller is cached, three things can change: the proxied function, when you edit it; numbox, when you upgrade it; and the C library that a binding calls. numbox repairs the first two cases automatically and reports the third. The one form it cannot repair is the module-level constant of Holding the function as a module-level constant.
After you edit a proxied function
Cached callers in other files still refer to the old version. On the next run, numbox recompiles each of them and warns once per stale cache entry:
StaleProxyCacheWarning: numbox: discarding a stale numba cache entry and recompiling: pipeline.vec_scale-7.py312
references @proxy cfunc alias(es) this process cannot call (the proxied body, signature or jit_options changed
since the caller was cached, or the binding is no longer available): numbox_pxy_scale_e653de386ea6678b
The first name in the warning is the caller’s cache entry: its module, its function, the line of its decorator and the
Python version, here a caller vec_scale in a module pipeline. In later runs, numbox issues no such warning. You
do not need to clear the cache. numba itself recompiles the callers in the same file as the proxied function, because it
detects that the file has changed. The repair covers callers decorated with @njit, @vectorize, @guvectorize
and @cfunc. The exception is a caller that holds .as_func as a module-level constant; see Holding the function
as a module-level constant.
The name at the end of the warning is the alias of the compiled body: a symbol that numbox registers in each process, through which callers reach the body. numbox computes the alias from the body’s code and the values it captures (closure variables, defaults and the globals it reads), from the function’s module and name, and from its signature and jit options. The same body therefore has the same alias in every process. Any change to those inputs renames the alias.
numba’s cache key for a caller does not include the callees, so numbox checks each cache
entry as numba loads it, and discards and recompiles an entry that refers to an alias this process has not registered.
Without the check, the entry would load with the old alias, and the process would end in a segmentation fault or an
LLVM ERROR: Symbol not found abort. The check does not depend on import order: a caller imports the module of the
function it calls, that module imports numbox.core.proxy.proxy, and the check is installed when that module is
imported.
After you upgrade numbox
numbox’s version is part of the cache key of every proxied function, as numbox.core.cache_key explains. The first run after an upgrade therefore compiles each proxied body and its wrapper once more and caches them again. The alias does not include the version, so cached callers load as before. A release that changes the code of one of numbox’s bindings renames that binding’s alias. A release that changes how aliases are computed renames every alias, including the aliases of your own proxied functions. numbox repairs each affected cached caller in the first run after such a release and issues one warning of the kind shown above per caller. The recompilation and the repairs are one-time costs. A caller that holds a numbox binding as a module-level constant is again the exception. You must clear its cache entry manually, as Holding the function as a module-level constant explains.
If numbox warns of an alias collision
An AliasCollisionWarning means that two different proxied functions computed the
same alias. The alias can include a captured value only if the value is the same in every process. A numba
ExternalFunction is the same in every process, and so is a C function reached as an attribute of the loaded
library, such as lib.strlen. A ctypes function built from a raw integer address is not the same in every process,
because address space layout randomization changes the address from one process to the next. numbox therefore excludes
such a function from the alias. Two bodies that differ only in such a value then have the same alias, because numbox
cannot distinguish them.
The remedy is to reach the C function as an attribute of the loaded library rather than through a pointer built from an address. Until you apply it, numbox assigns the second body a name that is used only in this process and stops using the shared alias. Cached callers of either body then recompile in every process instead of running the wrong body. Registering the same body twice is not a collision. After a module reload, or when a function that builds proxied functions is called twice with equal arguments, the alias is pointed at the new compilation and numbox keeps using it.
The same warning can also report a proxy_if_available symbol whose availability differs between two decorations in
the same process; the message says which body callers reach.
If a C symbol disappears
Suppose a caller of a proxy_if_available binding was cached where the library has the symbol, and later runs where
it does not. numbox discards the caller’s cache entry with a StaleProxyCacheWarning. The recompilation then fails
with the same TypingError as a compilation with an empty cache.
Strict mode
Set NUMBOX_PROXY_CACHE_STRICT to make a stale entry fail instead of being repaired, for example to make a test run
fail or to keep the entry on disk for inspection. Any value except 0, false, no, off or the empty
string, in upper or lower case, enables strict mode. For a stale alias, numbox then raises
StaleProxyCacheError instead of discarding the entry. A test run can also turn the
warning itself into an error with pytest’s -W error::numbox.core.proxy.proxy.StaleProxyCacheWarning.
If numbox cannot check a cache entry
The check reads the compiled code in each cache entry to find the aliases it refers to. If the check cannot read an
entry, because a numba release changed the entry’s layout or the file is damaged, numbox loads the entry unchecked and
warns once per process with UnvalidatedProxyCacheWarning. In strict mode the load
raises UnvalidatedProxyCacheError instead.
Holding the function as a module-level constant
numba reads a module-level variable as a compile-time constant, so jitted code can read .as_func from one, although
it cannot read scale.as_func itself. The following example is saved as constant.py:
from numba import njit
from mymodule import scale
SCALE = scale.as_func
@njit(cache=True)
def twice(x):
return SCALE(x) + SCALE(x)
In this form, the caller makes a direct call to the body. LLVM can inline that call. An exception raised in the body
propagates, as it does when .as_func is passed as an argument. twice is cacheable: when numbox lowers the
constant, it links the body’s compiled code into the caller, as numba does for an ordinary callee. Because of the two
costs below, prefer passing .as_func as an argument unless the inlining matters.
The first cost is the one the overview describes: twice embeds its own copy of the compiled body. The second is that
the copy becomes stale silently. The caller’s compiled code names no alias, so numbox’s check cannot detect an edit to
the body, and numba checks only the caller’s own source file for changes. After you edit the body, twice may keep
returning the old result, and numbox gives no warning. The same happens after a numbox upgrade when the constant is a
numbox binding. A StaleProxyCacheWarning in the same run names other callers, but it never names this caller.
The remedy is to delete the caller’s cache files. Their names are the module, the function, the line of its decorator
and the Python version, here constant.twice-8.py312.nbi and constant.twice-8.py312.1.nbc. They are:
in a subdirectory of
NUMBA_CACHE_DIRnamed after the source’s directory, if that variable is set;otherwise in the
__pycache__directory beside the caller’s source;or in numba’s user cache directory, if numba could not write that
__pycache__; the configurations page explains where numba writes the cache.
Even when twice and scale return the same result, the cache entry may still hold the old body, so delete the
files after every edit of the body.
A binding that proxy_if_available may find absent needs care in this form. Where the symbol is missing, a caller
that was cached while the symbol was present still loads. When that caller runs, the process can end in a segmentation
fault without any message on stderr. With an empty cache, a caller such as use_const below fails to compile with a
TypingError. A run with a warm cache and a run with an empty cache therefore behave differently. Strict mode cannot
detect this case, because the caller’s compiled code names no alias for the check to find.
Two forms cannot become stale. In the first form, your module reads .as_func with no check and therefore requires
the symbol: where the symbol is absent, the import fails on the missing attribute before any cache is reached. In the
second form, the caller receives .as_func as an argument, as apply does: the value is supplied at call time, and
a stub has no value to pass.
Of the two guarded forms below, one is safe and one is not:
from numba import njit
from mybindings import cos
if hasattr(cos, "as_func"):
COS = cos.as_func
@njit(cache=True)
def use(x):
return COS(x) # safe: the caller exists only where the binding does
MAYBE_COS = cos.as_func if hasattr(cos, "as_func") else None
@njit(cache=True)
def use_const(x):
return MAYBE_COS(x) # not safe: the cached entry loads the binding from the run that had it
The last form is unsafe because numba’s cache key does not include the value of a module-level variable such as
MAYBE_COS. The cached use_const loads with the body it embedded when it was compiled, whatever MAYBE_COS now
holds.
Modules
numbox.core.proxy.proxy
A decorator that compiles a function once and lets jitted callers call that copy instead of embedding their own.
proxy() compiles the decorated function at import. A jitted caller of the result holds a declaration of the
compiled function and a call to it, not a copy of its code. proxy_if_available() does the same for a binding to a
C symbol that the loaded library may lack. numbox registers each compiled function under an alias that is the same in
every process. It also checks the entries of numba’s CPU cache as numba loads them. If an entry refers to an alias
that this process cannot call, numbox discards the entry, and numba compiles the caller again. The warning and error
classes report what the check finds, and AliasCollisionWarning reports two functions that computed the same
alias.
- exception numbox.core.proxy.proxy.AliasCollisionWarning[source]
Bases:
RuntimeWarningWarning that two different proxied functions computed the same alias, so that the alias identifies neither.
numbox publishes the second function under a name of its own, used only in this process, and treats both names as stale in cache entries. Cached callers of either function therefore compile again in every process. The usual cause is a captured value that differs between processes, such as a ctypes function built from a raw address, which numbox leaves out of the alias. Access the C function as an attribute of the loaded library instead. The warning also reports a
proxy_if_available()binding that is absent in one decoration and present in another in the same process. In that case, the message says which body a call through the alias runs.
- exception numbox.core.proxy.proxy.StaleProxyCacheError[source]
Bases:
RuntimeErrorError that strict mode raises in place of
StaleProxyCacheWarningfor a cache entry with a stale alias.NUMBOX_PROXY_CACHE_STRICTenables strict mode. numbox raises the error before it discards the entry, so the stale entry stays on disk for inspection. By default, numbox discards the entry with the warning, and numba overwrites it with the code it compiles again. To recover, delete the caller’s numba cache files, or unsetNUMBOX_PROXY_CACHE_STRICT.
- exception numbox.core.proxy.proxy.StaleProxyCacheWarning[source]
Bases:
RuntimeWarningWarning that numbox discarded a cached function because it refers to an alias that this process cannot call.
numba then compiles the function again and saves the new code over the stale entry. An alias is stale if the proxied function, its signature or its
jit_optionschanged after the caller was cached, if aproxy_if_available()binding is absent in this process, or if an alias collision retired the alias. To make the warning an error, callwarnings.filterwarnings("error", category=StaleProxyCacheWarning), or run pytest with-W error::numbox.core.proxy.proxy.StaleProxyCacheWarning. The interpreter’s own-Woption andPYTHONWARNINGScannot name this class. Python reads them at startup, before site-packages is on the module path, so the class cannot be imported, and Python ignores the filter.-W error::RuntimeWarningworks, because the class derives fromRuntimeWarning.
- exception numbox.core.proxy.proxy.UnvalidatedProxyCacheError[source]
Bases:
RuntimeErrorError that strict mode raises in place of
UnvalidatedProxyCacheWarningfor an entry it cannot read.NUMBOX_PROXY_CACHE_STRICTenables strict mode. Strict mode refuses to load an entry that numbox could not check, so that a gap in the check becomes visible. The cause can be a numba release that changed the layout of cache entries, or a damaged object. An entry that numbox reads without error, and in which it finds no stale alias, loads normally in strict mode too. A reader that missed the entry’s imports could produce the same result, but numbox cannot distinguish that case from a valid entry that holds the alias prefix only in a string constant.
- exception numbox.core.proxy.proxy.UnvalidatedProxyCacheWarning[source]
Bases:
RuntimeWarningWarning that numbox could not read a numba cache entry and loaded it without checking it for stale aliases.
numbox warns once per process, because the cause, such as a numba release that changed the layout of cache entries, usually affects every entry. In the strict mode that
NUMBOX_PROXY_CACHE_STRICTenables, numbox raisesUnvalidatedProxyCacheErrorinstead.
- numbox.core.proxy.proxy.make_proxy_name(name)[source]
Return the name of the wrapper that
proxy()generates for a function namedname.The name is
namewith two leading underscores. The dispatcher thatproxy()returns has this name, and so does the stub thatproxy_if_available()returns for an absent symbol. numba’s error messages use this name, not the function’s own.
- numbox.core.proxy.proxy.proxy(sig, jit_options: dict | None = None)[source]
Compile the decorated function once, at import, so that jitted callers call it instead of embedding a copy.
sigis a numba signature such asfloat64(float64), or a list of signatures for a function with default arguments. The first signature in a list is the main signature. Each further signature describes a call that omits trailing defaulted parameters, and it types each omitted parameter as numba’sOmittedof its default value. A signature given as a string fails with anAttributeError.jit_optionsis passed tonjitfor the function and for the wrapper that numbox generates around it. A value that is not adictis ignored. The function is cached only ifjit_optionsenables caching, as{"cache": True}andnumbox.core.configurations.jit_optionsdo.The decorator returns the dispatcher of the wrapper. The dispatcher’s name is
__followed by the function’s name, and its docstring is the function’s docstring. A call through the dispatcher, from Python or from jitted code, enters the compiled function through its C entry point, under an alias that numbox registers in every process. If the function raises, such a call does not propagate the exception: Python prints it to stderr, and the call returns a zero of the return type. The wrapper takes every parameter as positional-or-keyword, so a keyword-only parameter can also be passed by position.The dispatcher’s
.as_funcis the compiled function as a first-class function value, aDeriveWAP. It has only the main signature, so a call through it passes every parameter. Read it in Python and pass it to a jitted function as an argument, because jitted code cannot read it from the dispatcher. An exception raised in the function propagates out of a call through.as_func, unless Python passes the value into a parameter that the jitted function declares as a plainFunctionType.numbox computes the alias from the function’s module, qualified name, code and docstring, the values it captures, the main signature and
jit_options. An edit to any of these renames the alias. numbox then discards each cached caller that refers to the old alias, and numba compiles the caller again. numbox warns once for each discarded entry withStaleProxyCacheWarning, or raisesStaleProxyCacheErrorin the strict mode thatNUMBOX_PROXY_CACHE_STRICTenables. A jitted caller that reads.as_funcfrom a module-level variable embeds a copy of the function instead, and the check cannot see that copy. After an edit, such a cached caller can continue to run the old code without a warning, so delete its cache files after every edit. If the C symbol of aproxy_if_available()binding is missing, such a caller can return the missing binding’s result or crash with a segmentation fault.Decoration raises a
ValueErrorif the function’s first decorator line is above line 8 of its file, or if its module defines a global named__followed by the function’s name. A function that takes*argsor**kwargscannot be proxied: with a signature for its other parameters, decoration fails with numba’s signature-mismatchTypeError. UnderNUMBA_DISABLE_JIT=1, decoration fails with anAttributeError. The documentation pagenumbox.core.proxyshows examples.
- numbox.core.proxy.proxy.proxy_if_available(lib, sig, jit_options: dict | None = None)[source]
Apply
proxy()iflibhas a C symbol named after the decorated function, and return a stub if not.The decorated function must have the C symbol’s name, because the check is
hasattr(lib, name). This suits a binding to a symbol that only newer versions of a library provide. If the symbol is present, the result is whatproxy()returns,.as_funcincluded. If it is absent, the result is a stub with the name thatmake_proxy_name()returns, and with the function’s qualified name and docstring. A call to the stub from Python raisesNotImplementedError. A jitted caller of the stub fails to compile with aTypingErrorthat names the binding and says that its C symbol is missing.cres_if_available()makes the same check forcres().The stub has no
.as_func, so code that passes the function as a value checks for the attribute first:if hasattr(my_binding, "as_func"): use(my_binding.as_func)
A caller cached in a process where the symbol was present refers to the binding’s alias. Where the symbol is absent, numbox discards that cache entry with a
StaleProxyCacheWarning, and the recompilation fails with the sameTypingError.