:- module(api_tests, []).

:- use_module(library(array)).
:- use_module(library(array/api)).
:- use_module(library(array/opencl), [opencl_device/2]).
:- use_module(test_devices, [test_device/2]).
:- use_module(library(array/compile), [kernels/3]).
:- use_module(library(clpBNR), [{}/1, (::)/2, op(700, xfx, ::)]).

% The functional overlay by @=: expressions build boxes, which eval/3 and run/4 then run.

near(Xs, Ys) :-
   maplist([X, Y]>>( X =:= Y -> true ; abs(X - Y) < 1.0e-5 * (1 + abs(X)) ), Xs, Ys).

% ramp(+N, +M, -Vs): N floats, the I-th I mod M, from 1.
ramp(N, M, Vs) :-
   numlist(1, N, Is),
   maplist({M}/[I, V]>>(V is float(I mod M)), Is, Vs).

% softmax(+X, -Y): the rows of X normalised, written as the standard writes it.
softmax(X, Y) :-
   E @= exp(X - max(X, [axis(1), keepdims(true)])),
   Y @= E / sum(E, [axis(1), keepdims(true)]).

% Reference values by plain Prolog.
softmax_rows(Rows, Out) :-
   maplist([Row, Ys]>>( max_list(Row, M), maplist([V, W]>>(W is exp(V - M)), Row, Ws),
                         sum_list(Ws, S), maplist([W, Y]>>(Y is W / S), Ws, Ys) ),
           Rows, Out).

:- begin_tests(api).

test(add_broadcasts_a_row, [timeout(60), true(Vs == [11.0, 22.0, 13.0, 24.0])]) :-
   shape(A, [2, 2]), shape(B, [2]),
   C @= A + B,
   shape(C, S), S == [2, 2],
   eval(C, [A-[1, 2, 3, 4], B-[10, 20]], Vs).

test(scalar_and_nested_expression, [timeout(60), true(Vs == [1.0, 3.0, 5.0])]) :-
   shape(A, [3]),
   C @= 2 * A - 1,
   eval(C, [A-[1, 2, 3]], Vs).

test(numbers_alone_are_a_number, [timeout(10), true(V =:= 7)]) :-
   V @= 2 * 3 + 1.

test(named_functions_are_the_operators, [timeout(60), true(Vs == [4.0, 6.0])]) :-
   shape(A, [2]), shape(B, [2]),
   C @= add(multiply(A, 2), B),
   eval(C, [A-[1, 2], B-[2, 2]], Vs).

test(shapes_that_do_not_broadcast_are_an_error, [timeout(10), error(domain_error(broadcastable_shapes, _))]) :-
   shape(A, [2]), shape(B, [3]),
   _ @= A + B.

% A name an over/2 defines over a product extent broadcasts with the names declared of it.
test(a_name_over_a_product_extent_broadcasts, [timeout(60), true(Vs == Expected)]) :-
   K::integer(1, 4), N = 4*K,
   shape(B, [N]),
   over([I:N, J:2], [X[I, J] := I + J]),
   over([I:N], [Y[I] := I * 2]),
   C @= sum(X, [axis(1)]) + B + Y,
   shape(C, S), S == [N],
   numlist(1, 8, Bs),
   eval(C, [B-Bs], Vs),
   numlist(0, 7, Is),
   maplist([I1, B1, V]>>(V is float(2*I1 + 1 + B1 + 2*I1)), Is, Bs, Expected).

test(unknown_expression_is_an_error, [timeout(10), error(type_error(array_expression, _))]) :-
   shape(A, [2]),
   _ @= foo(A).

test(sum_over_all_and_one_axis, [timeout(60)]) :-
   shape(A, [2, 3]),
   S @= sum(A),
   shape(S, Ss), Ss == [],
   R @= sum(A, [axis(1)]),
   shape(R, Sr), Sr == [2],
   K @= sum(A, [axis(0), keepdims(true)]),
   shape(K, Sk), Sk == [1, 3],
   L @= sum(A, [axis(-1)]),
   Data = [A-[1, 2, 3, 4, 5, 6]],
   eval(S, Data, [21.0]),
   eval(R, Data, [6.0, 15.0]),
   eval(K, Data, [5.0, 7.0, 9.0]),
   eval(L, Data, [6.0, 15.0]).

