| Did you know ... | Search Documentation: |
| Pack array -- README.md |
Multidimensional arrays for SWI-Prolog, written as boxes of equations and compiled to OpenCL.
A program is a sequence of over/2 boxes. Each box runs its equations at every point of its axes, like a loop nest, and an equation writes one element of an array. From these boxes the compiler derives the kernels: which axes are parallel, what fuses, what lives in registers or local memory, and how the intermediates share one arena. It prints them as OpenCL C and runs them on any OpenCL device. A reference interpreter, eval/3, runs the same boxes in Prolog, exactly, to check the device against.
Shapes and subscripts are clpBNR constraints. So an extent may stay unknown: one compiled program then serves every size, and a subscript out of bounds is an error before anything runs.
You need:
opencl-headers and ocl-icd-devel on Fedora), and at least one OpenCL runtime (pocl, or a GPU vendor's);pack_install installs as a dependency.swipl pack install https://github.com/kwon-young/array.git
The pack manager builds the foreign libraries with CMake into `lib/<arch>/`, runs a smoke test, and installs.
The smoke test, test/test_smoke.pl, takes seconds: it fails where no OpenCL device is found, or where a small program does not run on one.
cmake -B build cmake --build build ctest --test-dir build --output-on-failure # the smoke test
To use the checkout from anywhere, link it as a pack: `swipl pack install . --link` (or pack_install('.', [link(true)])).
:- use_module(library(array)). % C = A B, for A of N x M and B of M x P. matmul(A, B, C, N, M, P) :- shape(A, [N, M]), shape(B, [M, P]), shape(C, [N, P]), over([I:N, J:P], [C[I, J] := 0]), over([I:N, J:P, K:M], [C[I, J] := C[I, J] + A[I, K] * B[K, J]]).
?- matmul(A, B, C, 2, 3, 2), Data = [A-[1, 2, 3, 4, 5, 6], B-[1, 0, 0, 1, 1, 1]], eval(C, Data, Ref), run(C, Data, Values, [device(pocl)]). Ref = Values, Values = [4.0, 5.0, 10.0, 11.0].
Data gives the elements of each input, row-major, and the results come back the same way.
opencl_device(Name, Device) enumerates the devices; run/4 takes device(Name), pocl by default.
kernels(C, Options, Kernels) and source(Kernels, Source) show the kernels and their OpenCL C.
I:N is an index I over an extent N, an integer or a clpBNR integer variable.over(Axes, Equations) runs its equations at each point of its axes, in lexicographic order.
An equation may itself be a box.
A name's elements before its first write are undefined: a box reads what a box before it wrote, and eval/3 raises on a read of an element no box wrote.where(Cond, Then, Else), and on ints // mod >> << /\ \/ xor.bool, int8 to int64, uint8 to uint64, float8_e4m3, float16, bfloat16, float32 or float64, the last where the device has doubles.
A name whose device is not known yet may have any of them; a format its device turns out to lack is an error naming the format and the device, where the program is compiled for it.
A bfloat16 is the high half of a float32, and a float8_e4m3 the float8_e4m3fn of torch and the F8_E4M3 of safetensors: it has no infinity, and a value past its greatest, 448, is not a number.
type(Name, Format) declares it; an input that declares none is an int32 or a float32, and a written name takes the least format that holds what it is computed from, by a promotion that is a lattice: a uint8 and an int8 are an int16, a float holds the ints it is computed with exactly, so a float16 and a uint8 are a float16 and a float32 and an unranged int32 a float64: declare the range of the int, elements/2, or cast it, to stay in 32 bits.
A literal and an index are weak: they take the type of what they are next to, and a name of them alone is an int32 or a float32.
A value written to a declared name must fit: a narrower one is widened, a wider one is an error, and cast(Value, Format) is the one way down, an int saturating.
A type is a minimum: a kernel computes in 32 bits whatever the narrower format, in 64 for a name that needs them, and a float is rounded to its format where it is stored.elements(Idx, Lo-Hi) bounds the values of an int input, permutation/1 declares its elements distinct, and power_of_two/1 declares an extent a power of two.device(Name, Device): host, which only holds data, or an OpenCL device by name, or a variable while unknown.
The names of a box share one device: over/2 unifies theirs, so that a device propagates through a program and may stay unknown up to its run, where device(D) places the names still unknown, for that run only.
copy(From, To, Device) is the one box across devices: To, a new name of From's shape and kind on Device, holds From's elements, so one program may span several devices, and data goes from host to a device and back by copies.value(Name, Buffer): a host buffer on host, a cl_mem on a device, in the format of the name, float32 for a float, int32 for an int and bool, a byte, for a bool that declare no other.
A realized name is an input whatever its boxes: a program reading it starts from its value, its boxes, kept, are not run again, and a handle of the program takes it as an argument like any input, its own value when a run gives none, never a buffer baked in.
It is never written again: over/2 refuses a box writing it.
value(Name, HostBuffer) realizes a name on host; realize(Names, Data, Options) runs the programs of Names and keeps their values on the devices that computed them, binding their devices and the extents of their shapes; unrealize/1 drops a value, the bounds of an int's elements staying as the name's declared range, which a value given again must keep.
A realized name of integer elements is bounded by its value, so that a gather through it needs no elements/2; a range declared is checked against the value.compile(Out, Options, Exe) compiles the program of Out once, for every size its extents allow, every extent needing an upper bound, and run(Exe, Args, Result) runs it on a realized name per input, in the order of signature(Exe, Slots, OutSlot), giving Result, a new realized name of the shape of that call.
A handle is a clause: its extents are bound by the shapes of the arguments for one call alone, nothing is attached to the program's names, calls are independent, and release/1 erases it.
A handle keeps its arena and its kernels on each device, by thread, from one call to the next, so that a call allocates nothing but its result once it has run.
run(Out, Data, Values, Options) is a handle compiled, run once on Data, Name-List pairs, and released; realize/3 the same, the elements kept where they were computed.
The toplevel shows the names of an answer by the flag array_answer:
short, the default: the names of the bindings, one line each, with their kind and shape;
a computed name with the last equation writing it, `A[Ts] += E for A[Ts] := A[Ts] + E`, or the copy that writes it, copy(From, A, Device), in which a name not shown is _;
a realized name with its elements, the first and last of a large one.full: the whole program, as goals that build it again: each name declared at its first mention, then the boxes, a name after the names it reads, a copy as copy/3 with its device.raw: the residual goals of the attributes, as copy_term/3 gives them.
?- weights(pocl, Net), classifier(Net, X, Y, D).
Net = _{fc1:_{bias:_B, weight:_A}, fc2:_{bias:_D, weight:_C}, fc3:_{bias:_F, weight:_E}},
D = pocl,
_G::integer(1, 1024),
_A: float32[256, 784] = [[-0.0002674, 0.01916, -0.02939, ..., 0.02194, 0.003733, 0.00206], ..., [-0.02199, 0.01826, 0.006697, ..., 0.009257, -0.02576, -0.01413]],
_B: float32[256] = [-0.01172, 0.01327, -0.002469, ..., 0.002638, -0.009203, 0.01348],
...
X: float[_G, 784],
Y: float[_G, 10] copy(_, Y, host).
The kinds are those label_kinds/1 resolves, and the indices are named I, J, K, ... by their place in their box.
print_array(Term, Options) prints the names of Term the same way, mode(short) or mode(full), with variable_names(Bindings).
library(array/api) writes a program as expressions, with the functions of the Python array API standard, which NumPy and PyTorch follow.
`Y @= Expr` declares a new name Y and hangs on it the boxes that compute Expr; nothing runs, and Y is a name like any other, for run/4, compile/3 or eval/3.
:- use_module(library(array/api)). softmax(X, Y) :- E @= exp(X - max(X, [axis(1), keepdims(true)])), Y @= E / sum(E, [axis(1), keepdims(true)]).
Operands are names and numbers; shapes broadcast as the standard says, an extent of exactly 1 stretching and every other pair of extents unified, so that a symbolic extent never stretches.
The options of a function are a list, [axis(1), keepdims(true)], the standard's keyword arguments.
It covers, so far, `+ - * / ** and exp sqrt log sin cos tan erf abs maximum minimum`, the comparisons `< =< =:= > >= =\= with where` and the logical functions, the reductions `sum max min mean`, @ for matmul with `matrix_transpose diagonal cholesky inv`, `zeros ones full eye arange asarray`, `concat stack permute_dims broadcast_to`, and indexing.
An index expression `A[I, ...]` follows the standard's rules: an integer, negative from the end, drops its axis; a slice Start:Stop:Step keeps it, with _ for a default bound and _ alone for a whole axis; new inserts an axis of extent 1 and ... stands for the axes left out; an int name gathers, several broadcasting together; take/3 and take_along_axis/3 gather along one axis.
Each index is checked against its extent before anything runs, where the standard leaves it unspecified, and a symbolic extent indexes like a known one, `A[1:_, -1]` on a shape [N, 4] having the shape [N-1].
Rows @= X[Idx, _], % the rows of X picked by the int name Idx Last @= X[..., -1], % the last column Even @= X[_:_:2, 1:3] * W[new, _], % every other row, columns 1 and 2, times a broadcast row
library(array/grad) differentiates a program as source: the derivative is new boxes over new names, a program like any other, compiled and run with the one it derives from, in one plan.
There is no tape and no graph at run time.
:- use_module(library(array/grad)). grad(Loss, [W1, B1], [G1, Gb1]) % reverse mode from a rank-0 loss vjp(Outs, Wrt, Bars, Grads) % reverse mode, a cotangent per output jvp(Outs, Ins, ND, Tangents, OutTangents) % forward mode, ND directions at once jacobian(Z, X, J, [batch(1)]) % J[b, i, j] = dZ[b, i]/dX[b, j], by forward mode
max or a min is split between the elements that reach it.domain_error(available, Name), unless the name has a rule: derivative(Y, Xs, [vjp(Goal), jvp(Goal)]) declares Y a function of Xs differentiated by goals that build its backward or its forward boxes, as differentiable_cholesky/3 of examples/linalg.pl does.stop_gradient(Name) makes a name a constant of every derivative.domain_error(depended_on, Name) when no output depends on it, domain_error(reachable_through(Blockers), Name) when every path is blocked by a realized name, a stop_gradient, or a name that is not a float; a name on a path whose partials are all zero keeps its gradient, zero.
The overlay has them as expressions: `G @= grad(L, W)`, `[G1, G2] @= grads(L, [W1, W2])`, `J @= jacobian(F, X)`, stop_gradient(E).
A training step, the loss and every new weight, is one handle of several outputs, compile_all(Outs, Options, Exe), whose run/3 gives a list of results: see examples/train.pl.
Without a handle in sight, run_all(Outs, Data, Results, Options) runs the same program once on data, compiling at the first run and calling after, its results realized names given back as the data of the next.
| Module | |
|---|---|
library(array) | The user-facing predicates: the vocabulary, program/2, eval/3, kernels/3, source/2, compile/3, run/3, run/4, realize/3, device_options/2, opencl_device/2, print_array/2. |
library(array/answer) | Answers and print_array/2: names, boxes and programs printed for a reader. |
library(array/core) | The vocabulary, its checks, and the clpBNR hulls of subscripts. |
library(array/type) | The types: formats, their promotion lattice as joins of clpBNR integers, weak literals, the floors of a kind, rounding to a device's formats. No name, extent or device in it: test/type.plt checks every pair and triple of formats, and test/promotion.txt holds the table. |
library(array/compile) | The pipeline: program, fuse, schedule, print, and the layout of a device's names in one arena, decided once at the bound of the extents. |
library(array/handle) | A program compiled once as a handle, compile/3, a clause run on realized names, run/3, one call serving every size its extents allow; compile_all/3, a handle of several outputs; run/4 and realize/3, a handle run once on data. |
library(array/tune) | tune_device/1,2,3: the tile, panel, staged block and work-group of a device's matrix products, float32 and float64, measured on the device and kept under `~/.cache/array_tune` (library(array/tuned)), where device_options/2 takes them over the options its properties call for: what no OpenCL runtime reports, its registers, caches and double rate. Minutes per device; untune_device/1 forgets them, ARRAY_TUNING=0 leaves them out of a run. |
library(array/reference) | eval/3, the boxes compiled to a Prolog clause; with the flag eval_cache, results cached under `~/.cache/array_eval`. |
library(array/minimalloc) | The MiniMalloc static allocator, which lays out the intermediates in one arena. |
library(array/opencl) | A thin binding of the OpenCL host API (foreign, src/opencl.c); the binaries of built programs cached under `~/.cache/array_cl` for the Intel CPU runtime, which keeps none (ARRAY_CL_CACHE=0 turns it off, ARRAY_CL_CACHE_DIR moves it, cl_program_cache_clear/0 empties it). |
library(array/buffer) | Typed host buffers (foreign, src/buffer.c; its type conversions are generated by src/gen_type.pl). |
library(array/safetensors) | Trees of names realized on host, nested dicts and lists, written to and read from safetensors files, each in the format of its dtype: weights, copied to a device and realized there once; their declared ranges, permutations and bool kinds travel in the metadata. |
library(array/api) | The functional overlay: `Y @= Expr`, the functions of the array API standard building boxes. |
library(array/grad) | Derivatives as source: grad/3, vjp/4, jvp/5, jacobian/4, stop_gradient/1, and rules by derivative/3. |
`examples/` holds programs written with the library:
classifier.pl: an MLP classifier whose weights and inputs are read from safetensors files, written by classifier.py from a PyTorch model, the weights realized on a device once, the program compiled once as a handle with its batch size unknown, and run on each batch, the logits written back to a file;ekf.pl: one step of an extended Kalman filter, batched over tracks, the Jacobians of its model by forward mode;linalg.pl: matmul, dot, and Cholesky factorizations, plain, blocked and batched, and the backward of one as a rule;mnist.pl: a classifier of the MNIST digits trained by minibatch gradient descent, the digits on the device, a step a handle that gathers its batch, the accuracy another; mnist.py writes the digits as a safetensors file;nn.pl: softmax, a transformer MLP, layer norm, a ViT encoder block, scatters and an embedding backward pass;sort.pl: bitonic and LSD radix sorts of float keys with their payloads;train.pl: an MLP trained by gradient descent, the loss, its gradients and the new weights one handle of several outputs;pclp.pl: the API of pclp, a Gaussian belief over named keys filtered through a forward arithmetic program written as {X is E}, on a batch of states scored against a batch of detections, a discrete choice of the program a leading axis with a hypothesis per value: every assignment is the expression over the sigma points of every state, written with the overlay alone;epf.pl: the vocabulary of the EPF of DMOS over the beliefs of pclp, a grammar of terms written once and run under an engine: searched under the strategies of best_first.pl, replayed, or its noises learned on a parse by gradient descent. A term's program, built once by a tabled builder, scores every detection under every value of the choices of its cond, discrete/4 variables, at once on the device, on the belief of the node realized there; the candidates come back to the host, where the grammar backtracks over them as the original does; the fit makes of each kind of step a handle of its outputs and their vector-Jacobian products, the adjoint of the belief chained across the terms;omr.pl: the OMR grammar of pclp in that vocabulary, staff lines then notes, the pitch of a note a choice of its term, with the model of the original, its prior, detections and noises, and the drivers that search, replay and learn;tracking.pl: tracking by association under backtracking, the detections realized on the device once, the filter's state a name kept there, every step a small program run through the cache of handles;ukf.pl: one step of an unscented Kalman filter, batched over tracks and detections.
The data files of classifier.pl, detector.pl and mnist.pl are not in the repository.
On first use, each example downloads the files it needs from the GitHub release examples-data-1 (about 50 MB gzipped for all three) into array_examples under $XDG_CACHE_HOME or `~/.cache; examples/example_data.pl` checks each against its SHA-256.
The Python scripts beside them write the same files from PyTorch, and a file found beside the examples is used instead.swipl -g test_array -t halt test/test_array.pl swipl -g "test_array(compile_basics)" -t halt test/test_array.pl ARRAY_TEST=fast swipl -g test_array -t halt test/test_array.pl swipl -g test_smoke -t halt test/test_smoke.pl
Every test is a `.plt` file in `test/`, each a module of its own.
test/test_array.pl loads them all, putting the checkout's `prolog/ and lib/<arch>/` before any installed copy.
Tests that run kernels run on every OpenCL device found.
test/test_smoke.pl, what ctest and pack_install run, is a separate file of two tests: an OpenCL device is found, and a small program runs on each.
A fast suite, ARRAY_TEST=fast in the environment or set_prolog_flag(array_test, fast) before a run, leaves out the Intel CPU runtime, whose kernel builds take half the time of a full suite, as long as another CPU device is found.
The device loops enumerate test_device/2 of test/test_devices.pl; a test of several concrete sizes runs them all on one device and a few on the others, test_size/5.
`bench/` times the kernels against PyTorch:
bench.pl: the harness (bench_data/6 prints the best kernel time and the memory of the intermediates) and the runs of the examples, go/1, go_chol/1, go_vit/1, ...;bench_train.pl: one step of gradient descent on an MLP, against bench_train.py;bench_sort.pl, bench_ukf.pl, bench_alloc.pl, bench_minimalloc.pl, sweep.pl;swipl -g "go(nvidia)" -t halt bench.pl
The library is a research prototype; its interface changes. `archive/` holds earlier designs (a NumPy-like dict array with views, a kernel IR and C, OpenCL and Prolog runtimes), which no longer load.
GPL-3.0, see LICENSE.