:- module(compile_tests, []).

:- use_module(library(array)).
:- use_module(library(array/compile)).
:- use_module(library(array/opencl), [opencl_device/2, cl_device_info/3]).
:- use_module(test_devices, [test_device/2, test_size/5]).
:- use_module(library(array/buffer)).
:- use_module(library(clpBNR)).
:- op(20, yf, []).
:- use_module('../examples/nn', [vit_block/6]).
:- use_module(library(array/api), [(@=)/2, op(800, xfx, @=), op(400, yfx, @)]).

% The references are evaluated once for every program and data, then read from the disk:
% see reference.pl.
:- set_prolog_flag(eval_cache, true).

% The tests are several units, since plunit runs units concurrently: run_tests(all, [jobs(6)]).

% The kernels are checked against the reference on every device, with and without tiles.
near(Xs, Ys) :-
   maplist([X, Y]>>(abs(X - Y) < 1.0e-3 * (1 + abs(X))), Xs, Ys).

% residual_layer(+Delta, -X, -Stat, +X0, -X): X the stream X0 plus Delta, and Stat[N] the mean
% of each of its rows plus their variance.
residual_layer(Delta, X, Stat, X0, X) :-
   X @= X0 + Delta,
   Stat @= mean(X, [axis(-1)]) + var(X, [axis(-1)]).

names_with(X, Names) :-
   member(N, Names), N == X, !.

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]]).

cholesky(A, L, N) :-
   shape(A, [N, N]), shape(L, [N, N]), shape(C, [N]),
   over([I:N, J:N], [L[I, J] := where(J =< I, A[I, J], 0)]),
   over([K:N], [over([I:N], [C[I] := where(I =:= K, sqrt(L[K, K]), where(K < I, L[I, K] / sqrt(L[K, K]), 0))]),
                over([I:N], [L[I, K] := where(K =< I, C[I], L[I, K])]),
                over([I:N, J:N], [L[I, J] := where(K < J, where(J =< I, L[I, J] - C[I] * C[J], L[I, J]), L[I, J])])]).

batched_cholesky(A, L, M, N) :- batched_cholesky(A, L, _, M, N).
batched_cholesky(A, L, C, M, N) :-
   shape(A, [M, N, N]), shape(L, [M, N, N]), shape(C, [M, N]),
   over([B:M, I:N, J:N], [L[B, I, J] := where(J =< I, A[B, I, J], 0)]),
   over([B:M, K:N], [over([I:N], [C[B, I] := where(I =:= K, sqrt(L[B, K, K]), where(K < I, L[B, I, K] / sqrt(L[B, K, K]), 0))]),
                     over([I:N], [L[B, I, K] := where(K =< I, C[B, I], L[B, I, K])]),
                     over([I:N, J:N], [L[B, I, J] := where(K < J, where(J =< I, L[B, I, J] - C[B, I] * C[B, J], L[B, I, J]), L[B, I, J])])]).

% blocked_cholesky(+A, -L, +N, +NB): L L^T = A by panels of NB columns. Per panel: a sweep
% factors the diagonal block; the panel's columns are copied to P, from which a kernel per
% row solves the rows below the block against the block, L21 = A21 L11^-T; the finished panel
% is copied to P again, and the trailing matrix loses its outer product, a staged reduction
% over the panel's columns launched over the active block only.
blocked_cholesky(A, L, N, NB) :-
   Panels is N // NB,
   shape(A, [N, N]), shape(L, [N, N]), shape(C, [N]), shape(P, [N, NB]), shape(S, []),
   over([I:N, J:N], [L[I, J] := where(J =< I, A[I, J], 0)]),
   over([Kb:Panels], [
      over([K:NB], [over([I:N], [C[I] := where(I =:= Kb*NB + K, sqrt(L[Kb*NB + K, Kb*NB + K]),
                                         where(Kb*NB + K < I, where(I < Kb*NB + NB,
                                               L[I, Kb*NB + K] / sqrt(L[Kb*NB + K, Kb*NB + K]), 0), 0))]),
                    over([I:N], [L[I, Kb*NB + K] := where(Kb*NB + K =< I, where(I < Kb*NB + NB, C[I], L[I, Kb*NB + K]),
                                                           L[I, Kb*NB + K])]),
                    over([I:N, J:N], [L[I, J] := where(Kb*NB + K < J, where(J < Kb*NB + NB, where(J =< I, where(I < Kb*NB + NB,
                                                 L[I, J] - C[I] * C[J], L[I, J]), L[I, J]), L[I, J]), L[I, J])])]),
      over([I:N, Kk:NB], [P[I, Kk] := L[I, Kb*NB + Kk]]),
      over([I:N], [over([J:NB], [over([], [S := 0]),
                                 over([Kk:NB], [S := S + where(Kk < J, L[I, Kb*NB + Kk] * P[Kb*NB + J, Kk], 0)]),
                                 L[I, Kb*NB + J] := where(Kb*NB + NB =< I, (L[I, Kb*NB + J] - S) / P[Kb*NB + J, J],
                                                          L[I, Kb*NB + J])])]),
      over([I:N, Kk:NB], [P[I, Kk] := L[I, Kb*NB + Kk]]),
      over([I:N, J:N, Kk:NB], [L[I, J] := where(Kb*NB + NB =< J, where(J =< I, L[I, J] - P[I, Kk] * P[J, Kk], L[I, J]), L[I, J])])]).

% gelu(X) as x * sigmoid(1.702 x), with the ops the table has
gelu(X, X * (1 / (1 + exp(-1.702 * X)))).

:- begin_tests(compile_basics).

test(transpose, [timeout(30), true(V == [1.0, 4.0, 2.0, 5.0, 3.0, 6.0])]) :-
   shape(Y, [2, 3]),
   over([I:3, J:2], [T[I, J] := Y[J, I]]),
   run(T, [Y-[1, 2, 3, 4, 5, 6]], V, []).

test(matmul_matches_reference, [timeout(60), forall((test_device(D, _), member(Tile, [1, 4])))]) :-
   matmul(A, B, C, 8, 12, 8),
   numlist(1, 96, As), maplist([X, Y]>>(Y is X mod 7), As, Bs),
   eval(C, [A-As, B-Bs], Ref),
   run(C, [A-As, B-Bs], V, [device(D), tile(Tile)]),
   near(Ref, V).

test(matmul_schedule, [timeout(30)]) :-
   matmul(A, B, C, 8, 12, 8),
   kernels(C, [], [Acc]),
   kernel{par: [_:2, _:2], seq: [_:12, _:4, _:4], priv: [C-[_, _]], names: Names, pre: [_], post: [], temps: []} :< Acc,
   length(Names, 3), forall(member(N, Names), ( member(N1, [A, B, C]), N1 == N )).

test(cumsum_batch_is_parallel, [timeout(30), true(V == [1.0, 2.0, 4.0, 6.0, 9.0, 12.0])]) :-
   shape(X, [3, 2]),
   over([J:2], [C[0, J] := X[0, J]]),
   over([T:2, J:2], [C[T+1, J] := C[T, J] + X[T+1, J]]),
   kernels(C, [tile(1)], [_, Scan]),
   kernel{par: [J1:2], seq: [T1:2], priv: []} :< Scan,
   J1 == J, T1 == T,
   run(C, [X-[1, 2, 3, 4, 5, 6]], V, [tile(1)]).

test(fibonacci_is_sequential, [timeout(30), true(V == [1, 1, 2, 3, 5, 8, 13, 21])]) :-
   shape(F, [8]),
   over([], [F[0] := 1, F[1] := 1]),
   over([T:6], [F[T+2] := F[T] + F[T+1]]),
   kernels(F, [], [_, Rec]),
   kernel{par: [], seq: [_:6]} :< Rec,
   run(F, [], V, []).

test(source_is_printed, [timeout(30)]) :-
   matmul(A, B, C, 8, 12, 8),
   kernels(C, [], Ks), source(Ks, Src),
   once(sub_string(Src, _, _, _, "__kernel void k0(")),
   once(sub_string(Src, _, _, _, "get_global_id(0)")),
   once(sub_string(Src, _, _, _, "float r_")),
   shape(A, _), shape(B, _).

% Three products alike, of the same shapes, are three kernels of one entry: one source, which
% the three launches call, each with its own buffers; a product of other shapes has its own.
test(kernels_alike_share_a_source, [timeout(60), forall(test_device(D, _))]) :-
   matmul(A, B, C, 8, 8, 8), matmul(C, B, E, 8, 8, 8), matmul(E, B, F, 8, 8, 8), matmul(F, G, H, 8, 8, 4),
   kernels(H, [], Plan), compile:flat_plan(Plan, Ks),
   maplist([K, I, En]>>( get_dict(id, K, I), get_dict(entry, K, En) ), Ks, Ids, Entries),
   assertion(Ids == [0, 1, 2, 3]),
   assertion(Entries == [0, 0, 0, 3]),
   source(Ks, Src),
   aggregate_all(count, sub_string(Src, _, _, _, "__kernel"), 2),
   once(sub_string(Src, _, _, _, "__kernel void k0(")), once(sub_string(Src, _, _, _, "__kernel void k3(")),
   numlist(1, 64, As), maplist([X, Y]>>(Y is (X mod 7) / 8), As, Bs), numlist(1, 32, Gs),
   Data = [A-As, B-Bs, G-Gs],
   eval(H, Data, Ref),
   run(H, Data, V, [device(D)]),
   near(Ref, V).

:- end_tests(compile_basics).

:- begin_tests(compile_groups).

test(softmax_is_one_kernel_of_one_group, [timeout(30), forall(test_device(D, _))]) :-
   shape(X, [4]),
   over([], [M := -1.0e30]),
   over([K:4], [M := max(M, X[K])]),
   over([I:4], [E[I] := exp(X[I] - M)]),
   over([], [S := 0]),
   over([K:4], [S := S + E[K]]),
   over([I:4], [Y[I] := E[I] / S]),
   kernels(Y, [], [K1]),
   kernel{kind: groups, rows: [], phases: [serial(_), reduce(_, [red(M1, [], max, _)]), serial(_),
                                           reduce(_, [red(S1, [], +, _)]), spread(_, _, _)], names: Ns} :< K1,
   M1 == M, S1 == S, \+ ( member(N, Ns), N == E ),
   Xs = [1, 2, 3, 4],
   eval(Y, [X-Xs], Ref), run(Y, [X-Xs], V, [device(D)]),
   near(Ref, V), sum_list(V, Sum), abs(Sum - 1) < 1.0e-5.

test(batched_softmax_aligns_the_rows, [timeout(30), forall(test_device(D, _))]) :-
   shape(X, [3, 5]),
   over([R:3], [M[R] := -1.0e30]),
   over([R:3, K:5], [M[R] := max(M[R], X[R, K])]),
   over([R:3], [S[R] := 0]),
   over([R:3, K:5], [S[R] := S[R] + exp(X[R, K] - M[R])]),
   over([R:3, I:5], [Y[R, I] := exp(X[R, I] - M[R]) / S[R]]),
   kernels(Y, [], [K1]),
   kernel{kind: groups, rows: [R1:3], phases: Phases} :< K1,
   length(Phases, 5), R1 == R,
   numlist(1, 15, Xs0), maplist([A, B]>>(B is (A * 7) mod 11), Xs0, Xs),
   eval(Y, [X-Xs], Ref), run(Y, [X-Xs], V, [device(D), local(8)]),
   near(Ref, V).

test(dot_product_reduces_in_groups, [timeout(30), forall(test_device(D, _))]) :-
   shape(A, [1000]), shape(B, [1000]),
   over([], [S := 0]),
   over([K:1000], [S := S + A[K] * B[K]]),
   kernels(S, [local(128)], [K1, K2]),
   kernel{kind: groups, rows: [_:5], phases: [serial(_), reduce(_:200, _)]} :< K1,
   kernel{kind: groups, rows: [], phases: [serial(_), reduce(_:5, _)]} :< K2,
   numlist(1, 1000, As), maplist([X, Y]>>(Y is X mod 3), As, Bs),
   eval(S, [A-As, B-Bs], Ref), run(S, [A-As, B-Bs], V, [device(D), local(128)]),
   near(Ref, V).

test(small_output_reduction_goes_to_groups_large_to_items, [timeout(30)]) :-
   matmul(_, _, C, 8, 12, 8), kernels(C, [], Ks), maplist([K]>>get_dict(kind, K, items), Ks),
   matmul(A2, B2, C2, 4, 12, 8), kernels(C2, [], [K2]), get_dict(kind, K2, groups), shape(A2, _), shape(B2, _),
   kernels(C2, [items(16)], K2s), maplist([K]>>get_dict(kind, K, items), K2s).

:- end_tests(compile_groups).

:- begin_tests(compile_staging).

test(matmul_staged_in_local_memory_and_vectorised, [timeout(60), forall(test_device(D, _))]) :-
   matmul(A, B, C, 64, 96, 64),
   kernels(C, [], Ks), source(Ks, Src),
   once(sub_string(Src, _, _, _, "__local float s0_[")),
   once(sub_string(Src, _, _, _, "__local float *s0 = (__local float *)(((uintptr_t)s0_ + 31) & ~(uintptr_t)31);")),
   once(sub_string(Src, _, _, _, "barrier(CLK_LOCAL_MEM_FENCE)")),
   once(sub_string(Src, _, _, _, "float4 *")),
   once(sub_string(Src, _, _, _, "#pragma unroll")),
   last(Ks, Acc), kernel{stage: stage(8, 8, Tiles)} :< Acc, length(Tiles, 2),
   numlist(1, 6144, As), maplist([X, Y]>>(Y is (X * 3) mod 7 - 3), As, Bs0), length(Bs, 6144), append(Bs, _, Bs0),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D)]),
   near(Ref, V).