test(max_min_and_mean_keep_the_kind, [timeout(60)]) :-
   shape(A, [2, 2]), kind(A, int),
   M @= max(A, [axis(0)]),
   label_kinds([M]), kind(M, Km), Km == int,
   N @= min(A),
   Mean @= mean(A, [axis(1)]),
   eval(M, [A-[1, 4, 3, 2]], [3, 4]),
   eval(N, [A-[1, 4, 3, 2]], [1]),
   eval(Mean, [A-[1, 4, 3, 2]], Vs), near(Vs, [2.5, 2.5]).

test(matmul_two_by_three, [timeout(60), true(Vs == [4.0, 5.0, 10.0, 11.0])]) :-
   shape(A, [2, 3]), shape(B, [3, 2]),
   C @= A @ B,
   shape(C, S), S == [2, 2],
   eval(C, [A-[1, 2, 3, 4, 5, 6], B-[1, 0, 0, 1, 1, 1]], Vs).

test(matmul_broadcasts_the_batch, [timeout(60), true(Vs == [1.0, 2.0, 3.0, 4.0, 2.0, 4.0, 6.0, 8.0])]) :-
   shape(A, [2, 2, 2]), shape(B, [2, 2]),
   C @= matmul(A, B),
   shape(C, S), S == [2, 2, 2],
   eval(C, [A-[1, 0, 0, 1, 2, 0, 0, 2], B-[1, 2, 3, 4]], Vs).

test(creation, [timeout(60)]) :-
   Z @= zeros([2, 2]) + ones([2]) + full([1], 2),
   label_kinds([Z]), kind(Z, K), K == float,
   eval(Z, [], [3.0, 3.0, 3.0, 3.0]).

test(symbolic_extent_stays_one_program, [timeout(60)]) :-
   shape(A, [N, 3]),
   C @= A * 2.0 + A,
   shape(C, S), S == [N, 3],
   eval(C, [A-[1, 2, 3, 4, 5, 6]], Vs), Vs == [3.0, 6.0, 9.0, 12.0, 15.0, 18.0],
   var(N).

test(softmax_by_the_standard, [timeout(60)]) :-
   shape(X, [2, 3]),
   softmax(X, Y),
   Rows = [[1, 2, 3], [1, 1, 1]],
   append(Rows, Flat),
   eval(Y, [X-Flat], Vs),
   softmax_rows(Rows, Ref), append(Ref, RefFlat),
   near(Vs, RefFlat).

