The Array Context Abstraction¶
An array context is an abstraction that helps you dispatch between multiple
numpy-like \(n\)-dimensional arrays.
Freezing and thawing¶
One of the central concepts introduced by the array context formalism is
the notion of
thaw(). Each array handled by the array context
is either “thawed” or “frozen”. Unlike the real-world concept of freezing and
thawing, these operations leave the original array alone; instead, a semantically
separate array in the desired state is returned.
“Thawed” arrays are associated with an array context. They use that context to carry out operations (arithmetic, function calls).
“Frozen” arrays are static data. They are not associated with an array context, and no operations can be performed on them.
Freezing and thawing may be used to move arrays from one array context to another,
as long as both array contexts use identical in-memory data representation.
Otherwise, a common format must be agreed upon, for example using
Here are some rules of thumb to use when dealing with thawing and freezing:
Any array that is stored for a long time needs to be frozen. “Memoized” data (cf.
pytools.memoize()and friends) is a good example of long-lived data that should be frozen.
Within a function, if the user did not supply an array context, then any data returned to the user should be frozen.
Note that array contexts need not necessarily be passed as a separate argument. Passing thawed data as an argument to a function suffices to supply an array context. The array context can be extracted from a thawed argument using, e.g.,
What does this mean concretely?¶
Freezing and thawing are abstract names for concrete operations. It may be helpful to understand what these operations mean in the concrete case of various actual array contexts:
PyOpenCLArrayContextis associated with a
pyopencl.CommandQueue. In order to operate on array data, such a command queue is necessary; it is the main means of synchronization between the host program and the compute device. “Thawing” here means associating an array with a command queue, and “freezing” means ensuring that the array data is fully computed in memory and decoupling the array from the command queue. It is not valid to “mix” arrays associated with multiple queues within an operation: if it were allowed, a dependent operation might begin computing before an input is fully available. (Since bugs of this nature would be very difficult to find,
DOFArraywill not allow them.)
For the lazily-evaluating array context based on
pytato, “thawing” corresponds to the creation of a symbolic “handle” (specifically, a
pytato.array.DataWrapper) representing the array that can then be used in computation, and “freezing” corresponds to triggering (code generation and) evaluation of an array expression that has been built up by the user (using, e.g.
The interface of an array context¶
- class arraycontext.ArrayContext¶
An interface that allows software implementing a numerical algorithm (such as
Discretization) to create and interact with arrays without knowing their types.
New in version 2020.2.
- abstract empty(shape, dtype)¶
- abstract zeros(shape, dtype)¶
- abstract from_numpy(array: numpy.ndarray)¶
- abstract to_numpy(array)¶
- call_loopy(program, **kwargs)¶
loopyprogram program on the arguments kwargs.
dictof outputs from the program, each an array understood by the context.
- einsum(spec, *args, arg_names=None, tagged=())¶
Computes the result of Einstein summation following the convention in
spec – a string denoting the subscripts for summation as a comma-separated list of subscript labels. This follows the usual
numpy.einsum()convention. Note that the explicit indicator -> for the precise output form is required.
args – a sequence of array-like operands, whose order matches the subscript labels provided by spec.
arg_names – an optional iterable of string types denoting the names of the args. If None, default names will be generated.
tagged – an optional sequence of
pytools.tag.Tagobjects specifying the tags to be applied to the operation.
the output of the einsum
Provides access to a namespace that serves as a work-alike to
numpy. The actual level of functionality provided is up to the individual array context implementation, however the functions and objects available under this namespace must not behave differently from
As a baseline, special functions available through
exp) are accessible through this interface.
Callables accessible through this namespace vectorize over object arrays, including
- abstract freeze(array)¶
Return a version of the context-defined array array that is ‘frozen’, i.e. suitable for long-term storage and reuse. Frozen arrays do not support arithmetic. For example, in the context of
Array, this might mean stripping the array of an associated command queue, whereas in a lazily-evaluated context, it might mean that the array is evaluated and stored.
- abstract thaw(array)¶
Take a ‘frozen’ array and return a new array representing the data in array that is able to perform arithmetic and other operations, using the execution resources of this context. In the context of
Array, this might mean that the array is equipped with a command queue, whereas in a lazily-evaluated context, it might mean that the returned array is a symbol bound to the data in array.
The returned array may not be used with other contexts while thawed.
- abstract tag(tags: Union[Sequence[pytools.tag.Tag], pytools.tag.Tag], array)¶
If the array type used by the array context is capable of capturing metadata, return a version of array with the tags applied. array itself is not modified.
New in version 2021.2.
- abstract tag_axis(iaxis, tags: Union[Sequence[pytools.tag.Tag], pytools.tag.Tag], array)¶
If the array type used by the array context is capable of capturing metadata, return a version of array in which axis number iaxis has the tags applied. array itself is not modified.
New in version 2021.2.
- compile(f: Callable[[...], Any]) Callable[[...], Any] ¶
Compiles f for repeated use on this array context. f is expected to be a pure function performing an array computation.
Control flow statements (
while) that might take different paths depending on the data lead to undefined behavior and are illegal. Any data-dependent control flow must be expressed via array functions, such as
f may be called on placeholder data, to obtain a representation of the computation performed, or it may be called as part of the actual computation, on actual data. If f is called on placeholder data, it may be called only once (or a few times).
f – the function executing the computation.
a function with the same signature as f.
Implementations of the Array Context Abstraction¶
Array context based on
- class arraycontext.PyOpenCLArrayContext(queue: pyopencl.CommandQueue, allocator: Optional[pyopencl.tools.AllocatorInterface] = None, wait_event_queue_length: Optional[int] = None, force_device_scalars: bool = False)¶
A PyOpenCL memory allocator. Can also be None (default) or False to use the default allocator. Please note that running with the default allocator allocates and deallocates OpenCL buffers directly. If lots of arrays are created (e.g. as results of computation), the associated cost may become significant. Using e.g.
pyopencl.tools.MemoryPoolas the allocator can help avoid this cost.
pytato-based array context defers the evaluation of an array until its
frozen. The execution contexts for the evaluations are specific to an
ArrayContext type. For ex.
JIT-compile and execute the array expressions.
pytato-based array context are provided:
- class arraycontext.PytatoPyOpenCLArrayContext(queue, allocator=None)¶
pyopenclmemory allocator. Can also be None (default) or False to use the default allocator.
- __init__(queue, allocator=None)¶
- transform_dag(dag: pytato.DictOfNamedArrays) pytato.DictOfNamedArrays ¶
Returns a transformed version of dag. Sub-classes are supposed to override this method to implement context-specific transformations on dag (most likely to perform domain-specific optimizations). Every
pytatoDAG that is compiled to a
pyopenclkernel is passed through this routine.
dag – An instance of
A transformed version of dag.
Compiling a python callable¶
- class arraycontext.impl.pytato.compile.LazilyCompilingFunctionCaller(actx: arraycontext.impl.pytato.PytatoPyOpenCLArrayContext, f: Callable[[...], Any], program_cache: Dict[PMap[Tuple[Any, ...], AbstractInputDescriptor], CompiledFunction] = <factory>)¶
- class arraycontext.impl.pytato.compile.CompiledFunction(actx: arraycontext.impl.pytato.PytatoPyOpenCLArrayContext, pytato_program: pytato.target.BoundProgram, input_id_to_name_in_program: Mapping[Tuple[Any, ...], str], output_id_to_name_in_program: Mapping[Tuple[Any, ...], str], output_template: arraycontext.container.ArrayContainer)¶
A mapping from input id to the placholder name in
CompiledFunction.pytato_program. Input id is represented as the position of
f’s argument augmented with the leaf array’s key if the argument is an array container.
A mapping from output id to the name of
CompiledFunction.pytato_program. Output id is represented by the key of a leaf array in the array container