test(long_reduction_is_split_over_groups, [timeout(60), forall(test_device(D, _))]) :-
   shape(A, [65536]), shape(B, [65536]), shape(S, []),
   over([], [S := 0]),
   over([K:65536], [S := S + A[K] * B[K]]),
   kernels(S, [local(256)], [Partial, Combine]),
   kernel{kind: groups, rows: [_:C], phases: [serial(_), reduce(_:Chunk, _)]} :< Partial,
   kernel{kind: groups, rows: [], phases: [serial(_), reduce(_:C, _)]} :< Combine,
   C * Chunk =:= 65536, C < 64, Chunk >= 256,
   numlist(1, 65536, As), maplist([X, Y]>>(Y is X mod 5 - 2), As, Bs),
   eval(S, [A-As, B-Bs], Ref), run(S, [A-As, B-Bs], V, [device(D), local(256)]),
   near(Ref, V).

% A reduction longer than a block of K, packed on a CPU in several blocks, with the
% initialisation and the epilogue the shorter ones fuse: the sum is that of every block.
test(matmul_of_several_blocks_of_k, [timeout(120), forall(test_device(D, _))]) :-
   matmul(A, B, C, 100, 784, 128),
   shape(Y, [100, 128]),
   over([I:100, J:128], [Y[I, J] := max(C[I, J], 0)]),
   numlist(1, 78400, As0), maplist([X, V]>>(V is sin(X*0.37)), As0, As),
   numlist(1, 100352, Bs0), maplist([X, V]>>(V is sin(X*0.011)), Bs0, Bs),
   eval(Y, [A-As, B-Bs], Ref), run(Y, [A-As, B-Bs], Vals, [device(D)]),
   near(Ref, Vals).

% The sum of a matrix: a partial per row, a work item each, then the reduction of the
% partials, never one work item looping over every element.
test(reduction_over_two_axes_is_peeled, [timeout(60), forall(test_device(D, _))]) :-
   shape(A, [256, 96]), shape(S, []),
   over([], [S := 0]),
   over([I:256, K:96], [S := S + A[I, K] * A[I, K]]),
   kernels(S, [], Ks),
   Ks = [Rows | _],
   get_dict(par, Rows, Par), Par \== [],
   forall(member(K1, Ks), \+ kernel{kind: items, par: [], seq: [_, _]} :< K1),
   numlist(1, 24576, As0), maplist([X, Y]>>(Y is X mod 7 - 3), As0, As),
   eval(S, [A-As], Ref), run(S, [A-As], V, [device(D)]),
   near(Ref, V).

test(batched_long_reduction_splits_too, [timeout(60)]) :-
   shape(X, [4, 8192]), shape(M, [4]),
   over([R:4], [M[R] := -1.0e30]),
   over([R:4, K:8192], [M[R] := max(M[R], X[R, K])]),
   kernels(M, [], [Partial, Combine]),
   kernel{kind: groups, rows: [_:C, _:4]} :< Partial,
   kernel{kind: groups, rows: [_:4], phases: [serial(_), reduce(_:C, [red(_, _, max, _)])]} :< Combine,
   C * 4 < 64,
   numlist(1, 32768, Xs0), maplist([A, B]>>(B is (A * 37) mod 1009), Xs0, Xs),
   eval(M, [X-Xs], Ref), run(M, [X-Xs], V, []),
   near(Ref, V).

test(device_options_fit_the_device_and_run, [timeout(120), forall(test_device(D, Dev))]) :-
   device_options(Dev, Opts),
   option(vector(W), Opts), option(group(G), Opts), option(stage(TK), Opts), option(local(L), Opts),
   option(tile([TI, TJ]), Opts), TJ =:= 2*W, G*G =< 1024, L /\ (L-1) =:= 0,
   cl_device_info(Dev, local_mem_size, Bytes), (G*TI + G*TJ)*TK*4 =< Bytes,
   matmul(A, B, C, 64, 96, 64),
   numlist(1, 6144, As), maplist([X, Y]>>(Y is (X * 3) mod 7 - 3), As, Bs0), length(Bs, 6144), append(Bs, _, Bs0),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D)]),
   near(Ref, V).

test(cpu_matmul_is_packed_per_thread, [timeout(120), forall((test_device(D, Dev), cl_device_info(Dev, type, cpu)))]) :-
   device_options(Dev, Opts),
   matmul(A, B, C, 128, 256, 128),
   kernels(C, Opts, Ks), last(Ks, Acc),
   kernel{stage: pack(Threads, KC, MCT, NS, _, Tiles)} :< Acc,
   length(Tiles, 2), Threads >= 1, KC >= 2, MCT >= 1, NS >= 1,
   source(Ks, Src), once(sub_string(Src, _, _, _, "int t = get_global_id(0)")), \+ sub_string(Src, _, _, _, "barrier"),
   numlist(1, 32768, As), maplist([X, Y]>>(Y is (X * 5) mod 11 - 5), As, Bs),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D)]),
   near(Ref, V).

% A linear layer reads its weight across the rows, W[J, K] along J: strided in the buffer, but
% contiguous in the panel it is packed in, so the micro-kernel is vectors, an fma of a vector
% of the panel into a vector of the register tile, and none of single elements: a CPU runtime
% that vectorises across work items only, intel's, leaves those scalar.
test(packed_linear_of_a_transposed_weight_is_vectors, [timeout(120), forall(test_device(D, _))]) :-
   Packed = [threads(8), vector(8), tile([4, 16]), panel(256, 128), major(k_last)],
   shape(X, [100, 300]), shape(Wt, [50, 300]), shape(Y, [100, 50]),
   over([I:100, J:50], [Y[I, J] := 0]),
   over([I:100, J:50, K:300], [Y[I, J] := Y[I, J] + X[I, K] * Wt[J, K]]),
   kernels(Y, Packed, Ks), last(Ks, Acc), kernel{stage: pack(_, _, _, _, _, [_, _])} :< Acc,
   source(Ks, Src),
   once(sub_string(Src, _, _, _, "(float8)(fma(")),
   once(sub_string(Src, _, _, _, "(*(__local float8 *)&s1[")),
   \+ sub_string(Src, _, _, _, "] = fma("),
   numlist(1, 30000, Xs0), maplist([N, V]>>(V is sin(N*0.37)), Xs0, Xs),
   numlist(1, 15000, Ws0), maplist([N, V]>>(V is sin(N*0.011)), Ws0, Ws),
   eval(Y, [X-Xs, Wt-Ws], Ref), run(Y, [X-Xs, Wt-Ws], Vals, [device(D)]),
   near(Ref, Vals).

% A product of int matrices: a tile in local memory is floats, so the kernel is not staged,
% on a GPU nor packed on a CPU, and its sums are exact.
test(int_matmul_is_not_staged, [timeout(120), forall(test_device(D, Dev))]) :-
   device_options(Dev, Opts),
   matmul(A, B, C, 128, 256, 128), kind(A, int), kind(B, int),
   kernels(C, Opts, Ks), last(Ks, Acc), kernel{stage: none} :< Acc,
   numlist(1, 32768, As), maplist([X, Y]>>(Y is (X * 5) mod 11 - 5), As, Bs),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D)]),
   V == Ref.

% A product of doubles takes the fast paths of floats with the sizes of doubles, see
% device_options/2: packed per thread on a CPU, and staged in local memory on a GPU when
% double_stage(TK) asks for it; its tiles doubles, its vectors those of doubles, and its
% sums those of doubles.
test(float64_matmul_is_staged_or_packed, [timeout(120), forall(test_device(D, Dev))]) :-
   device_options(Dev, Opts0), merge_options([double_stage(16)], Opts0, Opts),
   matmul(A, B, C, 128, 256, 128), maplist([N]>>type(N, float64), [A, B, C]),
   kernels(C, Opts, Ks), last(Ks, Acc),
   kernel{stage: Stage, vector: W} :< Acc, option(double_vector(W), Opts),
   fast_stage(Stage, Tiles), length(Tiles, 2),
   source(Ks, Src), once(sub_string(Src, _, _, _, "__local double ")),
   numlist(1, 32768, Ns), maplist([X, Y]>>(Y is sin(X*0.37)), Ns, As), maplist([X, Y]>>(Y is sin(X*0.011)), Ns, Bs),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D), double_stage(16)]),
   near64(Ref, V).

fast_stage(stage(_, _, Tiles), Ts) => Ts = Tiles.
fast_stage(pack(_, _, _, _, _, Tiles), Ts) => Ts = Tiles.

% near64(+Xs, +Ys): equal to the precision of a sum of doubles.
near64(Xs, Ys) :-
   maplist([X, Y]>>(abs(X - Y) < 1.0e-12 * (1 + abs(X))), Xs, Ys).

% A product of doubles takes by default the path of floats, sized for doubles: packed on a
% device of packing threads, a CPU, staged in local memory elsewhere; tune_device/2 may find
% a device that runs it faster plain.
test(float64_matmul_default_stage, [timeout(60), forall(test_device(_, Dev))]) :-
   device_options(Dev, Opts), option(threads(Threads), Opts),
   matmul(A, B, C, 128, 256, 128), maplist([N]>>type(N, float64), [A, B, C]),
   kernels(C, Opts, Ks), last(Ks, Acc), get_dict(stage, Acc, Stage),
   default_stage(Threads, Stage).

default_stage(0, Stage) => Stage = stage(_, _, _).
default_stage(_, Stage) => Stage = pack(_, _, _, _, _, _).

% A product of a float32 and a float64 is computed in double: neither its float tiles nor its
% double ones are those of its kernel, so it is not staged, and its sums are those of doubles.
test(mixed_float_matmul_is_not_staged, [timeout(120), forall(test_device(D, Dev))]) :-
   device_options(Dev, Opts0), merge_options([double_stage(16)], Opts0, Opts),
   matmul(A, B, C, 64, 96, 64), type(A, float32), type(B, float64), type(C, float64),
   kernels(C, Opts, Ks), last(Ks, Acc), kernel{stage: none} :< Acc,
   numlist(1, 6144, Ns), maplist([X, Y]>>(Y is (X mod 13) / 8), Ns, As), maplist([X, Y]>>(Y is sin(X*0.011)), Ns, Bs),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D), double_stage(16)]),
   near64(Ref, V).

% A linear layer of doubles whose sizes no tile divides, with its bias and relu fused: one
% kernel, shifted strips, a reduced axis of two blocks keeping their sums on a CPU, staged
% by blocks of 15 on a GPU.
test(float64_linear_of_odd_sizes, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [100, 300]), shape(Wt, [300, 50]), shape(Bias, [50]), shape(Y, [100, 50]),
   maplist([N]>>type(N, float64), [X, Wt, Bias, Y]),
   over([I:100, J:50], [Y[I, J] := Bias[J]]),
   over([I:100, J:50, K:300], [Y[I, J] := Y[I, J] + X[I, K] * Wt[K, J]]),
   shape(Z, [100, 50]), type(Z, float64),
   over([I:100, J:50], [Z[I, J] := max(Y[I, J], 0)]),
   numlist(1, 30000, Xs0), maplist([N, V]>>(V is sin(N*0.37)), Xs0, Xs),
   numlist(1, 15000, Ws0), maplist([N, V]>>(V is sin(N*0.011)), Ws0, Ws),
   numlist(1, 50, Bs0), maplist([N, V]>>(V is cos(N)), Bs0, Bs),
   Data = [X-Xs, Wt-Ws, Bias-Bs],
   eval(Z, Data, Ref), run(Z, Data, Vals, [device(D), double_stage(16)]),
   near64(Ref, Vals).

% The attention matmuls of a transformer: the scores of each head, a batch axis before the
% strips, and the heads' products with the values, whose target mixes the head and its slice.
test(attention_matmuls_stage_per_head, [timeout(90), forall(test_device(D, _))]) :-
   H = 2, S = 16, Dh = 16, DM is H*Dh, Opts = [tile([8, 8]), group(2), stage(8)],
   shape(Q, [S, DM]), shape(Kt, [S, DM]), shape(Sc, [H, S, S]), shape(P, [H, S, S]), shape(V, [S, DM]), shape(O, [S, DM]),
   over([Hh:H, I:S, J:S], [Sc[Hh, I, J] := 0]),
   over([Hh:H, I:S, J:S, K:Dh], [Sc[Hh, I, J] := Sc[Hh, I, J] + Q[I, Hh*Dh + K] * Kt[J, Hh*Dh + K]]),
   over([Hh:H, I:S, K2:Dh], [O[I, Hh*Dh + K2] := 0]),
   over([Hh:H, I:S, K2:Dh, J:S], [O[I, Hh*Dh + K2] := O[I, Hh*Dh + K2] + P[Hh, I, J] * V[J, Hh*Dh + K2]]),
   kernels(Sc, Opts, [Ka]), kernel{par: [_:2, _:2, _:2], stage: stage(2, 8, [_, _]), pre: [_]} :< Ka,
   kernels(O, Opts, [Kb]), kernel{par: [_:2, _:2, _:2], stage: stage(2, 8, [_, _]), pre: [_]} :< Kb,
   numlist(1, 512, Ns), maplist([X, Y]>>(Y is (X * 7) mod 11 / 11 - 0.5), Ns, Qs), maplist([X, Y]>>(Y is (X * 5) mod 13 / 13 - 0.5), Ns, Ks),
   eval(Sc, [Q-Qs, Kt-Ks], Ref1), run(Sc, [Q-Qs, Kt-Ks], V1, [device(D) | Opts]), near(Ref1, V1),
   eval(O, [P-Qs, V-Ks], Ref2), run(O, [P-Qs, V-Ks], V2, [device(D) | Opts]), near(Ref2, V2).

:- end_tests(compile_staging).

:- begin_tests(compile_cholesky).

test(cholesky_is_one_sweep_kernel, [timeout(300), forall(test_device(D, _))]) :-
   cholesky(A, L, 64),
   kernels(L, [], [_, Sweep]),
   kernel{kind: groups, rows: [], phases: [loop(K1, 64, [spread(_, _, _), spread(_, _, _), spread([_, _], [_, _], _)])]} :< Sweep,
   K1 == K1,
   findall(V, ( between(0, 63, I), between(0, 63, J), V is min(I, J) + 1 ), As),
   eval(L, [A-As], Ref), run(L, [A-As], Vals, [device(D)]),
   near(Ref, Vals),
   nth0(0, Vals, V00), abs(V00 - 1) < 1.0e-4, nth0(4095, Vals, V), abs(V - 1) < 1.0e-3.