test(softmax_runs_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(X, [N, 4]),
   softmax(X, Y),
   numlist(1, 32, L), maplist([I, V]>>(V is sin(I)), L, Flat),
   Rows = [[1, 2, 3, 4], [1, 1, 1, 1]], once(append(Rows, Check)),
   eval(Y, [X-Check], Ref0), softmax_rows(Rows, Ref1), once(append(Ref1, Ref2)), near(Ref0, Ref2),
   eval(Y, [X-Flat], Ref),
   run(Y, [X-Flat], Vs, [device(D)]),
   near(Vs, Ref),
   var(N).

test(comparisons_are_bools_and_where_selects, [timeout(60)]) :-
   shape(A, [4]),
   B @= A > 2,
   label_kinds([B]), kind(B, Kb), Kb == bool,
   Data = [A-[1, 2, 3, 4]],
   eval(B, Data, [0, 0, 1, 1]),
   C @= greater_equal(A, 2) =\= (A =:= 3),
   eval(C, Data, [0, 1, 0, 1]),
   L @= less(A, 3), eval(L, Data, [1, 1, 0, 0]),
   Le @= A =< 1, eval(Le, Data, [1, 0, 0, 0]),
   Ne @= not_equal(A, 2), eval(Ne, Data, [1, 0, 1, 1]),
   W @= where(A > 2, A, 0),
   label_kinds([W]), kind(W, Kw), Kw == float,
   eval(W, Data, [0.0, 0.0, 3.0, 4.0]),
   R @= where(A =\= 2, A * 10, -A),
   eval(R, Data, [10.0, -2.0, 30.0, 40.0]).

test(logical_functions_stay_bools, [timeout(60)]) :-
   shape(A, [4]), shape(B, [4]),
   P @= logical_and(A > 1, B > 1),
   Q @= logical_or(A > 3, B > 3),
   X @= logical_xor(A > 2, B > 2),
   N @= logical_not(A > 2),
   label_kinds([P, Q, X, N]),
   maplist([V]>>(kind(V, K), K == bool), [P, Q, X, N]),
   Data = [A-[1, 2, 3, 4], B-[4, 3, 2, 1]],
   eval(P, Data, [0, 1, 1, 0]),
   eval(Q, Data, [1, 0, 0, 1]),
   eval(X, Data, [1, 1, 1, 1]),
   eval(N, Data, [1, 1, 0, 0]).

test(comparisons_of_numbers_alone_are_bits, [timeout(10)]) :-
   X @= 3 > 2, X == 1,
   Y @= 2 >= 3, Y == 0,
   Z @= where(1 < 2, 5, 6), Z == 5,
   W @= 2 =\= 2, W == 0.

test(where_broadcasts_its_three_operands, [timeout(60)]) :-
   shape(A, [2, 2]), shape(M, [2]),
   Y @= where(M, A, -1),
   shape(Y, S), S == [2, 2],
   eval(Y, [A-[1, 2, 3, 4], M-[1, 0]], [1.0, -1.0, 3.0, -1.0]).

test(relu_and_hinge_run_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(X, [N, 3]),
   Y @= where(X > 0, X, 0) + where(X >= 2, 1, 0) * where(X =\= 3, 10, 0),
   Data = [X-[-1, 0, 1, 2, 3, 4]],
   eval(Y, Data, Ref),
   Ref == [0.0, 0.0, 1.0, 12.0, 3.0, 14.0],
   run(Y, Data, Vs, [device(D)]),
   Vs == Ref,
   var(N).

% Indexing. A is a 3x4 of 1..12.
a34(A) :- shape(A, [3, 4]).
a34_data(A, [A-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]).

test(integer_index_drops_the_axis_and_a_slice_keeps_it, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   Y @= A[1, 1:3],
   shape(Y, S), S == [2],
   eval(Y, Data, [6.0, 7.0]).

test(negative_index_and_whole_axis, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   Y @= A[-1, _],
   shape(Y, S), S == [4],
   eval(Y, Data, [9.0, 10.0, 11.0, 12.0]).

test(strided_and_reversed_slices, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   Y @= A[0, _:_:2],
   shape(Y, Sy), Sy == [2],
   eval(Y, Data, [1.0, 3.0]),
   Z @= A[1, _:_:(-1)],
   eval(Z, Data, [8.0, 7.0, 6.0, 5.0]),
   W @= A[2, 3:0:(-2)],
   shape(W, Sw), Sw == [2],
   eval(W, Data, [12.0, 10.0]),
   V @= A[-2:_, -1],
   eval(V, Data, [8.0, 12.0]).

test(new_axis_and_ellipsis, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   Y @= A[..., new],
   shape(Y, Sy), Sy == [3, 4, 1],
   Z @= A[new, ..., 0],
   shape(Z, Sz), Sz == [1, 3],
   eval(Z, Data, [1.0, 5.0, 9.0]),
   W @= A[...],
   shape(W, Sw), Sw == [3, 4].

test(one_element_is_a_rank_zero_name, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   Y @= A[1, 2],
   shape(Y, S), S == [],
   eval(Y, Data, [7.0]),
   Z @= A[1, 2] + A[0, 0],
   eval(Z, Data, [8.0]).

test(indices_chain_and_apply_to_expressions, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   Y @= A[0][1],
   eval(Y, Data, [2.0]),
   X @= A[2],
   shape(X, Sx), Sx == [4],
   Z @= (A * 2)[-1, 0:2],
   eval(Z, Data, [18.0, 20.0]).

test(gather_by_an_int_name, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   shape(I, [2]), kind(I, int), elements(I, 0-2),
   Y @= A[I, _],
   shape(Y, Sy), Sy == [2, 4],
   eval(Y, [I-[2, 0] | Data], [9.0, 10.0, 11.0, 12.0, 1.0, 2.0, 3.0, 4.0]),
   shape(J, [2]), kind(J, int), elements(J, 0-3),
   Z @= A[I, J],
   shape(Z, Sz), Sz == [2],
   eval(Z, [I-[2, 0], J-[1, 3] | Data], [10.0, 4.0]).

test(gathers_broadcast_together_in_place_of_the_first, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   shape(I, [2, 1]), kind(I, int), elements(I, 0-2),
   shape(J, [3]), kind(J, int), elements(J, 0-3),
   Y @= A[I, J],
   shape(Y, Sy), Sy == [2, 3],
   eval(Y, [I-[1, 2], J-[0, 2, 3] | Data], [5.0, 7.0, 8.0, 9.0, 11.0, 12.0]).

test(take_and_take_along_axis, [timeout(60)]) :-
   a34(A), a34_data(A, Data),
   shape(I, [2]), kind(I, int), elements(I, 0-3),
   Y @= take(A, I, [axis(1)]),
   shape(Y, Sy), Sy == [3, 2],
   eval(Y, [I-[3, 0] | Data], [4.0, 1.0, 8.0, 5.0, 12.0, 9.0]),
   shape(J, [3, 1]), kind(J, int), elements(J, 0-3),
   Z @= take_along_axis(A, J),
   shape(Z, Sz), Sz == [3, 1],
   eval(Z, [J-[0, 1, 2] | Data], [1.0, 6.0, 11.0]),
   shape(K, [1, 4]), kind(K, int), elements(K, 0-2),
   W @= take_along_axis(A, K, [axis(0)]),
   shape(W, Sw), Sw == [1, 4],
   eval(W, [K-[2, 1, 0, 2] | Data], [9.0, 6.0, 3.0, 12.0]).

test(indexing_a_symbolic_extent_stays_one_program, [timeout(60)]) :-
   shape(A, [N, 4]),
   Y @= A[1:_, -1],
   shape(Y, [L]), \+ ground(L),
   eval(Y, [A-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]], [8.0, 12.0]),
   eval(Y, [A-[1, 2, 3, 4, 5, 6, 7, 8]], [8.0]),
   Z @= A[_:_:2, 0],
   eval(Z, [A-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]], [1.0, 9.0]),
   var(N).

test(index_out_of_the_extent_is_an_error, [timeout(10), error(domain_error(in_bounds, _))]) :-
   shape(A, [3]),
   _ @= A[5].

test(slice_past_the_extent_is_an_error, [timeout(10), error(domain_error(in_bounds, _))]) :-
   shape(A, [3]),
   _ @= A[1:5].

test(too_many_indices_is_an_error, [timeout(10), error(domain_error(rank(1), _))]) :-
   shape(A, [3]),
   _ @= A[0, 0].

test(two_ellipses_are_an_error, [timeout(10), error(domain_error(one_ellipsis, _))]) :-
   shape(A, [3, 3]),
   _ @= A[..., ...].

test(gather_and_slice_run_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(A, [N, 4]), shape(I, [2]), kind(I, int), elements(I, 0-2),
   Y @= A[I, 1:_:2] * 2 - A[0, new, _:_:(-2)],
   Data = [A-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12], I-[2, 0]],
   eval(Y, Data, Ref),
   Ref == [16.0, 22.0, 0.0, 6.0],
   run(Y, Data, Vs, [device(D)]),
   Vs == Ref,
   var(N).

test(a_slice_fuses_into_its_consumer, [timeout(60)]) :-
   shape(A, [8, 8]),
   Y @= exp(A[1:5, _:_:2]) + A[0:4, 0:4],
   kernels(Y, [], Ks),
   length(Ks, Count),
   Count == 1.

test(trigonometry_abs_and_pow, [timeout(60)]) :-
   shape(X, [3]),
   Y @= sin(X) + cos(X) * 2 + tan(X) / 10 + abs(X - 1) + X ** 2 + pow(2, X),
   Data = [X-[0.5, -2.0, 3.0]],
   maplist([V, R]>>(R is sin(V) + cos(V)*2 + tan(V)/10 + abs(V - 1) + V**2 + 2**V), [0.5, -2.0, 3.0], Expected),
   eval(Y, Data, Vs), near(Vs, Expected),
   shape(I, [2]), kind(I, int), J @= abs(I - 3),
   label_kinds([J]), kind(J, Kj), Kj == int,
   eval(J, [I-[1, 5]], [2, 2]),
   W @= abs(-3) + 2 ** 3, W =:= 11.

% erf is a primitive: the exact GELU, 0.5 x (1 + erf(x / sqrt 2)), is one kernel, and an erf
% of numbers alone is a number.
test(erf_and_the_exact_gelu, [timeout(60)]) :-
   shape(X, [5]),
   E @= erf(X),
   kind(E, K), K == float,
   Xs = [-3.0, -0.5, 0.0, 0.5, 3.0],
   maplist([V, R]>>(R is erf(V)), Xs, Expected),
   eval(E, [X-Xs], Vs), near(Vs, Expected),
   G @= 0.5 * X * (1 + erf(X / sqrt(2))),
   maplist([V, R]>>(R is 0.5 * V * (1 + erf(V / sqrt(2)))), Xs, Gelu),
   eval(G, [X-Xs], Gs), near(Gs, Gelu),
   kernels(G, [], Ks), length(Ks, Count), Count == 1,
   W @= erf(0.5), W =:= erf(0.5).

% A row longer than a vector and its tail, and both tails of erf, where it rounds to -1 and 1.
test(erf_runs_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(X, [N, 37]),
   Y @= 0.5 * X * (1 + erf(X / sqrt(2))) + erf(X),
   numlist(1, 74, Is), maplist([I, V]>>(V is (I - 37.5) / 6), Is, Xs),
   Data = [X-Xs],
   eval(Y, Data, Ref),
   run(Y, Data, Vs, [device(D)]),
   maplist([V, R]>>(abs(V - R) < 1.0e-5 * (1 + abs(R))), Vs, Ref),
   var(N).

% Creation and manipulation: constants of the program, ranges, and names joined, stacked and
% transposed; an int constant indexed keeps its range, so that it gathers.
test(asarray_arange_eye, [timeout(60)]) :-
   A @= asarray([[1, 2], [3, 4]]),
   shape(A, Sa), Sa == [2, 2], label_kinds([A]), kind(A, Ka), Ka == int,
   eval(A, [], [1, 2, 3, 4]),
   F @= asarray([1.5, 2]), eval(F, [], [1.5, 2.0]),
   R @= arange(5), eval(R, [], [0, 1, 2, 3, 4]),
   S @= arange(1, 2.5, 0.5), eval(S, [], [1.0, 1.5, 2.0]),
   D @= arange(3, 0, -1), eval(D, [], [3, 2, 1]),
   E @= eye(2, 3), eval(E, [], [1.0, 0.0, 0.0, 0.0, 1.0, 0.0]),
   shape(X, [4]), I @= arange(1, 3), Y @= X[I], eval(Y, [X-[5, 6, 7, 8]], [6.0, 7.0]).

test(concat_and_stack, [timeout(60)]) :-
   shape(A, [2, 2]), shape(B, [2, 1]),
   C @= concat([A, B], [axis(1)]),
   shape(C, Sc), Sc == [2, 3],
   eval(C, [A-[1, 2, 3, 4], B-[5, 6]], [1.0, 2.0, 5.0, 3.0, 4.0, 6.0]),
   D @= concat([A, A]), shape(D, Sd), Sd == [4, 2],
   shape(P, [N, 2]), shape(Q, [N, 2]), R @= concat([P, Q]), shape(R, [T, 2]), \+ ground(T),
   eval(R, [P-[1, 2], Q-[3, 4]], [1.0, 2.0, 3.0, 4.0]), var(N),
   shape(U, [2]), shape(V, [2]),
   W @= stack([U, V], [axis(1)]), shape(W, Sw), Sw == [2, 2],
   eval(W, [U-[1, 2], V-[3, 4]], [1.0, 3.0, 2.0, 4.0]),
   Z @= stack([U, V]), eval(Z, [U-[1, 2], V-[3, 4]], [1.0, 2.0, 3.0, 4.0]).

% A concat along axis 1 of two products of 64 columns: the parts are epilogues of the one
% reduction, each writing its own slice of the output, which is no register tile of the
% reduction's: found by examples/detector.pl.
test(concat_of_two_wide_products, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [3, 64]), shape(W, [64, 64]),
   A @= X @ W, B @= X @ W * 2,
   C @= concat([A, B], [axis(1)]),
   ramp(192, 7, Xs), ramp(4096, 5, Ws),
   eval(C, [X-Xs, W-Ws], Ref),
   run(C, [X-Xs, W-Ws], Out, [device(D)]),
   Ref == Out.

% A bound on a symbolic extent decides the schedule, never the values: the rows declared 64
% at least, the parts along the columns, a known axis, and along the rows, where the second
% part starts at the symbolic extent.
test(concat_of_products_over_a_bounded_extent, [timeout(120), forall(( test_device(D, _), member(Axis, [0, 1]) ))]) :-
   shape(X, [N, 64]), shape(W, [64, 64]), {N >= 64},
   A @= X @ W, B @= X @ W * 2,
   C @= concat([A, B], [axis(Axis)]),
   ramp(6144, 7, Xs), ramp(4096, 5, Ws),
   eval(C, [X-Xs, W-Ws], Ref),
   run(C, [X-Xs, W-Ws], Out, [device(D)]),
   Ref == Out,
   var(N).

% The second part of a concat of two different products is a kernel of its own, its place at
% an offset: its register tile is indexed by the tile, not by the place.
test(concat_of_two_different_products, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [16, 64]), shape(W, [64, 64]), shape(V, [64, 64]),
   A @= X @ W, B @= X @ V,
   C @= concat([A, B], [axis(1)]),
   ramp(1024, 7, Xs), ramp(4096, 5, Ws), ramp(4096, 3, Vs),
   Data = [X-Xs, W-Ws, V-Vs],
   eval(C, Data, Ref),
   run(C, Data, Out, [device(D)]),
   Ref == Out.

% An epilogue writing the product at another place than the reduction's own: transposed, or
% stacked along a new last axis, each element beside its double.
test(transpose_and_stack_of_wide_products, [timeout(120), forall(test_device(D, _))]) :-
   shape(X, [96, 64]), shape(W, [64, 64]),
   T @= permute_dims(X @ W, [1, 0]),
   S @= stack([X @ W, X @ W * 2], [axis(2)]),
   ramp(6144, 7, Xs), ramp(4096, 5, Ws),
   Data = [X-Xs, W-Ws],
   eval(T, Data, RefT), run(T, Data, OutT, [device(D)]), RefT == OutT,
   eval(S, Data, RefS), run(S, Data, OutS, [device(D)]), RefS == OutS.

test(broadcast_to_stretches_the_ones, [timeout(60)]) :-
   shape(A, [2, 1]), shape(C, [N, 3]),
   B @= broadcast_to(A, [2, 3]),
   shape(B, Sb), Sb == [2, 3],
   eval(B, [A-[1, 2]], [1.0, 1.0, 1.0, 2.0, 2.0, 2.0]),
   D @= broadcast_to(C, [N, 3]), D == C,
   E @= broadcast_to(5, [2]), eval(E, [], [5, 5]),
   catch(( _ @= broadcast_to(A, [3, 2]), fail ), error(domain_error(broadcastable_to(_), _), _), true).

% vecdot sums A * B along one axis, the last by default, the others broadcast; the axis has
% one extent in both, which does not stretch; a symbolic extent takes the other's.
test(vecdot, [timeout(60)]) :-
   shape(A, [2, 3]), shape(B, [3]), Data = [A-[1, 2, 3, 4, 5, 6], B-[1, 0, 2]],
   V @= vecdot(A, B), shape(V, Sv), Sv == [2], eval(V, Data, [7.0, 16.0]),
   shape(C, [2, 3]), W @= vecdot(A, C, [axis(0)]), shape(W, Sw), Sw == [3],
   eval(W, [A-[1, 2, 3, 4, 5, 6], C-[1, 1, 1, 2, 2, 2]], [9.0, 12.0, 15.0]),
   shape(X, [N]), shape(Y, [4]), _ @= vecdot(X, Y), N == 4,
   G @= grad(sum(vecdot(A, B)), B), eval(G, Data, [5.0, 7.0, 9.0]),
   shape(P, [3, 1]),
   catch(( _ @= vecdot(A, P, [axis(0)]), fail ), error(domain_error(same_extent_along(0), _), _), true),
   shape(Q, [2, 4]),
   catch(( _ @= vecdot(A, Q), fail ), error(domain_error(same_extent_along(-1), _), _), true).

% tril keeps the elements on and below the diagonal of the last two axes, triu on and above,
% k(K) the K-th diagonal, positive above; an int keeps its range with 0; a vector is no
% matrix.
test(tril_and_triu, [timeout(60)]) :-
   shape(A, [3, 3]), Data = [A-[1, 2, 3, 4, 5, 6, 7, 8, 9]],
   L @= tril(A), eval(L, Data, [1.0, 0.0, 0.0, 4.0, 5.0, 0.0, 7.0, 8.0, 9.0]),
   U @= triu(A, [k(1)]), eval(U, Data, [0.0, 2.0, 3.0, 0.0, 0.0, 6.0, 0.0, 0.0, 0.0]),
   S @= tril(A, [k(-1)]), eval(S, Data, [0.0, 0.0, 0.0, 4.0, 0.0, 0.0, 7.0, 8.0, 0.0]),
   shape(B, [N, 2, 3]), V @= triu(B), shape(V, Sv), Sv == [N, 2, 3],
   eval(V, [B-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]], [1.0, 2.0, 3.0, 0.0, 5.0, 6.0, 7.0, 8.0, 9.0, 0.0, 11.0, 12.0]),
   I @= tril(asarray([[3, 4], [5, 6]])), label_kinds([I]), elements(I, R), R == 0-6,
   eval(I, [], [3, 0, 5, 6]), var(N),
   catch(( _ @= tril(asarray([1, 2])), fail ), error(domain_error(matrix, _), _), true).

% The variance is the mean squared deviation from the mean, along the axes of the options,
% the count less correction(C) dividing; the standard deviation its square root; the
% gradient of a variance 2 (X - mean) / N.
test(var_and_std, [timeout(60)]) :-
   shape(A, [2, 3]), Data = [A-[1, 2, 3, 4, 6, 8]],
   V @= var(A), shape(V, Sv), Sv == [], eval(V, Data, [V0]), near([V0], [5.666666666666667]),
   R @= var(A, [axis(1)]), eval(R, Data, Vr), near(Vr, [0.6666666666666666, 2.6666666666666665]),
   S @= std(A, [axis(0), keepdims(true), correction(1)]), shape(S, Ss), Ss == [1, 3],
   eval(S, Data, Vs), near(Vs, [2.1213203435596424, 2.8284271247461903, 3.5355339059327378]),
   G @= grad(sum(var(A, [axis(1)])), A), eval(G, Data, Vg),
   near(Vg, [-0.6666666666666666, 0.0, 0.6666666666666666, -1.3333333333333333, 0.0, 1.3333333333333333]).

test(var_runs_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(A, [B, 3]), V @= std(A, [axis(1)]),
   Data = [A-[1, 2, 3, 4, 6, 8]],
   eval(V, Data, Ref), run(V, Data, Vs, [device(D)]), near(Ref, Vs), var(B).

% A reshape keeps the elements row-major; its extents are a relation, an unknown one or -1
% solved, now or once the others are known; a size that differs is a domain error.
test(reshape_keeps_the_elements_row_major, [timeout(60)]) :-
   shape(A, [2, 3]), Data = [A-[1, 2, 3, 4, 5, 6]],
   B @= reshape(A, [3, 2]), shape(B, Sb), Sb == [3, 2], eval(B, Data, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]),
   C @= reshape(A, [-1]), shape(C, Sc), Sc == [6],
   D @= reshape(A, [N, 2]), N == 3,
   E @= reshape(A, [1, 3, 2, 1]), eval(E, Data, [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]),
   T @= reshape(permute_dims(A, [1, 0]), [6]), eval(T, Data, [1.0, 4.0, 2.0, 5.0, 3.0, 6.0]),
   shape(S, []), U @= reshape(S, [1, 1]), eval(U, [S-[7]], [7.0]),
   V @= reshape(U, []), shape(V, Sv), Sv == [], eval(V, [S-[7]], [7.0]),
   shape(D, _), shape(C, _),
   catch(( _ @= reshape(A, [4]), fail ), error(domain_error(reshapable_to([4]), _), _), true).

test(reshape_of_a_symbolic_extent, [timeout(60)]) :-
   shape(X, [N, 6]),
   Y @= reshape(X, [N, 2, 3]),
   Z @= reshape(permute_dims(Y, [0, 2, 1]), [N, -1]), shape(Z, [N1, M]),
   N1 == N, var(N), var(M),
   eval(Z, [X-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]], [1.0, 4.0, 2.0, 5.0, 3.0, 6.0, 7.0, 10.0, 8.0, 11.0, 9.0, 12.0]),
   var(N), var(M).

test(reshape_gradient_is_reshaped_back, [timeout(60)]) :-
   shape(X, [2, 3]), shape(W, [3, 2]),
   L @= sum(reshape(X, [3, 2]) * W),
   G @= grad(L, X), shape(G, Sg), Sg == [2, 3],
   eval(G, [X-[1, 2, 3, 4, 5, 6], W-[6, 5, 4, 3, 2, 1]], [6.0, 5.0, 4.0, 3.0, 2.0, 1.0]).

test(reshape_runs_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(A, [B, 2, 3]),
   R @= reshape(permute_dims(A, [0, 2, 1]), [B, 3, 2]),
   Data = [A-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]],
   eval(R, Data, Ref), run(R, Data, Vs, [device(D)]), Ref == Vs, var(B).

test(transpose_diagonal_and_gather_by_a_constant, [timeout(60)]) :-
   shape(A, [2, 2, 3]),
   T @= matrix_transpose(A), shape(T, St), St == [2, 3, 2],
   eval(T, [A-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]], [1.0, 4.0, 2.0, 5.0, 3.0, 6.0, 7.0, 10.0, 8.0, 11.0, 9.0, 12.0]),
   shape(B, [2, 3]), P @= permute_dims(B, [1, 0]), eval(P, [B-[1, 2, 3, 4, 5, 6]], [1.0, 4.0, 2.0, 5.0, 3.0, 6.0]),
   shape(C, [2, 2, 2]), D @= diagonal(C), shape(D, Sd), Sd == [2, 2],
   eval(D, [C-[1, 2, 3, 4, 5, 6, 7, 8]], [1.0, 4.0, 5.0, 8.0]),
   shape(W, [2, 3, 3]), I @= asarray([2, 0]),
   Z @= W[_, I[_, new], I[new, _]], shape(Z, Sz), Sz == [2, 2, 2],
   eval(Z, [W-[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18]], [9.0, 7.0, 3.0, 1.0, 18.0, 16.0, 12.0, 10.0]).

test(cholesky_and_inv, [timeout(60)]) :-
   shape(A, [2, 2]), L @= cholesky(A),
   eval(L, [A-[4, 2, 2, 3]], [L00, L01, L10, L11]),
   near([L00, L01, L10, L11], [2.0, 0.0, 1.0, 1.4142135623730951]),
   shape(M, [2, 2]), I @= inv(M), eval(I, [M-[4, 7, 2, 6]], Vi), near(Vi, [0.6, -0.7, -0.2, 0.4]),
   shape(B, [N, 3, 3]), J @= inv(B), P @= B @ J,
   eval(P, [B-[2, 1, 0, 1, 3, 1, 0, 1, 4, 1, 0, 0, 0, 2, 0, 0, 0, 4]], Vp),
   near(Vp, [1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 1]), var(N).

test(cholesky_and_inv_run_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(A, [B, 2, 2]), L @= cholesky(A), I @= inv(A),
   S @= stack([diagonal(L), diagonal(I)], [axis(1)]),
   Data = [A-[4, 2, 2, 3, 1, 0, 0, 1]],
   eval(S, Data, Ref), run(S, Data, Vs, [device(D)]), near(Vs, Ref), var(B).

% The index of the least or greatest element, into the array flattened or along an axis, the
% first of equals, with its range declared so that it gathers; and the integer division.
test(argmin_argmax_and_integer_division, [timeout(60)]) :-
   shape(A, [2, 3]),
   I @= argmin(A), shape(I, Si), Si == [],
   J @= argmax(A, [axis(1)]), shape(J, Sj), Sj == [2],
   K @= argmin(A, [axis(0), keepdims(true)]), shape(K, Sk), Sk == [1, 3],
   Data = [A-[3, 1, 1, 0, 5, 0]],
   eval(I, Data, [3]),
   eval(J, Data, [0, 1]),
   eval(K, Data, [1, 0, 1]),
   G @= A[arange(2), J], eval(G, Data, [3.0, 5.0]),
   shape(B, [N]), kind(B, int),
   Q @= floor_divide(B, 3), R @= remainder(B, 3),
   eval(Q, [B-[0, 1, 2, 3, 4, 5, 6]], [0, 0, 0, 1, 1, 1, 2]),
   eval(R, [B-[0, 1, 2, 3, 4, 5, 6]], [0, 1, 2, 0, 1, 2, 0]),
   M @= argmin(B), eval(M, [B-[4, 2, 2, 9]], [1]),
   var(N).

test(argmin_runs_on_every_device, [timeout(300), forall(test_device(D, _))]) :-
   shape(A, [2, 3]),
   I @= argmin(A),
   J @= argmax(A, [axis(1)]),
   Data = [A-[3, 1, 1, 0, 5, 0]],
   run(I, Data, [3], [device(D)]),
   run(J, Data, [0, 1], [device(D)]).

:- end_tests(api).
