numbox.core.work
Overview
Functionality for fully-jitted and light-weight calculation on a graph. Fully jitted means that the whole calculation, including the traversal of the graph, runs in numba-compiled code rather than in Python.
Modules
numbox.core.work.builder
Overview
Pure Python abstraction for creation of JIT’ed graph of numbox.core.work.work.Work nodes.
Later examples of this overview use names that earlier examples define, so run the examples in order, in one
session.
Users can define the specs of end nodes [1]:
from numba.core.types import int16
from numbox.core.work.builder import End
w1_ = End(name="w1", init_value=137, ty=int16)
w2_ = End(name="w2", init_value=3.14)
w5_ = End(name="w5", init_value=10)
w6_ = End(name="w6", init_value=7.5)
where ty=int16 illustrates the optional ty argument, which sets the numba type of a node. Suppose more values, w3, w4, w7, w8, w9, w10, are derived as follows:
def derive_w3(w1_, w2_):
if w1_ < 0:
return 0.0
elif w1_ < 1:
return 2 * w2_
return 3 * w2_
def derive_w4(w1_):
return 2 * w1_
def derive_w7(w3_, w5_):
return w3_ + (w5_ ** 2)
def derive_w8(w6_, w2_):
if w6_ > 5:
return w6_ * w2_
else:
return w6_ + w2_
def derive_w9(w3_, w4_, w7_):
return (w4_ - w3_) / (abs(w7_) + 1e-5)
def derive_w10(w3_, w4_, w7_, w8_, w9_):
return (w3_ + w4_ + w7_) * 0.1 + (w8_ - w9_)
End and Derived are node specs rather than nodes: the actual node objects are the instances of
numbox.core.work.work.Work that the builder creates from them. Users can then declare the specs of the
derived nodes as:
from numbox.core.work.builder import Derived
w3_ = Derived(name="w3", init_value=0.0, derive=derive_w3, sources=(w1_, w2_))
w4_ = Derived(name="w4", init_value=0.0, derive=derive_w4, sources=(w1_,))
w7_ = Derived(name="w7", init_value=0.0, derive=derive_w7, sources=(w3_, w5_))
w8_ = Derived(name="w8", init_value=0.0, derive=derive_w8, sources=(w6_, w2_))
w9_ = Derived(name="w9", init_value=0.0, derive=derive_w9, sources=(w3_, w4_, w7_))
w10_ = Derived(name="w10", init_value=0.0, derive=derive_w10, sources=(w3_, w4_, w7_, w8_, w9_))
A DAG can then be constructed and used as follows [2]. Its access nodes are w7, w9 and w10: their specs
w7_, w9_ and w10_ are passed to numbox.core.work.builder.make_graph(), which returns a Work node for
each of them:
from numbox.core.work.builder import make_graph
access = make_graph(w7_, w9_, w10_)
w7 = access.w7
w9 = access.w9
w10 = access.w10
Here access is a named tuple with one numbox.core.work.work.Work node for each access node:
from numbox.core.work.work import Work
assert isinstance(w7, Work)
assert isinstance(w9, Work)
assert isinstance(w10, Work)
One can then compute and access values of the derived nodes:
from numpy import isclose
assert w10.data == 0
w10.calculate()
assert isclose(w7.data, 109.42)
assert isclose(w9.data, 2.418022)
assert isclose(w10.data, 60.416)
Specs are required to have a unique name attribute within their registry, the dictionary in which the builder keeps them by name. Attempting to declare a second spec, either End or Derived, with a name that is already in the registry will raise ValueError. The paragraphs on the global registry _specs_registry, near the end of this overview, describe registries.
Graph structure can be inspected as:
from numbox.core.work.print_tree import make_image
print(make_image(w10))
which outputs:
w10--w3--w1
| |
| w2
|
w4--w1
|
w7--w3--w1
| | |
| | w2
| |
| w5
|
w8--w6
| |
| w2
|
w9--w3--w1
| |
| w2
|
w4--w1
|
w7--w3--w1
| |
| w2
|
w5
The visualization utility for a sub-graph tree numbox.core.work.print_tree.make_image()
spans the breadth in the vertical direction and the depth in the horizontal direction.
The nodes are uniquely identified by their names.
To simplify the image structure, the same node can appear on one graph image multiple times.
Each Work can be represented as a light-weight numbox.core.work.node.Node. The first call of as_node
creates the Node and stores it in the node attribute of the Work, and later calls return the stored Node.
Here w3, the first source of w10, is taken from w10.sources:
w3 = w10.sources[0]
w3_n = w3.as_node()
The Node representation enables an assortment of utilities, which Work provides as methods that delegate to the Node. all_inputs_names lists the inputs transitively: the inputs of w7 include w1 and w2, the inputs of its source w3:
assert w3.all_inputs_names() == ["w1", "w2"]
assert w7.all_inputs_names() == ["w3", "w1", "w2", "w5"]
assert w3.depends_on("w1")
assert w3.get_input(0).name == "w1"
assert w10.get_input(3).name == "w8"
From an access node, here w10, values of nodes can be combined into a sheaf. A sheaf is a typed dictionary that maps each requested node name to an Any value (numbox.core.any), and w10.combine sets each value to the data of the node of that name in the graph of w10:
from numba.core.types import float64
from numbox.core.work.combine_utils import make_sheaf_dict
requested = ("w1", "w4", "w7", "w8")
sheaf = make_sheaf_dict(requested)
w10.combine(sheaf)
assert isclose(sheaf["w4"].get_as(float64), 274)
assert isclose(sheaf["w7"].get_as(float64), 109.42)
assert isclose(sheaf["w8"].get_as(float64), 23.55)
Values can be loaded into graph nodes through the access node as follows [3]:
from numba.core.types import int16, unicode_type
from numba.typed.typeddict import Dict
from numbox.core.any.any_type import AnyType, make_any
load_data = Dict.empty(key_type=unicode_type, value_type=AnyType)
assert sheaf["w1"].get_as(int16) == 137
load_data["w1"] = make_any(int16(12))
w10.load(load_data)
w10.combine(sheaf)
assert sheaf["w1"].get_as(int16) == 12
load clears the derived flag of each loaded node and of each node that depends on it, up to the node on which load is called. Recalculating the graph then computes new values of the affected nodes [4]:
w10.calculate()
w10.combine(sheaf)
assert isclose(sheaf["w4"].get_as(float64), 24)
Builder supports smart caching of compiled code that builds the graph from the specified End and Derived specs. If caching of the JIT’ed functions is configured (which is a default behavior), the graph maker is re-compiled when the name, sources, numba type or derive function of a node changes. It is not re-compiled when only the value of an init_value changes, because the cached graph maker receives the initial values as arguments.
The init_value attribute of the End and Derived specs can be assigned a variety of values, including scalars, arrays, and instances of StructRef. Only the numba type of each value enters the builder’s cache key, so a changed value, a StructRef included, does not make the builder recompile.
From each given access node, one can trace its derivation to all the End nodes:
from numbox.core.work.explain import explain
derivation_of_w9 = explain(w9)
print(derivation_of_w9)
prints:
All required end nodes: ['w1', 'w2', 'w5']
w1: end node
w2: end node
w3: derive_w3(w1, w2)
def derive_w3(w1_, w2_):
if w1_ < 0:
return 0.0
elif w1_ < 1:
return 2 * w2_
return 3 * w2_
w4: derive_w4(w1)
def derive_w4(w1_):
return 2 * w1_
w5: end node
w7: derive_w7(w3, w5)
def derive_w7(w3_, w5_):
return w3_ + (w5_ ** 2)
w9: derive_w9(w3, w4, w7)
def derive_w9(w3_, w4_, w7_):
return (w4_ - w3_) / (abs(w7_) + 1e-5)
This lists the end nodes that the derivation of the given node needs, that is, the inputs that no derive computes, followed by the logical sequence of steps (as indicated by the graph structure) to carry out the derivation.
By default, defining End or Derived node spec will store the created node spec instance
in the global registry _specs_registry (in numbox.core.work.builder) as a value paired to the key
given by the spec’s name.
A second spec with the same name in the same registry raises the ValueError described above.
Optionally, any number of (local) registries can be created, and node specs can be registered in them. To do so, provide a dictionary-valued argument as the registry parameter of either Derived or End. Then the make_graph utility needs to be provided with the same registry as its keyword argument:
reg_1 = {}
end_1 = End(name="end_1", init_value=0.0, registry=reg_1)
reg_2 = {}
end_1_another = End(name="end_1", init_value=0.0, registry=reg_2)
der_1 = Derived(name="der_1", init_value=0.0, sources=(end_1,), registry=reg_1, derive=lambda x: x + 2.17)
accessors_1 = make_graph(der_1, registry=reg_1)
der_1_ = accessors_1.der_1
der_1_.calculate()
assert isclose(der_1_.data, 2.17)
der_1_another = Derived(
name="der_1", init_value=0.0, sources=(end_1_another,), registry=reg_2, derive=lambda x: x + 3.14
)
accessors_2 = make_graph(der_1_another, registry=reg_2)
der_1_another_ = accessors_2.der_1
der_1_another_.calculate()
assert isclose(der_1_another_.data, 3.14)
In this example, there are two specs named “end_1” and two specs named “der_1”, but they are defined in different registries, and the two corresponding graphs are built from the specs obtained from their respective registries.
Node specs and the builder that compiles them into a jitted graph of Work nodes.
End and Derived declare the nodes, and each spec is registered under its name in a registry, by
default _specs_registry. make_graph() compiles a function, the graph maker, that creates the requested access
nodes and every node they depend on, and returns the access nodes as Work nodes. The module also computes the names
under which numba caches the graph maker and the derives, so that numba compiles them again after a change to a node.
- class numbox.core.work.builder.Derived(*args, **kwargs)[source]
Bases:
_DerivedSpec of a derived node: a node whose value
derivecomputes from the values ofsources.deriveis a plain Python function with one parameter per source, andmake_graph()compiles it for the node’s type over the types of the sources.sourcesis a tuple of specs.init_valueis the value that the node holds until it is calculated.name,registryandtyfollow the rules ofEnd.
- class numbox.core.work.builder.End(*args, **kwargs)[source]
Bases:
_EndSpec of an end node: a node whose value is given rather than computed.
nameandregistrymust be passed by keyword, because the registration reads them from the keywords. The spec is registered undernameinregistry, by default the module’s_specs_registry, and a name that the registry already holds raisesValueError.init_valueis the node’s initial value.ty, a numba type, sets the node’s type in place of the type ofinit_value, and numba converts the initial value to it.
- numbox.core.work.builder.code_block_hash(code_txt: str)[source]
Return the SHA-256 hex digest of
code_txt._kernel_fingerprinthashes the graph maker’s code text together with the derives’ fingerprints, the nodes’ types, the jit flags and numba’s settings, and the maker is named after the digest. A change to any of them changes the maker’s name, so numba does not load the code that it cached under the earlier name.
- numbox.core.work.builder.get_ty(spec_)[source]
Return the numba type of a spec’s node: its
tyif given, otherwise numba’s type for itsinit_value.
- numbox.core.work.builder.infer_end_and_derived_nodes(access_nodes: Tuple[Derived | End, ...], registry)[source]
Return the specs of the end nodes and of the derived nodes that
access_nodesneed, as two lists.The walk starts at each access node and follows the sources depth first, so a derived node comes after the derived nodes it reads; the access nodes are included. Each spec in the lists is the one that
registryholds under the node’s name, and a name thatregistrylacks raisesKeyError.
- numbox.core.work.builder.make_graph(*access_nodes: Derived | End, registry: dict | None = None, jit_options: dict | None = None)[source]
Create the graph that the given access node specs need, and return the access nodes as
Worknodes.The specs are looked up by name in
registry, by default_specs_registry. The result is a named tuple with one field per access node, named after the node, and each call creates new nodes.jit_optionstake precedence over numbox’s jit options for each derive and for the graph maker, the function that creates the nodes. With caching enabled, which is the default, numba caches the graph maker as a function defined in this module’s file. numba compiles the maker again after a change to a node’s name, sources, type or derive, to a jit option other thancache, or to a numba setting that changes the generated code. A change to aninit_valuealone reuses the cached maker, because the initial values are the maker’s arguments.The maker compiles without a cache when numbox cannot fingerprint a derive, when a node’s type contains a dispatcher, or when a jit option has no canonical form. If numba has no cache location for this module’s file,
make_graphissues aRuntimeWarningand compiles the maker without a cache. A derive that reads its module’s globals always compiles without a cache.
numbox.core.work.builder_utils
Queries on a graph of node specs, or of the Work nodes built from them. infer_sources_dependencies() finds,
for each node, the nodes that depend on it.
- numbox.core.work.builder_utils.infer_sources_dependencies(access_nodes: NamedTuple | Tuple)[source]
Return a dictionary from the name of each node of the graph of
access_nodesto the names of its dependents.A node’s dependents are the nodes that have it as a source, directly or through other nodes.
access_nodesholds specs, such asEndandDerived, or theWorknodes thatmake_graph()returns. An access node without sources has no entry in the dictionary. In the graph below,m1has the sourcesm2andm4,m2has the sourcem3, andm3has the sourcem5:m1 -- m2 -- m3 -- m5 | m4
For the access node
m1, the function returns:{ "m1": set(), "m2": {"m1"}, "m3": {"m1", "m2"}, "m4": {"m1"}, "m5": {"m1", "m2", "m3"} }
numbox.core.work.combine_utils
Collect the values of a graph’s nodes. make_sheaf_dict() makes a sheaf, a typed dictionary of Any values
keyed by node name, for Work.combine to fill. load_dict_into_array() copies a sheaf into the first row of a
NumPy structured array, whose dtype make_requested_dtype() makes.
- numbox.core.work.combine_utils.add_one(node, sheaf)[source]
Add an entry for
node, a node or a node name, tosheaf, with anAnyvalue that holdsNone.If the name of
nodeis not a string, an assertion fails.
- numbox.core.work.combine_utils.load_dict_into_array(array, sheaf)[source]
Copy the values of
sheafinto the first row of the structured arrayarray, one field per node name.make_requested_dtype()makes a matching dtype, and each value must hold the type of its field.
- numbox.core.work.combine_utils.make_requested_dtype(requested: dict)[source]
Return an aligned NumPy structured dtype with one field for each requested node, named after the node.
requestedmaps each node, or node name, to the dtype of its field.
- numbox.core.work.combine_utils.make_sheaf_dict(requested: Node | str | Work | Collection[Node | str | Work])[source]
Return a sheaf, a typed dictionary from the name of each requested node to an
Anyvalue that holdsNone.requestedis a node, a node name, or a collection of them.Work.combinereplaces each value with thedataof the node of that name.
- numbox.core.work.combine_utils.ol_load_array_row_into_dict(array_ty, sheaf_ty)[source]
Implement
load_dict_into_arrayin jitted code: set each field of the array’s first row from the sheaf.Each field’s name must be a key of the sheaf, and the value stored under that key must hold the field’s type, because
get_asreads the value without a conversion.
numbox.core.work.loader_utils
Load the fields of a NumPy structured array into a graph. Called from jitted code,
load_array_row_into_dict() stores the fields of one row in a typed dictionary of Any values keyed by field
name, the dictionary that Work.load reads. np_struct_member_type() gives the numba type of a field.
- numbox.core.work.loader_utils.load_array_row_into_dict(*args)[source]
Store each field of one row of a structured array, under the field’s name, in a dictionary of
Anyvalues.Call it from jitted code as
load_array_row_into_dict(array, row_index, loader_dict).loader_dictis a typed dictionary from strings toAnyvalues, whichWork.loadreads. Called from Python, the function raisesNotImplementedError.
numbox.core.work.node
Overview
numbox.core.work.node.Node represents a node on a directed acyclic graph
(DAG)
that exists in a fully jitted scope and is accessible both at the low-level and via a Python proxy.
Node can be used on its own (in which case the recommended way to
create it is via the factory function numbox.core.work.node.make_node())
or as a prototype to more functionally-rich graph nodes,
such as numbox.core.work.work.Work.
The logic of Node and its sub-classes follows a graph-optional design: no graph orchestration structure is required to register and manage the graph of Node instance objects. This in turn reduces unnecessary computation overhead and simplifies the program design.
To that end, each node is identified by its name and contains a uniformly-typed vector-like container member, a numba-native numba.typed.List, with references to all the input nodes that it depends on. This enables a traversal not only of graphs of Node instances themselves but also graphs of objects representable by it, such as, the graphs of Work nodes.
Node implementation makes heavy use of the numba
meminfo
paradigm that manages memory-allocated
payload via smart pointer (pointer to numba’s meminfo object) reference counting.
This allows users to reference the desired
memory location via a ‘void’ structref type, such as,
numbox.core.any.erased_type.ErasedType, or numbox.utils.void_type.VoidType,
or base structref type, such as, numbox.core.work.node_base.NodeBaseType,
and dereference its payload accordingly when needed via the appropriate numbox.utils.lowlevel.cast().
The Node type: a named node and its inputs, the structure of a graph without values or functions.
Node is the Python proxy, make_node() creates a node from
Python or from jitted code, and the overloads below implement the node’s methods in jitted code. A
Work node creates a Node representation of itself with as_node and answers
all_inputs_names and all_end_nodes through it.
- class numbox.core.work.node.Node(name, inputs)[source]
Bases:
NodeBaseA node of a directed acyclic graph that holds its name and the nodes it depends on, its inputs.
make_node()creates a node, from Python or from jitted code, and so doesNode(name, inputs). The inputs are stored in a typed list ofNodeBaseType.all_inputs_names,all_end_nodesanddepends_onwalk the graph by reading each input as aNode, andget_inputreturns an input as aNode. For an input of another type, such as aWorknode, these methods read its payload with the wrong layout, and the process can crash. For a graph ofWorknodes, use theNoderepresentations thatWork.as_nodecreates.- all_end_nodes()[source]
Return the names of the nodes without inputs that this node depends on, each once.
- all_inputs_names()[source]
Return the names of all the nodes this node depends on, each once, in depth-first order.
- depends_on(obj_)[source]
Return whether this node depends on
obj_, a node name or aNode, directly or through other nodes.
- class numbox.core.work.node.NodeTypeClass(*args, **kwargs)[source]
Bases:
NodeBaseTypeClassThe numba type class of
NodeType, the type of everyNode.
- numbox.core.work.node.make_node(name, inputs=())[source]
Create a
Nodenamednamewhose inputs are the nodesinputs, from Python or from jitted code.inputsis a tuple ofNodenodes. TheNodeclass explains why a node of another type must not be an input.
- numbox.core.work.node.ol_all_end_nodes(self_ty)[source]
Implement
Node.all_end_nodes()in jitted code, returning the names as a typed list.
- numbox.core.work.node.ol_all_inputs_names(self_ty)[source]
Implement
Node.all_inputs_names()in jitted code, returning the names as a typed list.
- numbox.core.work.node.ol_depends_on(self_ty, obj_ty)[source]
Implement
Node.depends_on(obj)in jitted code, for a name or aNode.For an argument of another type, an assertion fails when numba compiles the call.
- numbox.core.work.node.ol_get_input(self_ty, i_ty)[source]
Implement
Node.get_input(i)in jitted code: return the input at indexiasNodeBaseType.A negative index, or one past the last input, raises
NumbaError.
numbox.core.work.node_base
Overview
Base class for numbox.core.work.node.Node and numbox.core.work.work.Work.
Contains functionality dependent only on the node name.
The base node type NodeBaseType, whose only field is the name, and its Python proxy NodeBase.
Every Node and Work payload begins with the name field, so a node of either kind can be cast to
NodeBaseType; the inputs of a Node are stored that way.
- class numbox.core.work.node_base.NodeBase(name)[source]
Bases:
StructRefProxyA node whose only field is its name: the Python proxy of
NodeBaseTypeand the base class of Node and Work.NodeBaseTypehas one field,name. The payloads ofNodeandWorknodes begin with that field, so a node of either kind can be cast toNodeBaseType, as the inputs of aNodeare cast. CallingNodeBaseraisesNotImplementedErrorin Python and fails to compile in jitted code.- property name
The node’s name.
numbox.core.work.print_tree
Overview
Provides utilities to print a tree from the given node’s dependencies.
The node can be either instance of numbox.core.work.node.Node
or numbox.core.work.work.Work:
from numbox.core.work.node import make_node
from numbox.core.work.print_tree import make_image
n1 = make_node("first")
n2 = make_node("second")
n3 = make_node("third", inputs=(n1, n2))
n4 = make_node("fourth")
n5 = make_node("fifth", inputs=(n3, n4))
tree_image = make_image(n5)
print(tree_image)
which outputs:
fifth--third---first
| |
| second
|
fourth
Notice that the tree depth extends in horizontal direction, the width extends in vertical direction and is aligned to recursively fit images of the sub-trees.
For the sake of readability, if multiple nodes depend on the given node, the latter will be accordingly displayed multiple times on the tree image, for instance:
n1 = make_node("n1")
n2 = make_node("n2", (n1,))
n3 = make_node("n3", inputs=(n1,))
n4 = make_node("n4", inputs=(n2, n3))
tree_image = make_image(n4)
produces:
n4--n2--n1
|
n3--n1
Both references to ‘n1’ point to the same node, which is a source of two other nodes, ‘n2’ and ‘n3’.
A text drawing of a node and the nodes it depends on.
make_image() returns the drawing for a Node or a
Work node; make_graph() lays the tree out on a grid
first.
- class numbox.core.work.print_tree.ImmutableItemDict[source]
Bases:
dictA dictionary in which each key can be set only once; setting a key again raises
ValueError.The layout uses it to detect two items placed in one cell of the grid.
- numbox.core.work.print_tree.calculate_col_widths(graph)[source]
Return the width of each column of the grid
graph: the length of the longest item in the column.graphmaps (row, column) pairs to strings.
- numbox.core.work.print_tree.make_graph(node)[source]
Return the tree of
nodelaid out on a grid, with the numbers of rows and columns and the column widths.The grid maps (row, column) pairs to strings. Each item is padded to its column’s width, with
-when the next cell of its row holds an item and with spaces otherwise; a|is always padded with spaces. The inputs of a node are placed two columns to its right, one below another, and a node that the tree reaches along several paths appears once on each path.
- numbox.core.work.print_tree.make_image(node)[source]
Return a text drawing of the tree of
nodeand of the nodes it depends on.nodeis aNodeor aWorknode. Deeper nodes are drawn further to the right, and the inputs of a node are drawn one below another. A node that the tree reaches along several paths appears once on each path. The text begins with a newline, and no row ends in a space.
numbox.core.work.work
Overview
Defines numbox.core.work.work.Work StructRef.
Work is a unit of calculation work that is designed to
be included as a node on a jitted graph of other Work nodes.
The Python class Work subclasses numbox.core.work.node_base.NodeBase
and follows the logic of graph design of numbox.core.work.node.Node.
However, since numba StructRef does not support low-level subclasses,
there is no inheritance relation between NodeBaseType and WorkType,
leaving the data design to follow the composition pattern.
Namely, the member (name) of the NodeBase payload is a header in the payload of Work, which makes
a numbox.utils.lowlevel.cast() between the two meaningful.
The main way to create a Work instance is via the numbox.core.work.work.make_work() constructor
(Work(…) instantiation is in fact disabled both in Python and jitted scope). make_work can be invoked either
from Python or from jitted scope: the run function below works with or without its @njit decorator. Its
derive is compiled with numbox.utils.highlevel.cres(), which compiles a function for one signature and
returns it as a first-class function value:
import numpy
from numba import float64, njit
from numbox.core.work.work import make_work
from numbox.utils.highlevel import cres
@cres(float64(), cache=True)
def derive_work():
return 3.14
@njit(cache=True)
def run(derive_):
work = make_work("work", 0.0, derive=derive_)
work.calculate()
return work.data
assert numpy.isclose(run(derive_work), 3.14)
When called from jitted scope, if cacheability of the caller function
is a requirement, the derive function should be passed to run as
a FunctionType (not njit-produced CPUDispatcher) argument, i.e.,
decorated with numbox.utils.highlevel.cres(). If run instead took no
argument and read derive_work from the global scope, numba could not cache run.
For performance-critical large graphs, with hundreds of nodes or more created in a jitted scope,
numbox.core.work.work.make_work() is not feasible. Called from jitted code, it results in large memory use,
and in large disk use when the jitted caller is cached. Declaring make_work with numba’s inline=True directive
would produce a much smaller and optimized final compilation result, but its compilation would take a
substantial time. For such graphs it is recommended to use the low-level intrinsic
numbox.core.work.lowlevel_work_utils.ll_make_work as follows:
from numba import njit
from numba.core.types import float64
from numpy import isclose
from numbox.core.work.node_base import NodeBaseType
from numbox.core.work.lowlevel_work_utils import ll_make_work, create_uniform_inputs
from numbox.core.work.print_tree import make_image
from numbox.utils.highlevel import cres
@cres(float64())
def derive_v0():
return 3.14
@njit(cache=True)
def v0_maker(derive_):
return ll_make_work("v0", 0.0, (), derive_)
v0 = v0_maker(derive_v0)
assert v0.data == 0
assert v0.name == "v0"
assert v0.inputs == ()
assert not v0.derived
v0.calculate()
assert isclose(v0.data, 3.14)
Importantly, Work objects support the as_node method, implemented by numbox.core.work.work.ol_as_node().
It creates a numbox.core.work.node.Node instance with the same name as the Work instance and a vector
of inputs of the numbox.core.work.node_base.NodeBase type that references the Node representations of
the original Work instance’s sources. Upon the first invocation of as_node on the given Work
instance, Node representations for itself and recursively all its sources
are created and stored in their node attributes only once. Subsequent invocations
of as_node on either the given Work node or any of nodes on its sub-graph
will return the previously created Node objects stored as the node attribute.
Exception handling
A node’s derive is the function that computes the node’s data from the data of its sources. If the
derive raises an exception, calculate() raises the same exception, with its type
and message. The node keeps its data. Its derived flag, which calculate sets once the node is calculated,
stays unset, so a later calculate runs the derive again. Three ways of passing a derive lose the exception
instead, as When the exception is lost describes.
In the example below, make_work_helper() builds the nodes. Its derive_py
argument takes the derive as a plain Python function, which the helper compiles with
cres(). The source holds a one-element array, so that its value can change in place
between the two calls:
import numpy
from numbox.core.work.work_utils import make_work_helper
def derive_reciprocal(x_):
if x_[0] == 0.0:
raise ValueError("zero input")
return 1.0 / x_[0]
source = make_work_helper("source", numpy.zeros(1))
node = make_work_helper("node", 1.0, sources=(source,), derive_py=derive_reciprocal)
try:
node.calculate()
except ValueError as e:
print(e) # zero input
assert node.data == 1.0
assert not node.derived
source.data[0] = 4.0
node.calculate()
assert node.data == 0.25
cres compiles a function for one signature and returns it as a first-class function value, a value that jitted code can receive and
call. This page calls such a value a cres function. Exceptions propagate in the same way in four cases:
a
cresfunction passed tomake_work()from Python;a
cresfunction passed to a jitted function that builds the node withmake_workorll_make_work;a plain Python function given to
Derived, which compiles it withcres;the
.as_funcvalue of a function decorated withproxy().
The sections below describe the limits of this rule: three ways of passing a derive that lose its exception,
tuples that mix kinds of function values, jitted code that catches the exception, and parallel loops. A derive
that must report a failure in those situations can do so through its return value, for example by returning a NaN.
When the exception is lost
In three cases calculate returns normally although the derive raised. Python prints the exception to stderr
below a line that begins Exception ignored in:, which means that the exception was printed and then
discarded.
calculate sets derived and stores in data the value that the failed call returned. That value is usually
zero-filled, of the derive’s return type, such as 0.0 or an empty array. Do not rely on it: a @cfunc
declared float64() whose body always raises returns an arbitrary value instead. A later calculate does not run
the derive again, because derived is set, and the node keeps the stored value.
Warning
A zero-filled string holds a null pointer. Reading such a data from Python, as node.data, ends the process
with a segmentation fault.
The three cases are:
A
derivepassed from Python to a jitted function whose parameter is declared as numba’sFunctionType, fromnumba.types. This page calls numba’s own type the plainFunctionType; numbox assigns acresfunction the typeDeriveFunctionType, a subclass of it. For example,@njit(float64(FunctionType(float64(float64))))declares one parameter of the plain type, for a function that takes and returns afloat64. The exception is lost because numba converts the value to the plain type when Python passes it to the jitted function. The loss occurs only at that boundary between Python and jitted code: within jitted code, aderivepassed on to a function that declares the plainFunctionTypestill propagates its exception. For the exception to propagate, let numba infer the parameter’s type, or declare the parameter asDeriveFunctionType(float64(float64)), withDeriveFunctionTypefromnumbox.utils.derive_wap. A parameter declared that way accepts onlycresfunctions and.as_funcvalues.A
CompileResultWAPthat you build with numba directly.CompileResultWAP, fromnumba.core.types.function_type, is numba’s function value for one compiled function, andCompileResultWAP(f.get_compile_result(sig))builds one for an@njitfunctionf. The exception is lost when such a value reaches jitted code as an argument or as a global variable, because the value has the plainFunctionType.make_work()upgrades the value when Python callsmake_work, but a jitted function that receives the value cannot upgrade it. For the exception to propagate, build thederivewithcres, or upgrade the value in Python withrewrap_derive()before jitted code receives it.A
@cfuncused as aderive, whether it reachesmake_workfrom Python or from jitted code. The exception is lost because a@cfunchas the plainFunctionTypeand numbox does not upgrade a@cfunc. For the exception to propagate, compile the function withcresinstead.
numba can call a function value through two entry points. The numba entry point follows numba’s own calling convention
and propagates an exception to the caller. The C entry point, the kind that @cfunc builds, does not propagate an
exception: numba discards the exception there, as numba issue 8246
describes. numba records the numba entry point of a value only when the value comes from a dispatcher. For that reason
an @njit function compiled for a signature still propagates its exception when it is passed to a parameter of the
plain FunctionType. A compile result that numba’s own CompileResultWAP wraps is called through its C entry
point. cres therefore wraps its compile result in a DeriveWAP instead, and numbox
assigns that wrapper the numba type DeriveFunctionType. That type records the numba
entry point, and calculate calls a derive of that type through it. In the three cases above, the derive
reaches calculate as a value of the plain FunctionType with only its C entry point.
numbox.utils.derive_wap describes the mechanism.
Other limits
Jitted code can receive several function values at once as the elements of a tuple, for example the derive functions
of the nodes it builds. Below numba 0.68.0, a tuple whose elements take the same number of arguments but have
different types can fail with an AssertionError that has no message. Four kinds of function value can fail this
way in one tuple with a cres function: a @cfunc, an @njit function compiled for a signature, numba’s own
CompileResultWAP, and a cres function of another signature. The assertion is numba’s own check, and two plain
function values of different types can fail it as well. A cres function fails the check more often, because
numbox assigns it DeriveFunctionType, while numba assigns the other kinds the plain FunctionType. numba 0.68.0
accepts every such tuple, and each cres function in it still propagates its exception.
Under python -O, which removes assertions, numba below 0.68.0 skips that check and assigns the whole tuple the type
of its first element. A cres function that comes after another kind in the tuple then loses its exception. Another
kind that comes after a cres function raises a TypeError that names the value’s class.
A lazily compiled @njit function, one decorated without a signature, that takes as many arguments as a cres
function cannot be an element of one tuple with it on any numba version. Passing such a tuple to a jitted function
raises this error:
TypeError: DeriveFunctionType value must be a DeriveWAP, got <class 'numba.core.registry.CPUDispatcher'>
The message means that numba typed the whole tuple as DeriveFunctionType and numbox refused the CPUDispatcher
value, the lazily compiled function. Compile that function with cres too.
The .as_func value of a proxied function counts as a cres function in these rules. The proxy page’s section on
passing the function as a value states the same rules for .as_func.
A jitted caller can catch the exception of a derive only with a bare except: or with except Exception:.
numba accepts no other except clause, and it cannot bind the exception to a name with as; see numba’s
try .. except. Jitted code therefore
cannot read the exception’s type or message.
Exceptions in parallel loops
A raise written directly in the body of a prange loop makes numba run that loop serially. numba runs a loop in
parallel only if the loop has a single exit (see numba’s explicit parallel loops), and it warns with a
NumbaPerformanceWarning when it cannot. A derive whose own prange loop raises in this way therefore
propagates its exception like any other derive. A derive compiled with nogil=True also propagates its
exception like any other derive, because nogil only releases Python’s global interpreter lock while the
derive runs. The derive still runs on the thread that called it, and no parallel loop is involved.
An exception raised in a function that the body of a parallel loop calls is different, because numba does run that loop
in parallel. The thread that ran the failing iteration skips the rest of the iterations assigned to it, so the result
does not include the computation of that iteration or of the later iterations assigned to that thread. With numba’s omp
threading layer, the call from Python raises SystemError: ... returned a result with an exception set when the
failing iteration ran on the calling thread, and returns normally when it ran on another thread. With the workqueue
layer, the call always returns normally. The SystemError means that the jitted function returned while the exception
was still pending. Its __cause__ is the original exception, and an except clause for the original exception’s
type does not catch the SystemError. Either way, the jitted code after the loop runs as if the loop had succeeded. A
plain jitted function that does not use numbox behaves the same way.
If calculate runs in the body of a parallel loop and the derive raises, the node is left intact: it keeps its
data, and derived stays unset. Check node.derived after the loop to learn whether the derive
succeeded. A later calculate outside the loop raises the exception normally.
If the derive itself runs a parallel loop and a function called from its body raises, the derive returns
normally to calculate, which cannot detect the failure. calculate stores the incomplete result in data and
sets derived, so the failure stays cached, even when the call from Python then raises the SystemError. In a
derive, do not raise exceptions in the functions that a parallel loop calls.
After you upgrade or downgrade numbox
numbox 0.7.3 is the first release in which the exception of a derive propagates, on numba 0.61 or later. A
function of your own that numba caches may keep the old behavior after the upgrade. Its cache entry holds the code
that numbox generated for its calls of calculate, and numba’s key for the entry leaves out the code of the
functions it calls (what the key leaves out). As long as the function’s file and
signature stay unchanged, numba keeps loading that code.
A cached function that takes a cres function, or a node built from one, recompiles automatically, because numbox
0.7.3 assigns a cres function a new numba type on numba 0.61 or later. Consider instead a cached function whose
parameter is declared as the plain FunctionType. If it receives an @njit function compiled for a signature,
numba continues to load its 0.7.2 code, which discards the exception that 0.7.3 propagates. Delete that function’s cache
files, or save its source file again so that numba sees a newer modification time; the configurations page says
where numba writes the cache. For later upgrades, decorate such a function with
numbox_njit(), which numbox provides from 0.7.8. Its key includes numbox’s version, so the
function recompiles after every upgrade, as the cache_key page explains under
After you upgrade numbox.
numbox 0.7.4 assigns the .as_func value of a proxied function the numba type of a cres function, on numba
0.61 or later; before, it was a plain function value. From 0.7.4 on, a tuple that mixes .as_func with a plain
CompileResultWAP therefore can fail below numba 0.68.0, as the tuple rule
describes.
A downgrade to numbox 0.7.2 or earlier, with numba’s version unchanged, can leave a cache that numba cannot read. A call
of a cached function that received a cres function, or a node built from one, then raises
ModuleNotFoundError: No module named 'numbox.utils.derive_wap' while numba loads its cache. The message means that
the cache index names a numbox type that the older numbox lacks. numba reads the types in the index before it checks the
source file, so saving the file again does not clear the error. Delete the function’s cache files. An edit that moves
the function’s decorator to another line also works, because numba includes that line number in the cache file names.
If numba’s version changes as well, numba skips the old index without reading it, and the function recompiles. numbox
0.7.2 requires numba below 0.67, so downgrading numbox from an installation with numba 0.67 or later also changes
numba’s version.
Graph manager
While not a requirement, it is recommended that the Work instance’s name attribute matches the name of the variable to which that instance is assigned. Moreover, no built-in assertion of the uniqueness of Work names is provided; only the builder’s registries refuse a repeated name, as the builder overview describes. The users are free to implement their own graph managers that register the Work nodes and assert additional requirements on the names as needed. The core numbox library takes no position on whether such an overhead is universally beneficial (and worth the performance tradeoff).
One option for building a graph manager is a constructor such as the following:
from numba import njit
from numba.core.errors import NumbaError
from numbox.core.configurations import jit_options
from numbox.core.work.lowlevel_work_utils import ll_make_work
from numbox.core.work.node import NodeType
from numbox.utils.lowlevel import _cast
from work_registry import _get_global, registry_type
@njit(**jit_options)
def make_registered_work(name, data, sources=(), derive=None):
""" Optional graph manager. Consider using `make_work`
where performance is more critical and name clashes are
unlikely and/or inconsequential. """
registry_ = _get_global(registry_type, "_work_registry")
if name in registry_:
raise NumbaError(f"{name} is already registered")
work_ = ll_make_work(name, data, sources, derive)
registry_[name] = _cast(work_, NodeType)
return work_
The manager calls ll_make_work rather than make_work, as recommended above for large graphs: numba emits the
code of the intrinsic directly into the jitted function that calls it. Saved as work_registry.py, the registry
module that the example imports can be defined as follows:
1"""
2These functions included in this module::
3
4 get_or_make_global
5 _get_global
6 _set_global
7
8were mainly based on the
9
10 `CognitiveRuleEngine <https://github.com/DannyWeitekamp/Cognitive-Rule-Engine/blob/main/cre/utils.py>`_
11
12open-source project, distributed under
13
14MIT License
15
16Copyright (c) 2023 Daniel Weitekamp
17
18Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell # noqa: E501
19copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: # noqa: E501
20
21The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. # noqa: E501
22
23THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. # noqa: E501
24"""
25
26from llvmlite import ir
27from numba import njit
28from numba.extending import intrinsic
29from numba.core import cgutils
30from numba.core.types import DictType, unicode_type, void
31from numba.typed.typeddict import Dict
32
33from numbox.core.configurations import jit_options
34from numbox.core.work.node import NodeType
35
36
37def get_or_make_global(context, builder, fe_type, name):
38 mod = builder.module
39 try:
40 gv = mod.get_global(name)
41 except KeyError:
42 ll_ty = context.get_value_type(fe_type)
43 gv = ir.GlobalVariable(mod, ll_ty, name=name)
44 gv.linkage = "common"
45 gv.initializer = cgutils.get_null_value(gv.type.pointee)
46 return gv
47
48
49@intrinsic(prefer_literal=True)
50def _get_global(typingctx, type_ref, name_ty):
51 ty = type_ref.instance_type
52 name = name_ty.literal_value
53
54 def codegen(context, builder, signature, arguments):
55 gv = get_or_make_global(context, builder, ty, name)
56 v = builder.load(gv)
57 context.nrt.incref(builder, ty, v)
58 return v
59 sig = ty(type_ref, name_ty)
60 return sig, codegen
61
62
63@intrinsic(prefer_literal=True)
64def _set_global(typingctx, type_ref, name_ty, v_ty):
65 ty = type_ref.instance_type
66 name = name_ty.literal_value
67
68 def codegen(context, builder, signature, arguments):
69 _, __, v = arguments
70 gv = get_or_make_global(context, builder, ty, name)
71 builder.store(v, gv)
72 sig = void(type_ref, name_ty, v_ty)
73 return sig, codegen
74
75
76registry_type = DictType(unicode_type, NodeType)
77
78
79@njit(**jit_options)
80def set_global(registry_):
81 _set_global(registry_type, "_work_registry", registry_)
82
83
84registry = Dict.empty(unicode_type, NodeType)
85set_global(registry)
Implementation details
Internally, Work accommodates individual access to its sources
(the other Work nodes on the DAG that the given Work node depends on)
via a ‘Python-native compiler’ technique: before numba compiles an overload, numbox generates its Python source
for the given number of sources and runs it with Python’s compile and exec functions.
This technique is fully compatible with caching of
jitted functions and facilitates a natural Python counterpart to virtual functions (unsupported in numba).
Here it is extensively utilized in
numbox.core.work.work.ol_calculate() that overloads calculate method of
the Work class.
Invoking calculate method on the Work node triggers DFS calculation of its sources - all of the sources are automatically calculated before the node itself is calculated. Calculation of the Work node sets the value of its data attribute to the outcome of the calculation, which in turn can depend on the data values of its sources.
To avoid repeated calculation of the same node, Work has derived boolean flag that is set to True once the node has been calculated, preventing subsequent re-derivation. In particular, this ensures that DFS calculation of the node’s sources happens just once. numbox sets the flag only after the derive returns, so a derive whose exception propagates leaves it unset, and the node can be calculated again, as described under Exception handling.
The Work node of a jitted calculation graph: a value, its sources, and the function that computes the value.
Work is the Python proxy of the numba type that
numbox.core.work.lowlevel_work_utils defines, and make_work() creates a node from
Python or from jitted code. The overloads below implement the node’s methods in jitted code; calculate, load,
combine and make_inputs_vector run code generated for the node’s number of sources.
- class numbox.core.work.work.Work(*args, **kws)[source]
Bases:
NodeBaseA node of a jitted calculation graph: a value, the nodes it is computed from, and the function that computes it.
Nodes are created with
make_work(), withll_make_workin jitted code, or bymake_graph(). CallingWorkraisesNotImplementedErrorin Python and fails to compile in jitted code. The attributes below are the fields that jitted code reads; the properties of this class read most of them from Python.Attributes
- namestr
The node’s name.
- inputsUniTuple[NodeBaseType]
The sources, cast to
NodeBaseType.- dataAny
The node’s value. Its numba type is set when the node is created, and
calculatestores the derive’s result in it.- sourcesTuple[Work, …]
The nodes whose
datathe derive reads, in a tuple that can holdWorknodes of different types.- deriveFunctionType
The function that computes
datafrom thedataof the sources, orNonefor a node without one. Its signature is the type ofdataover the types of the sources’data.calculate()describes what happens when it raises.- derivedint8
1 once
datahas been calculated, otherwise 0.- nodeNodeType
The node’s
Noderepresentation, whichas_nodecreates on its first call; null until then.
The
namefield comes first in everyWorkpayload and has the same type in all of them, so aWorknode can be cast toNodeBaseType, the type ofnumbox.core.work.node_base.NodeBase.- all_end_nodes()[source]
Return the names of the nodes without sources that this node depends on, each once.
The call reads the graph through
as_node, which creates the node’sNoderepresentation if needed.
- all_inputs_names()[source]
Return the names of all the nodes this node depends on, each once, in depth-first order.
The call reads the graph through
as_node, which creates the node’sNoderepresentation if needed.
- as_node()[source]
Return the node’s
Noderepresentation, creating it on the first call.The first call also creates a representation for each source that lacks one, and these representations become the inputs of the new
Node. Later calls return the storedNode.
- calculate()[source]
Calculate the node’s
data, after calculating each source that is not yet calculated.The call returns at once for a node that is already calculated, and only marks a node without a derive as calculated. Otherwise
calculatecalls the derive on thedataof the sources, stores the result indataand setsderived. If the derive raises, the exception propagates with its type and message,datakeeps its value andderivedstays unset, so a later call runs the derive again. numba’s error path keeps the references it took. A node whose derive has failed therefore stays in memory, with everything it references, until the process ends. Another failure of the same node adds no further reference.In three cases the derive’s exception does not propagate. The first is a derive passed from Python into a jitted parameter declared as numba’s plain
FunctionType. The second is aCompileResultWAPbuilt with numba directly that reaches jitted code, wheremake_workcannot upgrade it. The third is a@cfunc. In each casecalculatestores a zero-filled result and setsderived. The.as_funcvalue of a@proxyfunction is not such aCompileResultWAP, and its exception propagates. The documentation ofnumbox.core.workdescribes these cases under “When the exception is lost”.
- combine(data)[source]
Copy the
dataof the named nodes of this node’s graph into the dictionarydata, under their names.datais a typed dictionary from node names toAnyvalues, such as the sheaf thatmake_sheaf_dict()returns. The walk covers this node and the nodes it depends on, depth first, and stops once it has found a node for every name. A name that no node of the graph has keeps its value.
- property data
The node’s value. An array is returned without a copy, so writing to it changes the node’s value.
- depends_on(obj_)[source]
Return whether this node depends on
obj_, a node name or aWorknode, directly or through others.
- property derive
The derive’s addresses, as a tuple of three integers.
The integers are the derive’s C entry point, the address of its Python object and numba’s entry point. The third is 0 when the derive has no numba entry point. In that case the derive’s exception does not propagate out of
calculate. Reading this property on a node without a derive raisesTypeError.
- property derived
1 once the node’s
datahas been calculated, otherwise 0.
- get_input(i)[source]
Return the source at index
ias itsNoderepresentation.The call creates the representations of the sources that lack one. A negative index, or one past the last source, raises
NumbaError.
- load(data)[source]
Set the nodes’
datafrom the dictionarydata, in this node’s graph, and return whether any was set.The graph is this node and the nodes it depends on.
datais a typed dictionary from node names toAnyvalues.loadreads each value as the node’s data type, with no conversion, so a value must have that type. It setsderivedback to 0 on each node it loads and on each node between that node and this one, so the nextcalculatecomputes them again. A loaded node that has a derive is computed again as well, and its loaded value is replaced.
- make_inputs_vector()[source]
Return the
Noderepresentations of the sources, as a typed list.The list holds
NodeBaseTypevalues. Ifas_nodehas created this node’s own representation, the list is that representation’s list of inputs. Otherwise it is a new list, and the representations of the sources that lack one are created.
- property sources
The nodes this node is computed from, as a tuple of
Worknodes.
- numbox.core.work.work.ensure_presence_of_source_getters_in_ns(num_sources_, ns_)[source]
Define
_get_source_{i}inns_for eachibelownum_sources_thatns_lacks._get_source_{i}is an intrinsic that returns elementiof a node’ssourcestuple.ns_is the module namespace or a copy of it that_codegen_methodextends, so the check readsns_itself.
- numbox.core.work.work.make_work(name, data, sources=(), derive=None)[source]
Create a
Worknode, from Python or from jitted code.datais the node’s initial value and sets its numba type.sourcesis a tuple ofWorknodes, andderivecomputes the node’s value from theirdata.deriveisNoneor a function value compiled for one signature, the type ofdataover the types of the sources’data, such as acres()function. Aderiveof another signature raisesValueError, and for a lazily compiled@njitfunction an assertion fails.Called from Python,
make_workupgrades aCompileResultWAPbuilt with numba directly to aDeriveWAPwithrewrap_derive(), so that an exception the derive raises propagates out ofcalculate. The node then holds the upgraded wrapper. Called from jitted code,make_workusesderiveunchanged. The value’s numba type is already fixed in jitted code, and the upgrade depends on the value’s Python class, which jitted code cannot access.make_work.py_funcis the Python function from which numba compiles the constructor thatmake_workcalls. Calling it from Python raisesNotImplementedError, because that function calls thell_make_workintrinsic. Unlikemake_work, that function does not upgradederive.
- numbox.core.work.work.ol_all_end_nodes(self_ty)[source]
Implement
Work.all_end_nodes()in jitted code, through the node’sNoderepresentation.
- numbox.core.work.work.ol_all_inputs_names(self_ty)[source]
Implement
Work.all_inputs_names()in jitted code, through the node’sNoderepresentation.
- numbox.core.work.work.ol_as_node(self_ty)[source]
Implement
Work.as_node()in jitted code, creating theNoderepresentation on the first call.
- numbox.core.work.work.ol_calculate(self_ty)[source]
Implement
Work.calculate()in jitted code: calculate the sources not yet calculated, then the node itself.A jitted caller can catch the derive’s exception only with a bare
except:or withexcept Exception:.
- numbox.core.work.work.ol_combine(work_ty, data_ty: ~numba.core.types.containers.DictType, harvested_ty=<class 'numba.core.types.misc.NoneType'>)[source]
Implement
Work.combine(data)in jitted code: store thedataof the named nodes inAnyvalues.combineresets the erased payloadpof each value to the node’sdata. The optionalharvesteddictionary records the names found so far, andcombinepasses it to thecombinecall of each source.
- numbox.core.work.work.ol_depends_on(self_ty, obj_ty)[source]
Implement
Work.depends_on(obj)in jitted code, for a name or aWorknode.For an argument of another type, an assertion fails when numba compiles the call.
- numbox.core.work.work.ol_get_input(self_ty, i_ty)[source]
Implement
Work.get_input(i)in jitted code: return the source at indexias aNode.A negative index, or one past the last source, raises
NumbaError.
- numbox.core.work.work.ol_get_inputs_names(self_ty)[source]
Implement
Work.get_inputs_names()in jitted code, returning the names as a typed list.
- numbox.core.work.work.ol_load(work_ty, data_ty: DictType)[source]
Implement
Work.load(data)in jitted code: set thedataof the named nodes fromAnyvalues.Each value’s erased payload
pmust hold the node’s data type, becauseloadreads it without a conversion.
numbox.core.work.work_utils
Overview
Convenience utilities for creating Work-graphs from Python scope.
The numbox.core.work.work.make_work() constructor accepts
a cres-compiled derive function as an argument, and cres requires
an explicitly provided signature of the derive function.
The return type of the derive function should match the type of the data attribute
of the corresponding Work instance, and its argument types
should match the data types of the Work instance’s sources.
Utilities defined in this module make it easier to ensure these requirements are met with a minimal amount of coding. Below, make_init_data() returns 0.0, the initial data of the node; given a shape, it returns an array of that shape filled with val:
import numpy
from numbox.core.work.work_utils import make_init_data, make_work_helper
pi = make_work_helper("pi", 3.1415)
def derive_circumference(diameter_, pi_):
return diameter_ * pi_
def run(diameter_):
diameter = make_work_helper("diameter", diameter_)
circumference = make_work_helper(
"circumference",
make_init_data(),
sources=(diameter, pi),
derive_py=derive_circumference,
jit_options={"cache": True}
)
circumference.calculate()
return circumference.data
if __name__ == "__main__":
assert numpy.isclose(run(1.41), 3.1415 * 1.41)
Helpers for building Work nodes from Python. make_work_helper() compiles a plain Python function as a
node’s derive, and make_init_data() makes a scalar or array initial value.
- numbox.core.work.work_utils.make_init_data(shape=(), val=0.0, ty=None)[source]
Return a node’s initial value:
valfor an emptyshape, else an array ofshapefilled withval.tyis the array’s dtype; by default NumPy infers it fromval.
- numbox.core.work.work_utils.make_work_helper(name, init_data, sources=(), derive_py=None, jit_options=None)[source]
Create a
Worknode from Python, compiling the plain Python functionderive_pyas its derive.The derive’s signature is the numba type of
init_dataover the numba types of the sources’ currentdata, as numba’stypeofgives them.derive_pyis compiled for that signature withcres(), which receivesjit_options; without them, the derive compiles without a cache. A node with neithersourcesnorderive_pyis an end node. Passingsourceswithoutderive_pyraisesTypeError. Ifderive_pyis not a plain function, an assertion fails.