test(blocked_cholesky_stages_the_trailing_update, [timeout(300), forall(test_device(D, _))]) :-
   blocked_cholesky(A, L, 128, 32),
   kernels(L, [], [_, loop(_, 4, [Panel, Copy, Solve, Copy2, Update])]),
   kernel{kind: groups, phases: [loop(_, 32, _)]} :< Panel,
   kernel{kind: items, stage: none} :< Copy, kernel{kind: items, stage: none} :< Copy2,
   kernel{kind: items, par: [_:128], local: [S1], tiles: []} :< Solve, var(S1),
   kernel{kind: items, stage: stage(_, _, _), ranges: [_, _]} :< Update,
   findall(V, ( between(0, 127, I), between(0, 127, J), V is min(I, J) + 1 ), As),
   eval(L, [A-As], Ref), run(L, [A-As], Vals, [device(D)]),
   near(Ref, Vals).

% The row solve's axis is parallel but for its accumulator, a local: a kernel of work items
% whatever the items threshold against the panel width, never a launch per row.
test(row_solve_is_never_a_host_loop, [timeout(60), forall(member(Min, [8, 40, 64, 128]))]) :-
   blocked_cholesky(A, L, 256, 64),
   kernels(L, [items(Min)], [_, loop(_, 4, [_, _, Solve, _, _])]),
   kernel{kind: items, par: [_:256], local: [S]} :< Solve, var(S),
   shape(A, _).

test(batched_cholesky_is_a_group_per_matrix, [timeout(300), forall(test_device(D, _))]) :-
   batched_cholesky(A, L, C, 4, 32),
   kernels(L, [], [_, Sweep]),
   kernel{kind: groups, rows: [B1:4], phases: [loop(_, 32, _)], shared: Shared} :< Sweep, var(B1),
   memberchk(L1-1-1024, Shared), L1 == L, memberchk(C1-1-32, Shared), C1 == C,
   source([Sweep], Src), once(sub_string(Src, _, _, _, "__local float s_")), \+ sub_string(Src, _, _, _, "GLOBAL_MEM_FENCE"),
   findall(V, ( between(0, 3, _), between(0, 31, I), between(0, 31, J), V is min(I, J) + 1 ), As),
   eval(L, [A-As], Ref), run(L, [A-As], Vals, [device(D)]),
   near(Ref, Vals).

% A step of a 4x4 factor has 4 parallel points, under the lanes a group occupies: each matrix
% is one work item, with no barrier; with lanes(1) it is a group, as before.
test(tiny_batched_cholesky_is_an_item_per_matrix, [timeout(300), forall(test_device(D, _))]) :-
   batched_cholesky(A, L, C, 64, 4),
   kernels(L, [], [_, Sweep]),
   kernel{kind: groups, rows: [_:64], phases: [loop(_, 4, _)], item: true, local: 1, shared: []} :< Sweep,
   source([Sweep], Src), once(sub_string(Src, _, _, _, "get_global_id(0)")), \+ sub_string(Src, _, _, _, "barrier"),
   kernels(L, [lanes(1)], [_, Group]), \+ get_dict(item, Group, _),
   findall(V, ( between(0, 63, _), between(0, 3, I), between(0, 3, J), V is min(I, J) + 1 ), As),
   eval(L, [A-As], Ref), run(L, [A-As], Vals, [device(D)]),
   near(Ref, Vals), shape(C, _).

% A chain of two reductions of length 2 cannot fill a warp: it goes to kernels of work items,
% a group only when the lanes are 1.
test(short_reductions_stay_items, [timeout(300), forall(test_device(D, _))]) :-
   shape(X, [64, 2, 2]), shape(Y, [64, 2]), shape(G, [64, 2]), shape(H, [64, 2]),
   over([B:64, I:2], [G[B, I] := 0]),
   over([B:64, I:2, K:2], [G[B, I] := G[B, I] + X[B, I, K] * Y[B, K]]),
   over([B:64, I:2], [H[B, I] := 0]),
   over([B:64, I:2, K:2], [H[B, I] := H[B, I] + G[B, I] * Y[B, K]]),
   kernels(H, [], Items), forall(member(K1, Items), get_dict(kind, K1, items)),
   kernels(H, [lanes(1)], [Group]), kernel{kind: groups, local: 1} :< Group,
   numlist(1, 256, Ns), maplist([N, V]>>(V is (N mod 5) - 2), Ns, Xs), length(Ys, 128), maplist([V]>>(V = 1), Ys),
   eval(H, [X-Xs, Y-Ys], Ref), run(H, [X-Xs, Y-Ys], Vals, [device(D)]), near(Ref, Vals),
   run(H, [X-Xs, Y-Ys], Vals1, [device(D), lanes(1)]), near(Ref, Vals1).

% A box reading what the chain wrote outside its own row ends the chain: the second product
% reads G at every K of its row, which other groups write. Grouped, it read them unfinished.
test(chain_reads_its_own_row_only, [timeout(300), forall(test_device(D, _))]) :-
   shape(X, [64, 2, 2]), shape(Y, [64, 2, 2]), shape(G, [64, 2, 2]), shape(H, [64, 2, 2]),
   over([B:64, I:2, J:2], [G[B, I, J] := 0]),
   over([B:64, I:2, J:2, K:2], [G[B, I, J] := G[B, I, J] + X[B, I, K] * Y[B, K, J]]),
   over([B:64, I:2, J:2], [H[B, I, J] := 0]),
   over([B:64, I:2, J:2, K:2], [H[B, I, J] := H[B, I, J] + G[B, I, K] * Y[B, K, J]]),
   kernels(H, [lanes(1)], Ks), length(Ks, 2), forall(member(K1, Ks), get_dict(kind, K1, items)),
   numlist(1, 256, Ns), maplist([N, V]>>(V is (N mod 5) - 2), Ns, Xs), maplist([N, V]>>(V is (N mod 3) - 1), Ns, Ys),
   eval(H, [X-Xs, Y-Ys], Ref), run(H, [X-Xs, Y-Ys], Vals, [device(D), lanes(1)]), near(Ref, Vals).

:- end_tests(compile_cholesky).

:- begin_tests(compile_scatter).

test(scatter_add_is_atomic, [timeout(120), forall(test_device(D, _))]) :-
   shape(Idx, [4096]), elements(Idx, 0-15), shape(W, [4096]), shape(H, [16]),
   over([I:16], [H[I] := 0]),
   over([K:4096], [H[Idx[K]] := H[Idx[K]] + W[K]]),
   kernels(H, [], [_, Scatter]),
   kernel{kind: items, par: [_:_], atomics: [H1-(+)]} :< Scatter, H1 == H,
   source([Scatter], Src), once(sub_string(Src, _, _, _, "atomic_add_float(")),
   numlist(1, 4096, Ks), maplist([X, Y]>>(Y is (X * 7) mod 16), Ks, Is), maplist([X, Y]>>(Y is X mod 5), Ks, Ws),
   eval(H, [Idx-Is, W-Ws], Ref), run(H, [Idx-Is, W-Ws], V, [device(D)]),
   near(Ref, V).

test(embedding_backward_scatters_rows, [timeout(120), forall(test_device(D, _))]) :-
   shape(Idx, [512]), elements(Idx, 0-63), shape(G, [512, 32]), shape(E, [64, 32]),
   over([I:64, J:32], [E[I, J] := 0]),
   over([K:512, J:32], [E[Idx[K], J] := E[Idx[K], J] + G[K, J]]),
   kernels(E, [], [_, Scatter]),
   kernel{kind: items, par: [_, _], atomics: [E1-(+)]} :< Scatter, E1 == E,
   numlist(1, 512, Ks), maplist([X, Y]>>(Y is (X * 13) mod 64), Ks, Is),
   numlist(1, 16384, Gs0), maplist([X, Y]>>(Y is X mod 7), Gs0, Gs),
   eval(E, [Idx-Is, G-Gs], Ref), run(E, [Idx-Is, G-Gs], V, [device(D)]),
   near(Ref, V).

% A reduction with too few outputs to fill the device keeps its long axis a loop: no subscript
% of the target mentions it, so atomic, every point would contend for the same place.
test(dense_reduction_keeps_its_axis_a_loop, [timeout(120), forall(test_device(D, _))]) :-
   Opts = [items(64), local(64), tile(4)],
   matmul(A, B, C, 4, 4096, 16),
   kernels(C, Opts, Ks),
   \+ ( member(K, Ks), get_dict(atomics, K, [_ | _]) ),
   numlist(1, 16384, As0), maplist([X, Y]>>(Y is X mod 7), As0, As),
   numlist(1, 65536, Bs0), maplist([X, Y]>>(Y is X mod 5), Bs0, Bs),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D) | Opts]),
   near(Ref, V).

% A scatter that also sums an inner axis: its sources run in parallel, each folds the inner
% axis in a register, then into the place atomically, since other sources fold into it too.
test(scatter_folds_inner_axis_then_atomically, [timeout(120)]) :-
   Opts = [items(64), local(64), tile(1)],
   shape(Idx, [512]), elements(Idx, 0-63), shape(G, [512, 32, 16]), shape(E, [64, 32]),
   over([I:64, J:32], [E[I, J] := 0]),
   over([K:512, J:32, L:16], [E[Idx[K], J] := E[Idx[K], J] + G[K, J, L]]),
   kernels(E, Opts, [_, Scatter]),
   kernel{kind: items, par: [_, _], atomics: [E1-(+)]} :< Scatter, E1 == E,
   source([Scatter], Src), once(sub_string(Src, _, _, _, "float a_")), once(sub_string(Src, _, _, _, "atomic_add_float(&")),
   numlist(1, 512, Ks), maplist([X, Y]>>(Y is (X * 13) mod 64), Ks, Is),
   numlist(1, 262144, Gs0), maplist([X, Y]>>(Y is X mod 7), Gs0, Gs),
   eval(E, [Idx-Is, G-Gs], Ref),
   forall(test_device(D, _),
          ( run(E, [Idx-Is, G-Gs], V, [device(D) | Opts]), near(Ref, V) )).

:- end_tests(compile_scatter).

:- begin_tests(compile_fusion).

test(matmul_with_epilogue_is_one_kernel, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [64, 96]), shape(W, [96, 64]), shape(B, [64]), shape(R, [64, 64]), shape(C, [64, 64]), shape(Y, [64, 64]),
   over([I:64, J:64], [C[I, J] := 0]),
   over([I:64, J:64, K:96], [C[I, J] := C[I, J] + X[I, K] * W[K, J]]),
   gelu(C[I2, J2] + B[J2], G),
   over([I2:64, J2:64], [Y[I2, J2] := G + R[I2, J2]]),
   kernels(Y, [], [K1]),
   kernel{kind: items, pre: [_], post: [_], temps: [C1]} :< K1, C1 == C,
   kernel{names: Names} :< K1, length(Names, 5),
   numlist(1, 6144, Xs0), maplist([A, V]>>(V is (A mod 13) / 13), Xs0, Xs), maplist([A, V]>>(V is ((A * 3) mod 7) / 7 - 0.5), Xs0, Ws),
   numlist(1, 64, Bs0), maplist([A, V]>>(V is A / 64), Bs0, Bs), numlist(1, 4096, Rs0), maplist([A, V]>>(V is (A mod 5) / 5), Rs0, Rs),
   eval(Y, [X-Xs, W-Ws, B-Bs, R-Rs], Ref), run(Y, [X-Xs, W-Ws, B-Bs, R-Rs], Vals, [device(D)]),
   near(Ref, Vals).

% An epilogue that adds into a name written before it reads that name's elements: the
% register tile is loaded at each tile, whichever device runs it, a CPU's thread visiting many.
test(epilogue_accumulating_into_a_written_name, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [64, 96]), shape(W, [96, 64]), shape(R, [64, 64]), shape(C, [64, 64]), shape(Y, [64, 64]),
   over([I0:64, J0:64], [Y[I0, J0] := R[I0, J0]]),
   over([I:64, J:64], [C[I, J] := 0]),
   over([I:64, J:64, K:96], [C[I, J] := C[I, J] + X[I, K] * W[K, J]]),
   over([I2:64, J2:64], [Y[I2, J2] := Y[I2, J2] + C[I2, J2] * 0.5]),
   numlist(1, 6144, Xs0), maplist([A, V]>>(V is (A mod 13) / 13), Xs0, Xs), maplist([A, V]>>(V is ((A * 3) mod 7) / 7 - 0.5), Xs0, Ws),
   numlist(1, 4096, Rs0), maplist([A, V]>>(V is (A mod 5) / 5 + 1), Rs0, Rs),
   eval(Y, [X-Xs, W-Ws, R-Rs], Ref), run(Y, [X-Xs, W-Ws, R-Rs], Vals, [device(D)]),
   near(Ref, Vals).

test(pure_names_stay_buffers_under_a_reduction, [timeout(60)]) :-
   shape(X, [64, 64]), shape(W, [64, 64]), shape(C, [64, 64]),
   over([I:64, J:64], [E[I, J] := exp(X[I, J])]),
   over([I:64, J:64], [C[I, J] := 0]),
   over([I:64, J:64, K:64], [C[I, J] := C[I, J] + E[I, K] * W[K, J]]),
   kernels(C, [], Ks), length(Ks, 2), last(Ks, Acc), kernel{stage: stage(_, _, _)} :< Acc.

test(recurrence_with_a_local_name, [timeout(30), forall(test_device(D, _))]) :-
   % x(t+1) = F x(t), F a rotation, P the loop-local product, B a batch of trajectories
   shape(F, [2, 2]), shape(X, [B, 5, 2]), B = 3,
   over([Bi:B, T:4], [over([I:2], [P[I] := 0]),
                      over([I:2, J:2], [P[I] := P[I] + F[I, J] * X[Bi, T, J]]),
                      over([I:2], [X[Bi, T+1, I] := P[I]])]),
   kernels(X, [tile(1)], [K]),
   kernel{par: [B1:3], seq: [T1:4], local: [P1]} :< K,
   B1 == Bi, T1 == T, P1 == P,
   Fs = [0, -1, 1, 0], Xs = [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0],
   eval(X, [F-Fs, X-Xs], Ref), run(X, [F-Fs, X-Xs], V, [device(D)]),
   near(Ref, V).

% A transformer encoder block is nine kernels: two layer norms and the softmax as work-group
% chains, the six matmuls with their initialisations and epilogues fused, bias, residual,
% gelu, the head's scale folded into the softmax.
test(vit_block_is_nine_kernels, [timeout(120), forall(test_device(D, _))]) :-
   S = 16, Dm = 32, H = 2, F = 64, Opts = [tile([8, 8]), group(2), stage(8), local(32), items(8), lanes(2)],
   vit_block(X, Y, S, Dm, H, F),
   kernels(Y, Opts, Ks), length(Ks, 9),
   include([K]>>get_dict(kind, K, groups), Ks, Gs), length(Gs, 3),
   include([K]>>(get_dict(stage, K, stage(_, _, _)), get_dict(pre, K, [_])), Ks, Ms), length(Ms, 6),
   compile:program(Y, Boxes), compile:names(Boxes, Names),
   include([N]>>(N \== Y, compile:boxes_of(N, [])), Names, Inputs),
   maplist([N, N-Vs]>>( shape(N, Sh), compile:size(Sh, Len), numlist(1, Len, Is),
                        maplist([I, V]>>(V is ((I * 7) mod 23) / 23 - 0.5), Is, Vs) ), Inputs, Data),
   eval(Y, Data, Ref), run(Y, Data, V, [device(D) | Opts]),
   near(Ref, V), shape(X, _).

% A view read again and again is inlined into its readers, its index arithmetic simplified
% by the divmod relation to affine: the heads of a reshape, split from the columns of Q and
% read by a matmul, give the source of the heads written by hand.
test(reshape_split_reads_as_written_by_hand, [timeout(120), forall(test_device(D, _))]) :-
   heads(by_hand, S1, Q1), heads(reshape, S2, Q2),
   kernels(S1, [], K1), source(K1, Src1),
   kernels(S2, [], K2), source(K2, Src2),
   Src1 == Src2,
   numlist(1, 512, Is), maplist([I, V]>>(V is ((I * 7) mod 23) / 23 - 0.5), Is, Qs),
   eval(S1, [Q1-Qs], Ref), run(S2, [Q2-Qs], Vs, [device(D)]), near(Ref, Vs).

% A reshape merging axes, reused by a matmul along the merged one, would be read at digits
% that are not affine: its operand is renamed the reshape, written at the merged offset,
% which simplifies to affine, the source of the merge written by hand.
test(reshape_merge_writes_as_written_by_hand, [timeout(120), forall(test_device(D, _))]) :-
   merged(by_hand, Y1, In1), merged(reshape, Y2, In2),
   kernels(Y1, [], K1), source(K1, Src1),
   kernels(Y2, [], K2), source(K2, Src2),
   Src1 == Src2,
   maplist([N, N-Vs]>>( shape(N, Sh), compile:size(Sh, Len), numlist(1, Len, Is),
                        maplist([I, V]>>(V is ((I * 5) mod 17) / 17 - 0.5), Is, Vs) ), In1, Data1),
   pairs_values(Data1, Values), pairs_keys_values(Data2, In2, Values),
   eval(Y1, Data1, Ref), run(Y2, Data2, Vs, [device(D)]), near(Ref, Vs).

% A box reading a prefix of a larger name at digits is no reshape, the sizes differ: the
% name is not renamed, which would write past the end of the smaller one.
test(prefix_read_of_a_larger_name_is_no_reshape, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [5, 8]), shape(A, [5, 8]), shape(Y, [32]), shape(W, [32, 3]), shape(Z, [3]),
   over([I:5, J:8], [A[I, J] := X[I, J] * 2]),
   over([M:32], [Y[M] := A[M // 8, M mod 8]]),
   over([N:3], [Z[N] := 0]),
   over([N1:3, K:32], [Z[N1] := Z[N1] + Y[K] * W[K, N1]]),
   numlist(1, 40, Xs), length(Ws, 96), maplist(=(1), Ws),
   eval(Z, [X-Xs, W-Ws], Ref), run(Z, [X-Xs, W-Ws], Vs, [device(D)]), near(Ref, Vs).

% A reshape whose operand is updated in place reads the operand's initial value: the operand
% is not renamed, its initial value stays an input of the run.
test(reshape_of_a_name_updated_in_place, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [4, 8]), shape(A, [4, 8]), shape(W, [32, 3]), shape(Z, [3]),
   over([I:4, J:8], [A[I, J] := A[I, J] * 0.5 + X[I, J]]),
   Y @= reshape(A, [32]),
   over([N:3], [Z[N] := 0]),
   over([N1:3, K:32], [Z[N1] := Z[N1] + Y[K] * W[K, N1]]),
   numlist(1, 32, Xs), numlist(1, 32, As), length(Ws, 96), maplist(=(1), Ws),
   Data = [A-As, X-Xs, W-Ws],
   eval(Z, Data, Ref), run(Z, Data, Vs, [device(D)]), near(Ref, Vs).

% A quotient of a value that may be negative keeps C's truncation: no divmod rewrite, which
% is of the floored division, in a box a view is inlined into.
test(signed_quotient_is_not_rewritten, [timeout(120), forall(test_device(D, _))]) :-
   shape(A, [4, 8]), shape(Y, [8, 4]), shape(Z, [8, 4, 3]),
   over([I:8, J:4], [Y[I, J] := A[J, I]]),
   over([I1:8, J1:4, K:3], [Z[I1, J1, K] := Y[I1, J1] * ((I1 - 8) // 8)]),
   numlist(1, 32, As),
   eval(Z, [A-As], Ref), run(Z, [A-As], Vs, [device(D)]), near(Ref, Vs).

% A name computed by the boxes of an earlier one, from the same names, is the earlier one: the
% mean var/3 takes is the mean its caller took, two reductions of the rows, not three.
test(common_mean_is_computed_once, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [16, 32]), Rows = [axis(1), keepdims(true)],
   Y @= (X - mean(X, Rows)) / sqrt(var(X, Rows) + 1.0e-5),
   compile:programs([Y], B0), compile:label_program([Y], B0), compile:fuse([Y], B0, B1),
   include(sum_fold, B1, Sums), length(Sums, 2),
   numlist(1, 512, Is), maplist([I, V]>>(V is ((I * 7) mod 23) / 23 - 0.5), Is, Xs),
   eval(Y, [X-Xs], Ref), run(Y, [X-Xs], Vs, [device(D)]), near(Ref, Vs).

% An output is never dropped for an earlier name of the same boxes: each output of a plan
% keeps its own.
test(common_output_kept, [timeout(60)]) :-
   shape(X, [8]),
   A @= sum(X),
   B @= sum(X),
   compile:programs([A, B], B0), compile:label_program([A, B], B0), compile:fuse([A, B], B0, B1),
   include(sum_fold, B1, Sums), length(Sums, 2),
   C @= A + B,
   compile:programs([C], C0), compile:label_program([C], C0), compile:fuse([C], C0, C1),
   include(sum_fold, C1, Sums1), length(Sums1, 1),
   numlist(1, 8, Xs), eval(C, [X-Xs], [72.0]), run(C, [X-Xs], [72.0], []).

% The same merge of a symbolic number of rows: the sizes are equal as products of numbers
% and extents, R*32 both, and the renaming needs no more.
test(reshape_merge_of_symbolic_rows, [timeout(120), forall(test_device(D, _))]) :-
   R1::integer(1, 64), R2::integer(1, 64),
   merged(by_hand, R1, Y1, In1), merged(reshape, R2, Y2, In2),
   kernels(Y1, [], K1), source(K1, Src1),
   kernels(Y2, [], K2), source(K2, Src2),
   Src1 == Src2,
   In1 = [P1, V1, W1], In2 = [P2, V2, W2],
   numlist(1, 1024, Ps0), maplist([I, X]>>(X is ((I * 5) mod 17) / 17 - 0.5), Ps0, Ps),
   numlist(1, 512, Vs0), maplist([I, X]>>(X is ((I * 3) mod 13) / 13 - 0.5), Vs0, Vs),
   numlist(1, 1024, Ws0), maplist([I, X]>>(X is ((I * 7) mod 11) / 11 - 0.5), Ws0, Ws),
   eval(Y1, [P1-Ps, V1-Vs, W1-Ws], Ref), run(Y2, [P2-Ps, V2-Vs, W2-Ws], Out, [device(D)]),
   near(Ref, Out), var(R1), var(R2).

% The divmod relation: X = D*Q + R, R of coefficients in 0..D-1; X // D is Q and X mod D is R
% when R's hull lies in 0..D-1, and Q + R // D and R mod D otherwise.
test(divmod_simplified_by_the_hull, [timeout(10)]) :-
   compile:simplified([], over([I:4, J:8], [Y[(I*8 + J) // 8, (I*8 + J) mod 8] := 0]), B1),
   B1 = over(_, [P1 := _]), P1 = [](Ts1, _), Ts1 == [I, J],
   compile:simplified([], over([I2:4, J2:16], [Y[(I2*8 + J2) // 8] := 0]), B2),
   B2 = over(_, [P2 := _]), P2 = [](Ts2, _), Ts2 == [I2 + J2 // 8],
   shape(Y, [4, 8]).

% A name whose boxes read an earlier name where that name's boxes read itself is no duplicate
% of it: S2, the last term of a row added to the row's sum S1, is not S1, though its boxes
% are those of S1 once S2 is read as S1.
test(reader_of_an_earlier_name_is_no_duplicate, [timeout(60), forall(test_device(D, _))]) :-
   shape(A, [4, 3]), shape(S1, [4]), shape(S2, [4]), shape(Y, [4]),
   over([I:4], [S1[I] := 0]),
   over([I:4, K:3], [S1[I] := S1[I] + A[I, K]]),
   over([I:4], [S2[I] := 0]),
   over([I:4, K:3], [S2[I] := S1[I] + A[I, K]]),
   over([I:4], [Y[I] := S1[I] * 100 + S2[I]]),
   numlist(1, 12, As),
   eval(Y, [A-As], Ref), Ref == [609.0, 1521.0, 2433.0, 3345.0],
   run(Y, [A-As], V, [device(D)]),
   near(Ref, V).

% A residual stream: each layer adds its delta to the stream and reads the sum four times, by
% two means, a centring and the next layer's sum. Inlined, a layer's readers would add every
% delta before it again; the stream is written at each layer instead, see compile:recomputed/3,
% so a kernel of the stream takes three names at most at the last layer as at the first.
test(a_residual_stream_is_written_at_each_layer, [timeout(120), forall(test_device(D, _))]) :-
   Shape = [64, 32],
   shape(X0, Shape), shape(D1, Shape), shape(D2, Shape), shape(D3, Shape), shape(D4, Shape),
   foldl(residual_layer, [D1, D2, D3, D4], [X1, X2, X3, X4], [S1, S2, S3, S4], X0, _),
   Y @= S1 + S2 + S3 + S4 + max(X4, [axis(-1)]),
   kernels(Y, [], Ks),
   maplist([K, Ns]>>get_dict(names, K, Ns), Ks, Nss),
   forall(member(X, [X1, X2, X3]),
          ( include(names_with(X), Nss, Reading),
            Reading = [_, _ | _],
            forall(member(Ns, Reading), ( length(Ns, Len), Len =< 3 )) )),
   include(names_with(X4), Nss, [_, _ | _]),
   numlist(1, 2048, Is),
   maplist([I, V]>>(V is (I mod 13) / 13), Is, Xs),
   maplist({Is}/[M, Vs]>>maplist({M}/[I, V]>>(V is ((I * M) mod 7) / 7 - 0.5), Is, Vs), [3, 5, 11, 17], [V1, V2, V3, V4]),
   Data = [X0-Xs, D1-V1, D2-V2, D3-V3, D4-V4],
   eval(Y, Data, Ref), run(Y, Data, Out, [device(D)]),
   near(Ref, Out).

% A sum of two names read by three boxes costs them six loads, and written once seven: it
% is inlined still, and the three readers are the program.
test(a_sum_read_by_three_boxes_is_inlined, [timeout(30)]) :-
   shape(A, [64, 32]), shape(B, [64, 32]),
   S @= A + B,
   Y @= sum(S, [axis(-1)]) + sum(S * S, [axis(-1)]) + sum(S * S * S, [axis(-1)]),
   kernels(Y, [], Ks),
   \+ ( member(K, Ks), get_dict(names, K, Ns), member(N, Ns), N == S ).

:- end_tests(compile_fusion).

sum_fold(over(_, [P := P1 + _])) :-
   P1 == P.

% heads(+How, -S, -Q): S[H, I, J], the products of the heads of Q[16, 32] of 8 columns each,
% the heads read by hand at Q[I, H*8 + K] or through a reshape of Q.
heads(How, S, Q) :-
   shape(Q, [16, 32]), shape(S, [4, 16, 16]),
   head_reads(How, Q, H, I, J, K, Qi, Qj),
   over([H:4, I:16, J:16], [S[H, I, J] := 0]),
   over([H:4, I:16, J:16, K:8], [S[H, I, J] := S[H, I, J] + Qi * Qj]).

head_reads(by_hand, Q, H, I, J, K, Qi, Qj) => Qi = Q[I, H*8 + K], Qj = Q[J, H*8 + K].
head_reads(reshape, Q, H, I, J, K, Qi, Qj) => Q4 @= reshape(Q, [16, 4, 8]), Qi = Q4[I, H, K], Qj = Q4[J, H, K].

% merged(+How, -Y, -Inputs): Y = O W, O[16, 32] the four heads O3[I, H, K] = sum P[H, I, J]
% V[J, H*8 + K] side by side, written by hand at O[I, H*8 + K] or through a reshape of O3.
merged(How, Y, Inputs) :-
   merged(How, 16, Y, Inputs).

% merged(+How, +R, -Y, -Inputs): merged/3 of R rows, a number or an extent.
merged(How, R, Y, [P, V, W]) :-
   shape(P, [4, R, 16]), shape(V, [16, 32]), shape(W, [32, 32]), shape(Y, [R, 32]),
   heads_out(How, R, O, H, I, K, Ot, Ow),
   over([H:4, I:R, K:8], [Ot := 0]),
   over([H:4, I:R, K:8, J:16], [Ot := Ot + P[H, I, J] * V[J, H*8 + K]]),
   Ow,
   over([I2:R, N:32], [Y[I2, N] := 0]),
   over([I2:R, N:32, K2:32], [Y[I2, N] := Y[I2, N] + O[I2, K2] * W[K2, N]]).

heads_out(by_hand, R, O, H, I, K, Ot, Ow) =>
   shape(O, [R, 32]), Ot = O[I, H*8 + K], Ow = true.
heads_out(reshape, R, O, H, I, K, Ot, Ow) =>
   shape(O3, [R, 4, 8]), Ot = O3[I, H, K], Ow = (O @= reshape(O3, [R, 32])).

:- begin_tests(compile_kinds).

% A count is an int: an int reduction on the device, read back as integers.
test(int_count_reduction, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [8, 64]), shape(C, [8]),
   over([I:8], [C[I] := 0]),
   over([I:8, K:64], [C[I] := C[I] + where(X[I, K] < 0, 1, 0)]),
   numlist(1, 512, Ns), maplist([N, V]>>(V is (N mod 7) - 3), Ns, Xs),
   eval(C, [X-Xs], Ref), run(C, [X-Xs], V, [device(D)]),
   kind(C, int), maplist(integer, V), Ref == V.

% A max over ints starts from the int extreme, in the registers and in the split partials.
test(int_max_reduction, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [4, 1024]), kind(X, int), shape(M, [4]),
   over([I:4], [M[I] := -2147483648]),
   over([I:4, K:1024], [M[I] := max(M[I], X[I, K])]),
   kernels(M, [], Ks), source(Ks, Src), \+ sub_string(Src, _, _, _, "INFINITY"),
   numlist(1, 4096, Ns), maplist([N, V]>>(V is ((N * 7919) mod 1000) - 500), Ns, Xs),
   eval(M, [X-Xs], Ref), run(M, [X-Xs], V, [device(D)]),
   Ref == V.

% An int scatter folds with the built-in atomic.
test(int_scatter_uses_builtin_atomic, [timeout(120), forall(test_device(D, _))]) :-
   shape(Idx, [4096]), elements(Idx, 0-15), shape(H, [16]),
   over([I:16], [H[I] := 0]),
   over([K:4096], [H[Idx[K]] := H[Idx[K]] + 1]),
   kernels(H, [], [_, Scatter]), source([Scatter], Src), once(sub_string(Src, _, _, _, "atomic_add(")),
   numlist(1, 4096, Ks), maplist([X, Y]>>(Y is (X * 7) mod 16), Ks, Is),
   eval(H, [Idx-Is], Ref), run(H, [Idx-Is], V, [device(D)]),
   Ref == V.

% The data is coerced to the kind: an int input given as floats is truncated, a float input
% given as integers is converted; a quotient of ints is a float.
test(kinds_coerce_data, [timeout(120), forall(test_device(D, _))]) :-
   shape(Idx, [8]), elements(Idx, 0-3), shape(X, [4]), shape(Y, [8]),
   over([K:8], [Y[K] := X[Idx[K]] / 2]),
   Data = [Idx-[0.0, 1.0, 2.0, 3.0, 3.0, 2.0, 1.0, 0.0], X-[1, 2, 3, 4]],
   eval(Y, Data, Ref), run(Y, Data, V, [device(D)]),
   kind(Y, float), near([0.5, 1.0, 1.5, 2.0, 2.0, 1.5, 1.0, 0.5], Ref), near(Ref, V).

:- end_tests(compile_kinds).

:- begin_tests(compile_hull).

% A gather through xor, the stride of a bitonic pass, against the Prolog evaluation.
test(xor_gather, [timeout(120), forall(test_device(D, _))]) :-
   power_of_two(N), shape(X, [N]), shape(S, [P]), elements(S, 0-(N-1)), shape(T, [P, N]),
   over([Pi:P, I:N], [T[Pi, I] := X[I xor S[Pi]]]),
   N = 64, P = 3,
   numlist(1, 64, Xs), Data = [X-Xs, S-[1, 8, 32]],
   eval(T, Data, Ref), run(T, Data, V, [device(D)]),
   near(Ref, V).

% A read strided by mod and a quotient, and a where in a subscript.
test(mod_quotient_where_reads, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [32]), shape(T, [32]),
   over([I:32], [T[I] := X[(I*3) mod 32] + X[I // 4] + X[where(I < 16, I, 31 - I)]]),
   numlist(1, 32, Xs), eval(T, [X-Xs], Ref), run(T, [X-Xs], V, [device(D)]),
   near(Ref, V).

% A count over a bit test: /\ in a value, an int reduction.
test(and_in_a_count, [timeout(120), forall(test_device(D, _))]) :-
   shape(C, [8]),
   over([I:8], [C[I] := 0]),
   over([I:8, K:64], [C[I] := C[I] + where((K /\ I) =:= 0, 1, 0)]),
   eval(C, [], Ref), run(C, [], V, [device(D)]),
   Ref == V.

% A non-affine read inside a matmul: the staged kernel loads it one element at a time.
test(non_affine_read_in_a_staged_matmul, [timeout(120), forall(test_device(D, _))]) :-
   power_of_two(M), shape(A, [64, M]), shape(B, [M, 64]), shape(C, [64, 64]),
   over([I:64, J:64], [C[I, J] := 0]),
   over([I:64, J:64, K:M], [C[I, J] := C[I, J] + A[I, K xor 1] * B[K, J]]),
   M = 64,
   numlist(1, 4096, Ns), maplist([X, Y]>>(Y is (X * 3) mod 7 - 3), Ns, As), maplist([X, Y]>>(Y is (X * 5) mod 11 - 5), Ns, Bs),
   eval(C, [A-As, B-Bs], Ref), run(C, [A-As, B-Bs], V, [device(D)]),
   near(Ref, V).

:- end_tests(compile_hull).

:- begin_tests(compile_symbolic).

% An unknown extent is a kernel parameter: one source and one program for every size, and a
% run binds the extents from its data in a scope undone after it.
test(one_program_for_every_size, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [N]), shape(Y, [N]),
   over([I:N], [Y[I] := X[I] * 2]),
   kernels(Y, [], Ks), source(Ks, Src), once(sub_string(Src, _, _, _, "int v")),
   forall(member(Size, [16, 40]),
          ( numlist(1, Size, Xs), eval(Y, [X-Xs], Ref), run(Y, [X-Xs], V, [device(D)]), near(Ref, V) )),
   % the program run builds, by its source, not a count of every program: other units build
   % theirs concurrently
   compile:device(D, Device, Context, _), compile:device_options(Device, Derived),
   merge_options([device(D)], Derived, Options),
   kernels(Y, Options, RunKs), source(RunKs, RunSrc),
   aggregate_all(count, compile:program_state(Context, RunSrc, _), 1),
   var(N).

% A reduction in groups over an unknown row length, the rows counted by another input.
test(groups_reduction_at_two_sizes, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [R, C]), shape(B, [R]), shape(S, [R]),
   over([I:R], [S[I] := B[I]]),
   over([I:R, K:C], [S[I] := S[I] + X[I, K]]),
   forall(member(R0-C0, [8-64, 3-100]),
          ( N is R0*C0, numlist(1, N, Xs), numlist(1, R0, Bs), Data = [X-Xs, B-Bs],
            eval(S, Data, Ref), run(S, Data, V, [device(D), local(32)]), near(Ref, V) )).

% A recurrence over an unknown number of steps.
test(recurrence_at_two_sizes, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [N, M]), shape(W, [M]),
   over([I:M], [Y[0, I] := X[0, I]]),
   over([T:N-1], [over([I:M], [Y[T+1, I] := Y[T, I] + X[T+1, I] * W[I]])]),
   forall(member(N0-M0, [4-8, 7-3]),
          ( L is N0*M0, numlist(1, L, Xs), numlist(1, M0, Ws), Data = [X-Xs, W-Ws],
            eval(Y, Data, Ref), run(Y, Data, V, [device(D)]), near(Ref, V) )).

% A local name is private to a work item: its array holds the slice the item touches, not the
% whole name, so an unknown batch costs it nothing.
test(private_local_holds_the_items_slice, [timeout(120), forall(test_device(D, _))]) :-
   shape(F, [2, 2]), shape(X, [B, 5, 2]),
   over([Bi:B, T:4], [over([I:2], [P[Bi, I] := 0]),
                      over([I:2, J:2], [P[Bi, I] := P[Bi, I] + F[I, J] * X[Bi, T, J]]),
                      over([I:2], [X[Bi, T+1, I] := P[Bi, I]])]),
   kernels(X, [tile(1)], [K]), kernel{local: [P1]} :< K, P1 == P,
   source([K], Src), once(sub_string(Src, _, _, _, "[2] = {0}")),
   Fs = [0, -1, 1, 0],
   forall(member(B0, [3, 64]),
          ( L is B0*10, numlist(1, L, Ns), maplist([I, V]>>(V is (I mod 7) / 7 - 0.5), Ns, Xs),
            eval(X, [F-Fs, X-Xs], Ref), run(X, [F-Fs, X-Xs], V, [device(D), tile(1)]), near(Ref, V) )),
   var(B).

% A reduction whose rows are not work items keeps its initialisation and epilogue as kernels of
% their own: fused, the initialisation would run outside the row loop.
test(sequential_rows_are_not_fused, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [16, 4]), shape(C, [8]), shape(Y, [8]),
   over([I:16], [C[I mod 8] := 0]),
   over([I:16, K:4], [C[I mod 8] := C[I mod 8] + X[I, K]]),
   over([I:16], [Y[I mod 8] := C[I mod 8] * 2]),
   kernels(Y, [], Ks), length(Ks, 3),
   numlist(1, 64, Xs), eval(Y, [X-Xs], Ref), run(Y, [X-Xs], V, [device(D)]), near(Ref, V).

% An extent the data leaves unknown is an error.
test(undetermined_extent, [timeout(120), throws(error(existence_error(extent_value, _), _))]) :-
   shape(X, [N, _]), shape(Y, [N]),
   over([I:N], [Y[I] := X[I, 0]]),
   numlist(1, 12, Xs), run(Y, [X-Xs], _, []).

:- end_tests(compile_symbolic).

:- begin_tests(compile_permutation).

% A scatter through a permutation keeps its axis parallel: a kernel of work items, no atomics.
test(scatter_through_a_permutation_is_parallel, [timeout(120), forall(test_device(D, _))]) :-
   shape(P, [64]), elements(P, 0-63), permutation(P), shape(X, [64]), shape(Y, [64]),
   over([I:64], [Y[P[I]] := X[I] * 2]),
   kernels(Y, [], [K]), kernel{kind: items, par: [_:_], atomics: []} :< K,
   numlist(1, 64, Xs), numlist(0, 63, Is), maplist([I, J]>>(J is (I * 37) mod 64), Is, Ps),
   eval(Y, [P-Ps, X-Xs], Ref), run(Y, [P-Ps, X-Xs], V, [device(D)]), near(Ref, V).

% The bits of a float, as the device holds it.
test(bits_of_floats, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [4]), shape(B, [4]),
   over([I:4], [B[I] := bits(X[I])]),
   Xs = [1.0, -2.0, 0.5, 0.0],
   eval(B, [X-Xs], Ref), run(B, [X-Xs], V, [device(D)]),
   Ref == [1065353216, -1073741824, 1056964608, 0], V == Ref.

:- end_tests(compile_permutation).

:- begin_tests(compile_alloc).

% A name lives from the first kernel mentioning it to the last, and across the whole of a
% host loop it is mentioned in.
test(lifetimes_span_host_loops, [timeout(10), true(Spans == [a-(0-0), b-(1-2), c-(1-3)])]) :-
   lifetimes([kernel{names: [a]}, loop(_, 2, [kernel{names: [b]}, kernel{names: [c]}]), kernel{names: [c]}], Spans).

test(loop_names_live_across_the_loop, [timeout(60)]) :-
   blocked_cholesky(A, L, 128, 32),
   kernels(L, [], Plan), Plan = [_, loop(_, 4, Inner)], length(Inner, NI),
   lifetimes(Plan, Spans),
   forall(( member(N-(First-Last), Spans), N \== A, N \== L ), ( First =:= 1, Last =:= NI )),
   shape(A, _).

% The toy instance of minimalloc.pl: the packing reaches the peak, and buffers alive at once
% are apart.
test(packing_reaches_the_peak, [timeout(10), true(Bytes == 250)]) :-
   Bufs = [buffer(1, 0, 2, 100, _), buffer(2, 1, 3, 100, _), buffer(3, 2, 4, 100, _), buffer(4, 0, 4, 50, _)],
   compile:packing(Bufs, 50, 250, Bytes),
   forall(( member(buffer(I, S1, E1, Z1, O1), Bufs), member(buffer(J, S2, E2, Z2, O2), Bufs), I < J, S1 < E2, S2 < E1 ),
          ( O1 + Z1 =< O2 ; O2 + Z2 =< O1 )).

:- end_tests(compile_alloc).

:- begin_tests(compile_layout).

% The symbolic layout: decided at the reference point, every extent at its upper bound, and
% valid at every value of the extents.

mlp(X, Y, B) :-
   B::integer(1, 1024),
   shape(X, [B, 784]), shape(W1, [256, 784]), shape(B1, [256]), shape(W2, [128, 256]), shape(B2, [128]),
   shape(W3, [10, 128]), shape(B3, [10]),
   dense(X, W1, B1, H1, B, 784, 256), relu(H1, A1, B, 256),
   dense(A1, W2, B2, H2, B, 256, 128), relu(H2, A2, B, 128),
   dense(A2, W3, B3, Y, B, 128, 10).

dense(X, W, Bias, Y, B, In, Out) :-
   shape(Y, [B, Out]),
   over([I:B, J:Out], [Y[I, J] := Bias[J]]),
   over([I:B, J:Out, K:In], [Y[I, J] := Y[I, J] + X[I, K] * W[J, K]]).

relu(X, Y, B, N) :-
   shape(Y, [B, N]),
   over([I:B, J:N], [Y[I, J] := max(0, X[I, J])]).

% evaluated(+Layout, +Bindings, -Places, -Bytes): the slots as Name-(Offset-Size), and the bytes,
% with the extents bound as Bindings, Extent-Value pairs, says; undone.
evaluated(layout(Slots, Goals, Bytes), Bindings, Places, Total) :-
   findall(Ps-Bytes,
           ( maplist([E-V]>>(E = V), Bindings),
             maplist(call, Goals),
             maplist([slot(_, S, O), O-S]>>true, Slots, Ps) ),
           [Places0-Total]),
   maplist([slot(N, _, _), O-S, N-(O-S)]>>true, Slots, Places0, Places).

% apart(+Spans, +Places): names alive at once hold disjoint bytes.
apart(Spans, Places) :-
   forall(( nth1(I, Places, N1-(O1-S1)), nth1(J, Places, N2-(O2-S2)), I < J,
            compile:span_of(Spans, N1, F1-L1), compile:span_of(Spans, N2, F2-L2), F1 =< L2, F2 =< L1 ),
          ( O1 + S1 =< O2 ; O2 + S2 =< O1 )).

% reference_height(+Plan, +Names, +Align, -Height): the arena packing/4 gives at the reference point.
reference_height(Plan, Names, Align, Height) :-
   lifetimes(Plan, Spans),
   maplist(shape, Names, Shapes), term_variables(Shapes, Extents),
   findall(H, ( maplist(compile:upper, Extents),
                maplist(compile:aligned_bytes(Align), Names, Sizes),
                length(Names, N), numlist(1, N, Ids),
                maplist(compile:buffer_of(Spans), Ids, Names, Sizes, Bufs),
                compile:peak(Bufs, Peak),
                compile:packing(Bufs, Align, Peak, H) ),
           [Height]).

test(matmul_chain_apart_at_every_size, [timeout(60)]) :-
   N::integer(1, 64),
   matmul(A, B, C, N, 16, 8), matmul(C, D, E, N, 8, 4),
   kernels(E, [], Plan),
   arena_names(Plan, E, all, Names), length(Names, 5),
   layout(Plan, Names, 64, Layout),
   lifetimes(Plan, Spans),
   forall(member(V, [1, 3, 17, 64]),
          ( evaluated(Layout, [N-V], Places, Bytes), apart(Spans, Places),
            forall(member(_-(O-S), Places), ( O mod 64 =:= 0, O + S =< Bytes )) )),
   reference_height(Plan, Names, 64, Height),
   evaluated(Layout, [N-64], _, Height),
   var(N), shape(A, _), shape(B, _), shape(D, _).

% The intermediates alone, as allocate/8 shares them: the inputs and the output are not slots.
test(intermediates_alone, [timeout(60)]) :-
   N::integer(1, 64),
   matmul(A, B, C, N, 16, 8), matmul(C, D, E, N, 8, 4),
   kernels(E, [], Plan),
   arena_names(Plan, E, intermediates, Names),
   Names = [C1], C1 == C,
   layout(Plan, Names, 64, Layout),
   evaluated(Layout, [N-64], [_-(0-2048)], 2048),
   shape(A, _), shape(B, _), shape(D, _).

test(mlp_tight_at_the_bound, [timeout(120)]) :-
   mlp(X, Y, B),
   kernels(Y, [], Plan),
   arena_names(Plan, Y, all, Names),
   layout(Plan, Names, 256, Layout),
   lifetimes(Plan, Spans),
   forall(member(V, [1, 7, 1000, 1024]),
          ( evaluated(Layout, [B-V], Places, _), apart(Spans, Places) )),
   reference_height(Plan, Names, 256, Height),
   evaluated(Layout, [B-1024], _, Height),
   evaluated(Layout, [B-1], _, Small), Small < Height,
   var(B), shape(X, _).

% A host loop: a name mentioned in it lives across the loop, and the names alive at once in
% its steps are apart.
test(host_loop_names_apart, [timeout(120)]) :-
   blocked_cholesky(A, L, 128, 32),
   kernels(L, [], Plan), memberchk(loop(_, _, _), Plan),
   arena_names(Plan, L, all, Names),
   layout(Plan, Names, 64, Layout),
   lifetimes(Plan, Spans),
   evaluated(Layout, [], Places, Bytes), apart(Spans, Places),
   reference_height(Plan, Names, 64, Bytes),
   shape(A, _).

test(unbounded_extent_has_no_layout, [timeout(60), error(domain_error(bounded_extent, _))]) :-
   shape(X, [N]), shape(Y, [N]),
   over([I:N], [Y[I] := X[I] * 2]),
   kernels(Y, [], Plan),
   arena_names(Plan, Y, all, Names),
   layout(Plan, Names, 64, _).

:- end_tests(compile_layout).

floats(Values, Buffer) :-
   length(Values, N),
   compound_name_arguments(Data, data, Values),
   buffer_from_data(Buffer, float32, N, Data).

double_plus_one(X, H, Y, N) :-
   shape(X, [N]), shape(H, [N]), shape(Y, [N]),
   over([I:N], [H[I] := X[I] * 2]),
   over([I:N], [Y[I] := H[I] + 1]).

:- begin_tests(compile_realize).

% A realized name is an input with a value: a program reading it starts from it, and its
% boxes, kept, are not run again.

% Weights on host, copied to the device once, realized there: a run reads them in place.
test(resident_weights_need_no_data, [timeout(120), forall(test_device(D, _))]) :-
   floats([1.0, 0.0, 0.0, 1.0, 1.0, 1.0], Bv),
   shape(Bh, [3, 2]), value(Bh, Bv),
   copy(Bh, B, D),
   realize([B], [], []),
   value(B, Mem), blob(Mem, cl_mem),
   matmul(A, B, C, 2, 3, 2),
   As = [1, 2, 3, 4, 5, 6],
   eval(C, [A-As], Ref),
   run(C, [A-As], V, []),
   Ref == [4.0, 5.0, 10.0, 11.0], near(Ref, V).

test(realized_intermediate_breaks_the_graph, [timeout(120), forall(test_device(D, _))]) :-
   double_plus_one(X, H, Y, N), N::integer(1, 100),
   program(Y, [_, _]),
   realize([H], [X-[1, 2, 3]], [device(D)]),
   N == 3,
   device(H, D),
   program(Y, [_]),
   run(Y, [], V, []),
   eval(Y, [], Ref),
   Ref == [3.0, 5.0, 7.0], near(Ref, V).

% Realized on a device, a value stays there: a cl_mem, read back only when asked.
test(realized_output_stays_on_its_device, [timeout(120)]) :-
   double_plus_one(X, _, Y, 3),
   realize([Y], [X-[1, 2, 3]], [device(pocl)]),
   value(Y, Mem), blob(Mem, cl_mem),
   device(Y, pocl),
   program(Y, []),
   run(Y, [], V, []),
   V == [3.0, 5.0, 7.0].

% Data for a realized name is its argument, its boxes still not run.
test(data_for_a_realized_name, [timeout(120)]) :-
   double_plus_one(X, H, Y, 3),
   realize([H], [X-[1, 2, 3]], []),
   run(Y, [H-[1, 2, 3]], V, []),
   V == [2.0, 3.0, 4.0],
   program(Y, [_]).

test(unrealized_name_is_computed_again, [timeout(120), forall(test_device(D, _))]) :-
   double_plus_one(X, H, Y, 3),
   realize([H], [X-[1, 2, 3]], [device(D)]),
   unrealize(H),
   program(Y, [_, _]),
   run(Y, [X-[0, 1, 2]], V, []),
   V == [1.0, 3.0, 5.0].

% The value of a realized index bounds a gather through it, no range declared, and its copy
% takes the range.
test(gather_through_a_realized_index, [timeout(120), forall(test_device(D, _))]) :-
   buffer_from_data(Ib, int32, 3, data(2, 0, 1)),
   shape(Ih, [3]), kind(Ih, int), value(Ih, Ib),
   copy(Ih, Idx, D),
   shape(X, [3]), shape(Y, [3]),
   over([I:3], [Y[I] := X[Idx[I]]]),
   eval(Y, [X-[10, 20, 30]], Ref),
   run(Y, [X-[10, 20, 30]], V, []),
   Ref == [30.0, 10.0, 20.0], near(Ref, V).

test(realize_a_bool, [timeout(120)]) :-
   shape(X, [3]), shape(M, [3]),
   over([I:3], [M[I] := X[I] < 2]),
   realize([M], [X-[1, 2, 3]], []),
   kind(M, bool),
   elements(M, R), R == 0-1,
   run(M, [], V, []),
   V == [1, 0, 0].

:- end_tests(compile_realize).

:- begin_tests(compile_devices).

% A program whose device stays unknown runs on any device, and stays unknown after.
test(device_polymorphic_program, [timeout(120), forall(test_device(D, _))]) :-
   double_plus_one(X, _, Y, 3),
   run(Y, [X-[1, 2, 3]], V, [device(D)]),
   V == [3.0, 5.0, 7.0],
   device(Y, DY), var(DY).

test(host_round_trip, [timeout(120), forall(test_device(D, _))]) :-
   floats([5.0, 6.0], B),
   shape(W, [2]), value(W, B),
   copy(W, Wd, D),
   copy(Wd, Wh, host),
   run(Wh, [], V, []),
   V == [5.0, 6.0].

% One program on two devices, a copy between them a transfer of its plan.
test(two_devices, [timeout(120), forall(( test_device(D1, _), test_device(D2, _), D1 @< D2 ))]) :-
   shape(X, [4]), shape(H, [4]),
   over([I:4], [H[I] := X[I] * 2]),
   device(H, D1),
   copy(H, Hd, D2),
   shape(Y, [4]),
   over([I:4], [Y[I] := Hd[I] + 1]),
   kernels(Y, [], Plan),
   memberchk(transfer(_, _), Plan),
   Data = [X-[1, 2, 3, 4]],
   eval(Y, Data, Ref),
   run(Y, Data, V, []),
   Ref == [3.0, 5.0, 7.0, 9.0], near(Ref, V).

% A device to device copy, realized on the second, read back through the host.
test(device_to_device, [timeout(120), forall(( test_device(D1, _), test_device(D2, _), D1 \== D2 ))]) :-
   floats([1.5, 2.5, 3.5], B),
   shape(W, [3]), value(W, B),
   copy(W, W1, D1), copy(W1, W2, D2),
   realize([W2], [], []),
   device(W2, D2),
   run(W2, [], V, []),
   V == [1.5, 2.5, 3.5].

test(unknown_device, [timeout(120), error(existence_error(opencl_device, nowhere))]) :-
   double_plus_one(X, _, Y, 3),
   run(Y, [X-[1, 2, 3]], _, [device(nowhere)]).

:- end_tests(compile_devices).

:- begin_tests(compile_review).

% A name written once at a target that is an expression in its index is read by a later box:
% fusion must compare the targets with the indices by identity, never unify them.
test(reversal_read_later_is_not_fused_cyclically, [timeout(60), true(V == Ref)]) :-
   N = 4,
   shape(X, [N]),
   over([I:N], [Y[N-1-I] := X[I]]),
   over([I:N], [Z[I] := Y[I] * 2]),
   eval(Z, [X-[1, 2, 3, 4]], Ref),
   run(Z, [X-[1, 2, 3, 4]], V, []).

test(padding_read_later_is_not_fused_cyclically, [timeout(60), true(V == Ref)]) :-
   shape(X, [2, 2]), shape(Y, [4, 4]),
   over([I:2, J:2], [Y[I+1, J+1] := X[I, J]]),
   over([I:4, J:4], [Z[I, J] := where(0 < I, where(I < 3, where(0 < J, where(J < 3, Y[I, J], 0), 0), 0), 0)]),
   eval(Z, [X-[1, 2, 3, 4]], Ref),
   run(Z, [X-[1, 2, 3, 4]], V, []).

% A sweep whose slices live in local memory, run below the bound of a symbolic extent: the
% slice copied in and out is the one of this run's size, not of the bound.
test(sweep_shared_slice_below_bound, [timeout(120), forall(member(Nv, [32, 48]))]) :-
   N::integer(32, 64),
   batched_cholesky(A, L, 2, N),
   N1 is Nv - 1,
   findall(V, ( between(1, 2, B), between(0, N1, I), between(0, N1, J),
                ( I =:= J -> V is Nv + B ; V is 1.0 / (1 + abs(I - J)) ) ), As),
   eval(L, [A-As], Ref),
   run(L, [A-As], V, [device(pocl)]),
   assertion(near(Ref, V)).

% The reference raises on a gather the data sends out of bounds, as run/4 does.
test(eval_raises_on_a_subscript_outside_the_range, [timeout(60), error(domain_error(in_bounds, _))]) :-
   shape(X, [4]), shape(Idx, [4]), elements(Idx, 0-3),
   over([I:4], [Y[I] := X[Idx[I]]]),
   eval(Y, [X-[10, 20, 30, 40], Idx-[0, 1, 2, 700]], _).

:- end_tests(compile_review).

:- begin_tests(compile_tiles).

% The fast path of a reduction, strips of rows in registers and reads staged in local memory,
% on extents that are not a known multiple of the tile: a multiple the program states as a
% product, 64*K; an extent the tile does not divide, its last strip shifted inwards; a
% reduced axis longer than its blocks by a rest.

% rows_product(+N, +D, +M, -X, -W, -C): C[N, M] = X[N, D] W[D, M].
rows_product(N, D, M, X, W, C) :-
   shape(X, [N, D]), shape(W, [D, M]),
   C @= X @ W.

% centred(+N, +P, -Vs): N small values about 0.
centred(N, P, Vs) :-
   numlist(1, N, Is),
   maplist({P}/[I, V]>>(V is ((I * 7) mod P) / P - 0.5), Is, Vs).

% product_matches(+D, +C, +X, +W, +Rows, +Cols, +M): the product run on D at the sizes given
% is the reference's.
product_matches(D, C, X, W, Rows, Cols, M) :-
   NX is Rows*Cols, NW is Cols*M,
   centred(NX, 13, Xs), centred(NW, 11, Ws),
   eval(C, [X-Xs, W-Ws], Ref),
   run(C, [X-Xs, W-Ws], V, [device(D)]),
   near(Ref, V).

% staged(+Ks): the last kernel of Ks stages its reads.
staged(Ks) :-
   last(Ks, K),
   get_dict(stage, K, Stage),
   Stage \== none.

% A multiple of the tile as the program states it: the rows are strips, the strips whole
% work-groups, the kernel the staged one of a known extent, with the extent its parameter.
test(symbolic_multiple_is_staged, [timeout(60)]) :-
   rows_product(64*K, 32, 64, _, _, C), K::integer(1, 8),
   kernels(C, [], Ks),
   last(Ks, Kernel),
   kernel{stage: stage(8, 8, Tiles), shifted: [], par: [_:E, _:16], extents: [K1]} :< Kernel,
   length(Tiles, 2), E == 16*K, K1 == K,
   source(Ks, Src),
   once(sub_string(Src, _, _, _, "__local float s0_[")),
   once(sub_string(Src, _, _, _, "float4 *")),
   var(K).

test(symbolic_multiple_matches_reference, [timeout(120), forall(( test_device(D, _), member(K0, [1, 3]) ))]) :-
   rows_product(64*K, 32, 64, X, W, C), K::integer(1, 8),
   Rows is 64*K0,
   product_matches(D, C, X, W, Rows, 32, 64),
   var(K).

% The data of a product of extents binds them, and data that is no multiple is refused.
test(symbolic_multiple_refuses_another_size, [timeout(60), error(domain_error(data_length(_), _))]) :-
   rows_product(64*K, 4, 4, X, W, C), K::integer(1, 8),
   centred(280, 13, Xs), centred(16, 11, Ws),
   run(C, [X-Xs, W-Ws], _, []).

% A realized argument binds the product as the data does.
test(symbolic_multiple_of_a_realized_argument, [timeout(120), forall(test_device(D, _))]) :-
   rows_product(64*K, 32, 64, X, W, C), K::integer(1, 8),
   centred(4096, 13, Xs), centred(2048, 11, Ws),
   eval(C, [X-Xs, W-Ws], Ref),
   floats(Xs, Xv), floats(Ws, Wv),
   shape(Xh, [128, 32]), value(Xh, Xv), shape(Wh, [32, 64]), value(Wh, Wv),
   copy(Xh, Xd, D), copy(Wh, Wd, D), realize([Xd, Wd], [], []),
   run(C, [X-Xd, W-Wd], V, [device(D)]),
   near(Ref, V),
   var(K).

test(symbolic_multiple_refuses_a_realized_argument_of_another_size, [timeout(60), error(domain_error(shape(_), _))]) :-
   rows_product(64*K, 4, 4, X, W, C), K::integer(1, 8),
   centred(280, 13, Xs), centred(16, 11, Ws),
   floats(Xs, Xv), floats(Ws, Wv),
   shape(Xh, [70, 4]), value(Xh, Xv), shape(Wh, [4, 4]), value(Wh, Wv),
   run(C, [X-Xh, W-Wh], _, []).

% The reduced axis a multiple too: its blocks divide the number of the product, and a vector
% runs along a row of 64*K columns, a multiple of its width at every K.
test(symbolic_multiple_reduced_axis_is_staged, [timeout(120), forall(test_device(D, _))]) :-
   rows_product(64*K, 64*K, 32, X, W, C), K::integer(1, 4),
   kernels(C, [], Ks), staged(Ks),
   last(Ks, Kernel), kernel{stage: stage(8, 8, _)} :< Kernel,
   product_matches(D, C, X, W, 64, 64, 32),
   product_matches(D, C, X, W, 128, 128, 32),
   var(K).

% The offset of a row of a name of 64*K columns: the lane has its stride, a vector along it
% starts at a multiple of its width; a strip has none, the extent multiplies it. A row of N
% columns, N unknown, starts anywhere.
test(stride_and_alignment_through_an_unknown_extent, [timeout(60)]) :-
   K::integer(1, 8), N::integer(1, 512),
   Row = (I*8 + Ii) * (64*K) + J*8 + V,
   compile:stride(V, Row, 1),
   \+ compile:stride(Ii, Row, _),
   compile:aligned(4, V, Row),
   Odd = (I*8 + Ii) * N + J*8 + V,
   compile:stride(V, Odd, 1),
   \+ compile:aligned(4, V, Odd),
   var(I), var(J).

% An extent the tile does not divide: the last strip is shifted inwards, the kernel staged,
% at every size above the tile; a size up to the tile has no strip.
test(shifted_strip_is_staged, [timeout(60)]) :-
   rows_product(891, 32, 64, _, _, C),
   kernels(C, [], Ks),
   last(Ks, Kernel),
   kernel{stage: stage(8, 8, _), shifted: [I-shift(891, 4, 224)], par: [I1:888, _:16]} :< Kernel,
   I1 == I,
   source(Ks, Src),
   once(sub_string(Src, _, _, _, "min((int)(gi * 8 + li) * 4, 887)")).

test(shifted_strip_matches_reference, [timeout(300), forall(( test_device(D, _), test_size(D, [cpu, gpu], [1, 3, 4, 5, 7, 8, 9, 63, 65, 891], [3, 891], N) ))]) :-
   rows_product(N, 32, 64, X, W, C),
   product_matches(D, C, X, W, N, 32, 64).

% Both axes shifted, and the columns the tile of the vector.
test(shifted_strips_of_both_axes, [timeout(120), forall(( test_device(D, _), test_size(D, [cpu, gpu], [9-9, 65-67, 70-33], [65-67], N-M) ))]) :-
   rows_product(N, 16, M, X, W, C),
   product_matches(D, C, X, W, N, 16, M).

% A reduction that reads its sums, its initialisation a kernel of its own, may not overlap:
% two work items would add to the rows they share. Its rows stay whole strips, or none.
test(reduction_reading_its_sums_is_not_shifted, [timeout(120), forall(test_device(D, _))]) :-
   matmul(A, B, C, 891, 16, 32),
   kernels(C, [epilogue(false)], Ks),
   last(Ks, Red), kernel{shifted: [], stage: none} :< Red,
   centred(14256, 13, As), centred(512, 11, Bs),
   eval(C, [A-As, B-Bs], Ref),
   run(C, [A-As, B-Bs], V, [device(D), epilogue(false)]),
   near(Ref, V).

% An unknown extent of a tile at the least, as the program declares it: one program for
% every size, staged, the strips counted at each run.
test(symbolic_shifted_strip_is_staged, [timeout(60)]) :-
   rows_product(N, 32, 64, _, _, C), {N >= 64},
   kernels(C, [], Ks),
   last(Ks, Kernel),
   kernel{stage: stage(8, 8, _), shifted: [_-shift(N1, 4, _)], extents: [N2]} :< Kernel,
   N1 == N, N2 == N,
   var(N).

test(symbolic_shifted_strip_matches_reference, [timeout(300), forall(test_device(D, _))]) :-
   rows_product(N, 32, 64, X, W, C), N::integer(64, 1024),
   forall(member(Rows, [64, 65, 71, 100, 891]),
          product_matches(D, C, X, W, Rows, 32, 64)),
   var(N).

% Without the bound the least value of the extent is under a tile: no strip of the rows, no stage.
test(symbolic_extent_without_a_bound_has_no_strip, [timeout(60)]) :-
   rows_product(N, 32, 64, _, _, C),
   kernels(C, [], Ks),
   forall(member(K, Ks), \+ get_dict(stage, K, stage(_, _, _))),
   forall(member(K, Ks), \+ get_dict(shifted, K, [_ | _])),
   var(N).

% A reduced axis no block divides: whole blocks staged, then the rest on the global reads.
test(rest_of_a_staged_axis, [timeout(60)]) :-
   rows_product(64, M, 64, _, _, C), {M >= 8},
   kernels(C, [], Ks),
   last(Ks, Kernel), kernel{stage: stage(8, 8, _)} :< Kernel,
   source(Ks, Src),
   once(sub_string(Src, _, _, _, "kb < (v")),
   once(sub_string(Src, _, _, _, " / 8) * 8); v")),
   var(M).

test(rest_of_a_staged_axis_matches_reference, [timeout(300), forall(test_device(D, _))]) :-
   rows_product(N, M, 64, X, W, C), N::integer(64, 128), M::integer(16, 128),
   forall(member(Rows-Cols, [64-16, 64-17, 70-31, 64-50, 67-64]),
          product_matches(D, C, X, W, Rows, Cols, 64)),
   var(N), var(M).

% A known reduced axis with no divisor worth a block, a prime: blocks and a rest too.
test(rest_of_a_prime_axis, [timeout(120), forall(test_device(D, _))]) :-
   rows_product(64, 37, 64, X, W, C),
   kernels(C, [], Ks), staged(Ks),
   product_matches(D, C, X, W, 64, 37, 64).

% The rows of a softmax and of a layer norm, reductions with their epilogues, and the square
% scores of an attention, at a size no tile divides, unknown and known.
attention(N, X, W, O) :-
   shape(X, [N, 16]), shape(W, [16, 48]),
   Rows = [axis(-1), keepdims(true)],
   Xn @= (X - mean(X, Rows)) / sqrt(var(X, Rows) + 1.0e-5),
   Qkv @= Xn @ W,
   S @= Qkv[_, 0:16] @ matrix_transpose(Qkv[_, 16:32]) * 0.1,
   Ex @= exp(S - max(S, Rows)),
   O @= (Ex @ Qkv[_, 32:48]) / sum(Ex, Rows).

attention_matches(D, O, X, W, Rows) :-
   NX is Rows*16,
   centred(NX, 13, Xs), centred(768, 11, Ws),
   eval(O, [X-Xs, W-Ws], Ref),
   run(O, [X-Xs, W-Ws], V, [device(D)]),
   near(Ref, V).

test(attention_at_sizes_no_tile_divides, [timeout(300), forall(( test_device(D, _), test_size(D, cpu, [9, 67, 150], [67], N) ))]) :-
   attention(N, X, W, O),
   attention_matches(D, O, X, W, N).

test(attention_at_unknown_sizes, [timeout(300), forall(test_device(D, _))]) :-
   attention(N, X, W, O), N::integer(64, 256),
   forall(member(Rows, [64, 67, 150]), attention_matches(D, O, X, W, Rows)),
   var(N).

test(attention_at_a_symbolic_multiple, [timeout(300), forall(test_device(D, _))]) :-
   attention(64*K, X, W, O), K::integer(1, 4),
   forall(member(Rows, [64, 192]), attention_matches(D, O, X, W, Rows)),
   var(K).

% The packed kernel of a thread per core, with a reduced axis of several blocks: the sums of
% a block of rows stay in register tiles of the work item's own between the blocks, a tile
% per tile of the block, so that the initialisation is the kernel's, before the first block,
% and the rows no tile divides are shifted strips. The options are a CPU's, with blocks small enough for small data.
packed([threads(4), panel(32, 16), tile([4, 16]), vector(8), lds(262144)]).

test(packed_blocks_keep_their_sums, [timeout(60)]) :-
   packed(Opts),
   rows_product(70, 96, 64, _, _, C),
   kernels(C, Opts, [K]),
   kernel{stage: pack(4, 32, _, _, _, [_, _]), pre: [_], shifted: [I-shift(70, 4, 18)], par: [I1:67, _:4]} :< K,
   I1 == I,
   source([K], Src),
   once(sub_string(Src, _, _, _, "+ ip) * 64) + ")),
   once(sub_string(Src, Mb, _, _, "for (int mb = 0;")), once(sub_string(Src, Kb, _, _, "for (int kb = 0;")), Mb < Kb.

% One block of the reduced axis: the one register tile.
test(packed_block_alone_has_no_sums_panel, [timeout(60)]) :-
   packed(Opts),
   rows_product(70, 32, 64, _, _, C),
   kernels(C, Opts, [K]),
   kernel{stage: pack(4, 32, _, _, _, _), pre: [_]} :< K,
   source([K], Src),
   \+ sub_string(Src, _, _, _, "+ ip) * 64) + ").

% Whole strips and several blocks: the reduction alone, as before, its tile loaded and stored
% at each block, the initialisation a kernel of its own.
test(packed_blocks_of_whole_strips_are_a_reduction_alone, [timeout(60)]) :-
   packed(Opts),
   rows_product(72, 96, 64, _, _, C),
   kernels(C, Opts, [_, K]),
   kernel{stage: pack(4, 32, _, _, _, _), pre: [], shifted: []} :< K,
   source([K], Src),
   \+ sub_string(Src, _, _, _, "+ ip) * 64) + ").

% The reduction alone, its initialisation a kernel of its own, reads its sums: whole strips,
% the one register tile loaded and stored at each block.
test(packed_reduction_alone_has_no_sums_panel, [timeout(60)]) :-
   packed(Opts),
   rows_product(72, 96, 64, _, _, C),
   kernels(C, [epilogue(false) | Opts], Ks),
   last(Ks, K), kernel{stage: pack(4, 32, _, _, _, _), pre: [], shifted: []} :< K,
   source(Ks, Src),
   \+ sub_string(Src, _, _, _, "+ ip) * 64) + ").

% An unknown reduced axis, of unknown blocks, the last one shorter: one program for every size.
test(packed_blocks_of_an_unknown_axis, [timeout(60)]) :-
   packed(Opts),
   rows_product(N, M, 64, _, _, C), N::integer(64, 1024), M::integer(64, 1024),
   kernels(C, Opts, [K]),
   kernel{stage: pack(_, 32, _, _, _, _), pre: [_], shifted: [_-shift(N1, 4, _)]} :< K,
   N1 == N,
   source([K], Src),
   once(sub_string(Src, _, _, _, "+ ip) * 64) + ")),
   once(sub_string(Src, _, _, _, "int kc = (")),
   var(N), var(M).

packed_product_matches(D, C, X, W, Rows, Cols, M) :-
   packed(Opts),
   NX is Rows*Cols, NW is Cols*M,
   centred(NX, 13, Xs), centred(NW, 11, Ws),
   eval(C, [X-Xs, W-Ws], Ref),
   run(C, [X-Xs, W-Ws], V, [device(D) | Opts]),
   near(Ref, V).

test(packed_blocks_match_reference,
     [timeout(300), forall(( test_device(D, _), test_size(D, cpu, [70-257-64, 67-300-48, 64-891-64, 33-100-37], [70-257-64, 33-100-37], N-M-P) ))]) :-
   rows_product(N, M, P, X, W, C),
   packed_product_matches(D, C, X, W, N, M, P).

test(packed_blocks_of_an_unknown_axis_match_reference, [timeout(300), forall(test_device(D, _))]) :-
   rows_product(N, M, 64, X, W, C), N::integer(64, 128), M::integer(64, 1024),
   forall(member(Rows-Cols, [64-64, 67-257, 70-300, 64-891]),
          packed_product_matches(D, C, X, W, Rows, Cols, 64)),
   var(N), var(M).

test(packed_blocks_of_a_symbolic_multiple_match_reference, [timeout(300), forall(test_device(D, _))]) :-
   rows_product(64*K, 64*L, 64, X, W, C), K::integer(1, 4), L::integer(1, 8),
   forall(member(Rows-Cols, [64-64, 128-320, 64-512]),
          packed_product_matches(D, C, X, W, Rows, Cols, 64)),
   var(K), var(L).

% An epilogue after the blocks: it runs at the last block alone, on the whole sums, and a
% name it folds into, read at each tile, is read there.
test(packed_blocks_with_an_epilogue_match_reference,
     [timeout(300), forall(( test_device(D, _), test_size(D, cpu, [70-257, 65-96, 67-300], [70-257], N-M) ))]) :-
   packed(Opts),
   shape(X, [N, M]), shape(W, [M, 48]), shape(B, [N, 48]),
   O @= B + exp((X @ W) * 0.1),
   kernels(O, Opts, Ks), last(Ks, K),
   kernel{stage: pack(_, _, _, _, _, _), pre: [_], post: [_ | _]} :< K,
   NX is N*M, NW is M*48, NB is N*48,
   centred(NX, 13, Xs), centred(NW, 11, Ws), centred(NB, 7, Bs),
   eval(O, [X-Xs, W-Ws, B-Bs], Ref),
   run(O, [X-Xs, W-Ws, B-Bs], V, [device(D) | Opts]),
   near(Ref, V).

% The attention with the options of each device: on a CPU the product of the scores with the
% values reduces over the rows, more than a block of them, known, unknown and a multiple.
test(attention_over_several_blocks, [timeout(600), forall(( test_device(D, _), test_size(D, cpu, [257, 300], [300], N) ))]) :-
   attention(N, X, W, O),
   attention_matches(D, O, X, W, N).

test(attention_over_several_unknown_blocks, [timeout(600), forall(test_device(D, _))]) :-
   attention(N, X, W, O), N::integer(64, 1024),
   forall(member(Rows, [257, 300]), attention_matches(D, O, X, W, Rows)),
   var(N).

test(attention_over_several_blocks_of_a_multiple, [timeout(600), forall(test_device(D, _))]) :-
   attention(64*K, X, W, O), K::integer(1, 8),
   forall(member(Rows, [320]), attention_matches(D, O, X, W, Rows)),
   var(K).

% The product of the scores with the values, 128 wide, with the options of a CPU: packed,
% its sums kept between the blocks of the rows it reduces over, known or not.
wide_attention(N, O) :-
   shape(X, [N, 128]), shape(W, [128, 384]),
   Rows = [axis(-1), keepdims(true)],
   Qkv @= X @ W,
   S @= Qkv[_, 0:128] @ matrix_transpose(Qkv[_, 128:256]) * 0.1,
   Ex @= exp(S - max(S, Rows)),
   O @= (Ex @ Qkv[_, 256:384]) / sum(Ex, Rows).

test(cpu_attention_values_keep_their_sums, [timeout(120), forall((test_device(_, Dev), cl_device_info(Dev, type, cpu)))]) :-
   device_options(Dev, Opts),
   forall(member(Size, [891, unknown]),
          ( wide_attention_rows(Size, N), wide_attention(N, O),
            kernels(O, Opts, Ks),
            once(( member(K, Ks), kernel{stage: pack(_, _, _, _, _, _), pre: [_], seq: [_:D | _]} :< K, D == N )),
            source(Ks, Src),
            once(sub_string(Src, _, _, _, "+ ip) * 64) + ")) )).

wide_attention_rows(unknown, N) => N::integer(64, 2048).
wide_attention_rows(Size, N) => N = Size.

% The softmax of the rows of the scores S, weighing the values V. The program has the sum of
% the exponentials after their product with the values, and the division last: the sum is
% computed before the product, where it joins the maximum and the exponentials in one kernel
% of work-groups, a group per row, each exponential written and summed in one pass, and the
% product divides its rows in its epilogue.
weighed(N, M, S, V, O) :-
   shape(S, [N, N]), shape(V, [N, M]),
   Rows = [axis(-1), keepdims(true)],
   Ex @= exp(S - max(S, Rows)),
   O @= (Ex @ V) / sum(Ex, Rows).

% The options of a device of work-groups, a GPU.
grouped([vector(4), group(8), tile([8, 8]), stage(16), local(256), items(40), threads(0), lanes(32)]).

% softmax_chain(+K, -Sum): K is the kernel of the maximum of the rows, their exponentials and
% the Sum of these.
softmax_chain(K, Sum) :-
   kernel{kind: groups, rows: [_],
          phases: [serial(_), reduce(_, [red(Max, _, max, _)]), serial(_),
                   reduce(_, [red(Sum, _, +, Ex1[_, _])], [Ex[_, _] := exp(_ - Max1[_, _])])]} :< K,
   Max1 == Max, Ex1 == Ex.

% weighed_rows(+Size, -N): the rows of a size: a known one, a multiple the program states, or
% an unknown one.
weighed_rows(multiple, N) => K::integer(4, 32), N = 64*K.
weighed_rows(unknown, N) => N::integer(256, 2048).
weighed_rows(Size, N) => N = Size.

test(softmax_before_its_product_is_one_chain, [timeout(60), forall(member(Size, [896, 891, multiple, unknown]))]) :-
   grouped(Opts),
   weighed_rows(Size, N),
   weighed(N, 64, _, _, O),
   kernels(O, Opts, [K1, K2]),
   softmax_chain(K1, Sum),
   kernel{kind: items, stage: stage(_, _, _), pre: [_], post: [_ := _ / Sum1[_, _]]} :< K2,
   Sum1 == Sum.

% Rows of 64 at the least are no group's worth with 8 elements a lane of 32, the default, and
% one with 2, the option of a device of warps, see compile:device_options/2: the size of a
% group is decided at the least value of an unknown extent, for every value.
test(short_rows_are_a_chain_with_two_elements_a_lane, [timeout(60)]) :-
   grouped(Opts),
   weighed(64*K, 64, _, _, O), K::integer(1, 32),
   kernels(O, Opts, Ks0),
   \+ ( member(K0, Ks0), get_dict(kind, K0, groups) ),
   kernels(O, [share(2) | Opts], [K1, K2]),
   softmax_chain(K1, _),
   kernel{kind: groups, local: 32} :< K1,
   kernel{kind: items, pre: [_], post: [_]} :< K2.

test(warps_take_two_elements_a_lane, [timeout(60), forall(test_device(_, Dev))]) :-
   device_options(Dev, Opts),
   cl_device_info(Dev, local_mem_type, Type),
   memberchk(share(S), Opts),
   ( Type == local -> S == 2 ; S == 8 ).

% With threads the boxes stay in the program's order, see compile:ahead/2: the sum after the
% product, no chain of the three, and the kernels those of the reductions apart.
test(softmax_stays_in_program_order_with_threads, [timeout(60)]) :-
   packed(Opts),
   weighed_rows(multiple, N),
   weighed(N, 64, _, _, O),
   kernels(O, Opts, Ks),
   \+ ( member(K, Ks), get_dict(kind, K, groups) ),
   once(( nth0(I, Ks, K1), get_dict(stage, K1, pack(_, _, _, _, _, _)) )),
   once(( nth0(J, Ks, K2), get_dict(box, K2, over(_, [P := P1 + _[_, _]])), P == P1 )),
   I < J.

% Two heads: the chain of the first takes the sum of its own exponentials alone; the
% initialisation of the second product, which a chain could take as any box over its rows,
% stays the second product's.
test(softmax_chain_leaves_the_next_product_whole, [timeout(60)]) :-
   grouped(Opts),
   weighed_rows(multiple, N),
   weighed(N, 64, S, _, O1),
   shape(V2, [N, 64]),
   Rows = [axis(-1), keepdims(true)],
   Ex @= exp(S*2 - max(S*2, Rows)),
   O2 @= (Ex @ V2) / sum(Ex, Rows),
   O @= concat([O1, O2], [axis(1)]),
   kernels(O, Opts, [K1, K2, K3, K4]),
   softmax_chain(K1, _), softmax_chain(K3, _),
   forall(member(K, [K2, K4]), kernel{stage: stage(_, _, _), pre: [_], post: [_]} :< K).

% A sum of the product itself is not computed before it: the product has no epilogue, and
% the division is a kernel after the sum.
test(sum_of_a_product_stays_after_it, [timeout(120), forall(test_device(D, _))]) :-
   grouped(Opts),
   shape(X, [72, 16]), shape(W, [16, 24]),
   Rows = [axis(-1), keepdims(true)],
   C @= X @ W,
   Y @= C / sum(C, Rows),
   kernels(Y, Opts, Ks),
   Ks = [K | _], kernel{pre: [_], post: []} :< K,
   last(Ks, Last), kernel{box: over(_, [_ := _ / _]), pre: [], post: []} :< Last,
   centred(1152, 13, Xs0), maplist([A, B]>>(B is A + 1), Xs0, Xs), centred(384, 11, Ws0), maplist([A, B]>>(B is A + 1), Ws0, Ws),
   eval(Y, [X-Xs, W-Ws], Ref), run(Y, [X-Xs, W-Ws], Out, [device(D)]),
   near(Ref, Out).

% weighed_matches(+D, +O, +S, +V, +N, +M): the weighed values run on D at N rows are the
% reference's, to the precision of a float; the scores are spread wide enough for the
% exponentials to span a float's range.
weighed_matches(D, O, S, V, N, M) :-
   NS is N*N, NV is N*M,
   centred(NS, 13, Ss0), maplist([X, Y]>>(Y is X*40), Ss0, Ss), centred(NV, 11, Vs),
   eval(O, [S-Ss, V-Vs], Ref),
   run(O, [S-Ss, V-Vs], Out, [device(D)]),
   maplist([X, Y]>>(abs(X - Y) < 1.0e-5), Ref, Out).

test(weighed_softmax_at_sizes_no_tile_divides, [timeout(300), forall(( test_device(D, _), test_size(D, gpu, [9, 67, 131], [67], N) ))]) :-
   weighed(N, 24, S, V, O),
   weighed_matches(D, O, S, V, N, 24).

test(weighed_softmax_at_unknown_sizes, [timeout(300), forall(test_device(D, _))]) :-
   weighed(N, 24, S, V, O), N::integer(64, 512),
   forall(member(Rows, [64, 131, 257]), weighed_matches(D, O, S, V, Rows, 24)),
   var(N).

test(weighed_softmax_at_a_symbolic_multiple, [timeout(300), forall(test_device(D, _))]) :-
   weighed(64*K, 24, S, V, O), K::integer(1, 8),
   forall(member(Rows, [64, 320]), weighed_matches(D, O, S, V, Rows, 24)),
   var(K).

% The weights first: the program has the sum before the product, the chain is the program's
% order on every device, with threads too, and the exponentials are written and summed in
% one phase, see compile:stored/2.
weights_first(N, M, S, V, O) :-
   shape(S, [N, N]), shape(V, [N, M]),
   Rows = [axis(-1), keepdims(true)],
   Ex @= exp(S - max(S, Rows)),
   O @= (1 / sum(Ex, Rows)) * (Ex @ V).

% stored_sum(+Ks): a kernel of Ks writes the exponentials and sums them in one phase.
stored_sum(Ks) :-
   member(K, Ks),
   get_dict(phases, K, Phases),
   member(reduce(_, [red(_, _, +, Ex1[_, _])], [Ex[_, _] := exp(_)]), Phases),
   Ex1 == Ex,
   !.

test(exponentials_are_summed_as_they_are_written, [timeout(300), forall(( test_device(D, Dev), test_size(D, [cpu, gpu], [67, 131, 256], [131], N) ))]) :-
   device_options(Dev, Opts),
   weights_first(N, 24, S, V, O),
   kernels(O, Opts, Ks),
   stored_sum(Ks),
   weighed_matches(D, O, S, V, N, 24).

test(exponentials_are_summed_as_they_are_written_at_unknown_sizes, [timeout(300), forall(test_device(D, Dev))]) :-
   device_options(Dev, Opts),
   weights_first(N, 24, S, V, O), N::integer(64, 512),
   kernels(O, Opts, Ks),
   stored_sum(Ks),
   forall(member(Rows, [64, 131, 257]), weighed_matches(D, O, S, V, Rows, 24)),
   var(N).

% A sum reading the exponentials at other places than the one an item writes, each with its
% mirror in the row, is a phase after theirs.
test(sum_of_mirrored_exponentials_is_a_phase_apart, [timeout(300), forall(test_device(D, _))]) :-
   N = 72,
   shape(S, [N, N]), shape(V, [N, 24]), shape(Z, [N, 1]),
   Rows = [axis(-1), keepdims(true)],
   Ex @= exp(S - max(S, Rows)),
   C @= Ex @ V,
   over([I:N], [Z[I, 0] := 0]),
   over([I:N, K:N], [Z[I, 0] := Z[I, 0] + Ex[I, K] * Ex[I, N - 1 - K]]),
   O @= C / Z,
   grouped(Opts),
   kernels(O, [share(1) | Opts], [K1 | _]),
   kernel{kind: groups, phases: [serial(_), reduce(_, _), spread(_, _, _), serial(_), reduce(_, [red(Z1, _, +, _ * _)])]} :< K1,
   Z1 == Z,
   NS is N*N, NV is N*24,
   centred(NS, 13, Ss), centred(NV, 11, Vs),
   eval(O, [S-Ss, V-Vs], Ref),
   run(O, [S-Ss, V-Vs], Out, [device(D)]),
   near(Ref, Out).

:- end_tests(compile_tiles).
